LocalMusic.ets 541 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572
  1. import TitleBar from './TitleBar'
  2. import { curves, display, MenuModifier,PiPWindow, promptAction, router, SymbolGlyphModifier, window } from '@kit.ArkUI';
  3. import { VideoItem } from '../viewmodel/VideoItem';
  4. import { LengthMetrics, SegmentButton,SegmentButtonOptions } from '@kit.ArkUI';
  5. import { getWebdavVideoItems, getWebdavCurrentPlayIndex } from '../pages/WebDavMainPage';
  6. import { getNavidromeVideoItems, getNavidromeCurrentPlayIndex } from '../common/util/NavidromePlaylistStore';
  7. import {
  8. ButtonFancyModifier,
  9. ImageFancyModifier,
  10. ShadowModifier,
  11. SymbolGlyphFancyModifier } from '../common/util/AttributeModifierUtil'
  12. import {
  13. AppUtil,
  14. ArrayUtil,
  15. Base64Util,
  16. DateUtil,
  17. DeviceUtil,
  18. FileUtil,
  19. GlobalContext,
  20. LogUtil,
  21. MD5,
  22. PreferencesUtil,
  23. RandomUtil,
  24. StrUtil,
  25. ToastUtil
  26. } from '@pura/harmony-utils';
  27. import { imagePathToPixelMap } from '../common/util/CommUtils';
  28. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  29. import { CommonConstants } from '../common/constants/CommonConstants';
  30. import { BaiduConstants } from '../common/constants/BaiduConstants';
  31. import { EventConstants } from '../common/constants/EventConstants';
  32. import Logger from '../common/util/Logger';
  33. import { http } from '@kit.NetworkKit';
  34. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  35. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  36. import { BubbleBean } from '../viewmodel/BubbleBean';
  37. import { PopupPosition, XPopup } from '@chinalike/popup';
  38. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  39. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  40. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  41. import { MessageEvents, util, worker, ErrorEvent, JSON } from '@kit.ArkTS';
  42. import { Verify } from './Verify';
  43. import { taskpool } from '@kit.ArkTS';
  44. import { RotatingCover } from './RotatingCover';
  45. import { PlayConstants } from '../common/constants/PlayConstants';
  46. import { effectKit } from '@kit.ArkGraphics2D';
  47. import { ColorConversion } from '../common/util/ColorConversion';
  48. import { LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  49. import { AvSessionController } from '../controller/AvSessionController';
  50. import { repairAudioMetadata, convertDsfToWav, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  51. import { extractHwMediaMetadata, FFMpegTags,Utility } from '../common/util/Utility';
  52. import { TagsContentCover } from '../view/TagsContentCover';
  53. import {
  54. DeviceChangeReason,
  55. IjkMediaPlayer,
  56. InterruptEvent,
  57. InterruptHintType,
  58. LogUtils,
  59. OnBufferingUpdateListener,
  60. OnCompletionListener,
  61. OnErrorListener,
  62. OnInfoListener,
  63. OnPreparedListener,
  64. OnSeekCompleteListener,
  65. OnTimedTextListener,
  66. OnVideoSizeChangedListener
  67. } from '@ohos/ijkplayer';
  68. import { PlayStatus } from '../common/PlayStatus';
  69. import fs from '@ohos.file.fs';
  70. import { image } from '@kit.ImageKit';
  71. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  72. import { UniversalDetector } from '@ohos/juniversalchardet';
  73. import { SettingPage } from '../pages/SettingPage';
  74. import { secondToTime,getTransverterText } from '../common/util/CommUtils';
  75. import { CommonConstants2 } from '../common/util/CommonConstants2';
  76. import { hilog } from '@kit.PerformanceAnalysisKit';
  77. import { LazyDataSource } from '../common/util/LazyDataSource';
  78. import MediaTable from '../common/util/MediaTable';
  79. import FileDeletionWatcher from '../common/util/FileDeletionWatcher';
  80. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  81. import ImageUtils from '../common/util/ImageUtils';
  82. import { ringtone } from '@kit.RingtoneKit';
  83. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  84. import { resourceManager } from '@kit.LocalizationKit';
  85. import { deviceInfo } from '@kit.BasicServicesKit';
  86. import { RemoteCacheManager } from '../common/network/RemoteCacheManager';
  87. import '../common/network/RemoteCacheRegistry';
  88. import { RemoteCacheType, resolveCacheFilePath } from '../common/network/RemoteSongCache';
  89. import { findWebDavCacheIfExists, triggerWebDavCacheDownload } from '../common/network/WebDavFileCache';
  90. import { navidromeApi } from '../common/network/NavidromeApi';
  91. import { ServerLogUtil } from '../common/util/ServerLogUtil';
  92. import { ensureSmbFileStreaming, SmbStreamingMeta } from '../common/network/SmbFileCache';
  93. import { ensureBaiduFileCached } from '../common/network/BaiduFileCache';
  94. import FileManager from '../common/util/FileManager';
  95. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  96. import app from '@system.app';
  97. import { TextNodeController } from './PipLyricTextBuilder';
  98. import { IndexerView } from './IndexerView';
  99. import { KeyCode } from '@kit.InputKit';
  100. import { KnockController } from '../controller/KnockController';
  101. import { DeleteComptent } from '../view/DeleteComptent';
  102. import { ABLoopComptent } from '../view/ABLoopComptent';
  103. import { FixMessyView } from '../view/FixMessyView';
  104. import { parseCueFile,CueTrack,CueInfo } from '../common/util/CueUtils';
  105. import { CueComptent } from '../view/CueComptent';
  106. import PlaylistTable from '../common/util/PlaylistTable';
  107. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  108. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  109. import { convertPlaylistSongsToVideoItems, emptyView,updateAllSongsSortOrder } from '../pages/PlaylistDetailPage';
  110. import { Playlist, PlaylistSong } from '../viewmodel/Playlist';
  111. import { Song } from '../viewmodel/Song';
  112. import { SongType } from '../common/enums/SongType';
  113. import { RemoteDriveManager, WebDavAuthInfo as WebDavManagerAuthInfo,
  114. buildHttpHeadersWithWebDav,
  115. WebDavAuthItem} from '../common/util/RemoteDriveManager';
  116. import PermissionUtil from '../common/util/PermissionUtil'
  117. import { EditAudio, setRingTone } from './EditAudio';
  118. import { ExtractAccompaniment } from './ExtractAccompaniment';
  119. import { ExtractAudioFromVideo } from './ExtractAudioFromVideo';
  120. import { AudioFormatConverter } from './AudioFormatConverter';
  121. import { MergeAudio } from './MergeAudio';
  122. import { AIVoiceSeparation } from './AIVoiceSeparation';
  123. import { WebDavUrlUtil } from '../common/util/WebDavUrlUtil';
  124. import { ChangeTone } from './ChangeTone';
  125. import {
  126. hdsEffect,
  127. HdsVisualComponent,
  128. HdsSceneController,
  129. HdsSceneType,
  130. HdsVisualComponentAttribute,
  131. } from '@kit.UIDesignKit';
  132. import { GlobalAlphabetIndexerModifier } from '../Styels/GlobalStyles'
  133. import { getFirstLetter } from '../Constants';
  134. import { audio } from '@kit.AudioKit';
  135. const TAG = 'LocalMusic';
  136. const HICAR_LOG_TAG = 'HiCarWindow';
  137. function logHiCarWindow(message: string): void {
  138. void ServerLogUtil.info(HICAR_LOG_TAG, message);
  139. }
  140. /**
  141. * 歌单播放事件数据
  142. */
  143. interface PlaylistEventData {
  144. playlistId: string;
  145. playlistName: string;
  146. songCount: number;
  147. startIndex: number;
  148. songFilePaths: string[];
  149. isJump: boolean;
  150. webDavAuthInfo?: WebDavAuthItem; // 新增WebDAV认证信息
  151. }
  152. const DEFAULT_INDEX =
  153. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  154. 'X', 'Y', 'Z']
  155. //排序类型
  156. function getTypeOrder(type: number) {
  157. switch (type) {
  158. case CommonConstants.TYPE_IS_DIR:
  159. return 1; // First
  160. case CommonConstants.TYPE_IS_CSJAD:
  161. return 2; // Middle
  162. case CommonConstants.TYPE_LOCAL:
  163. return 3; // Last
  164. case CommonConstants.TYPE_WEBDAV:
  165. case CommonConstants.TYPE_SMB:
  166. case CommonConstants.TYPE_NAVIDROME:
  167. case CommonConstants.TYPE_FTP:
  168. case CommonConstants.TYPE_BAIDU:
  169. return 3;
  170. default:
  171. return 4; // Unknown types, if any, go last
  172. }
  173. }
  174. function isWebDavType(type: number): boolean {
  175. return type === CommonConstants.TYPE_WEBDAV;
  176. }
  177. function isSmbType(type: number): boolean {
  178. return type === CommonConstants.TYPE_SMB;
  179. }
  180. function isNavidromeType(type: number): boolean {
  181. return type === CommonConstants.TYPE_NAVIDROME;
  182. }
  183. function isFtpType(type: number): boolean {
  184. return type === CommonConstants.TYPE_FTP;
  185. }
  186. function isBaiduType(type: number): boolean {
  187. return type === CommonConstants.TYPE_BAIDU;
  188. }
  189. function isRemoteCloudType(type: number): boolean {
  190. return isWebDavType(type) || isSmbType(type) || isNavidromeType(type) || isFtpType(type) || isBaiduType(type);
  191. }
  192. function getShareNameFromFilePath(filePath?: string): string | undefined {
  193. if (!filePath) {
  194. return undefined;
  195. }
  196. const match = filePath.match(/^smb:\/\/[^/]+\/([^/]+)/i);
  197. return match && match[1] ? match[1] : undefined;
  198. }
  199. function removeSharePrefixFromPath(path: string, primaryShare?: string, secondaryShare?: string): string {
  200. const uniqueShares: string[] = [];
  201. [primaryShare, secondaryShare].forEach((name?: string) => {
  202. const cleaned = name ? name.replace(/^\/+|\/+$/g, '') : '';
  203. if (cleaned.length > 0 && !uniqueShares.some(item => item.toLowerCase() === cleaned.toLowerCase())) {
  204. uniqueShares.push(cleaned);
  205. }
  206. });
  207. if (uniqueShares.length === 0) {
  208. return path;
  209. }
  210. let result = path;
  211. for (let i = 0; i < uniqueShares.length; i++) {
  212. const share = uniqueShares[i];
  213. const lowerPath = result.toLowerCase();
  214. const lowerShare = share.toLowerCase();
  215. if (lowerPath === lowerShare) {
  216. result = '';
  217. break;
  218. }
  219. const prefix = `${lowerShare}/`;
  220. if (lowerPath.startsWith(prefix)) {
  221. result = result.substring(share.length + 1);
  222. break;
  223. }
  224. }
  225. return result;
  226. }
  227. function extractSmbRelativePath(song: VideoItem, shareNameOverride?: string): string {
  228. const shareFromFilePath = getShareNameFromFilePath(song.filePath);
  229. const shareName = shareNameOverride ?? shareFromFilePath;
  230. if (song.remote_rel_path && song.remote_rel_path.length > 0) {
  231. const cleaned = song.remote_rel_path.replace(/^\/+/, '');
  232. return removeSharePrefixFromPath(cleaned, shareName, shareFromFilePath);
  233. }
  234. if (!song.filePath) {
  235. return '';
  236. }
  237. const match = song.filePath.match(/^smb:\/\/[^/]+\/([^/]+)(\/.*)?$/i);
  238. if (!match) {
  239. return song.filePath.replace(/^\/+/, '');
  240. }
  241. const remainder = match[2] ? match[2].replace(/^\/+/, '') : '';
  242. if (remainder.length === 0) {
  243. return '';
  244. }
  245. return remainder;
  246. }
  247. function extractFtpRelativePath(song: VideoItem): string {
  248. if (song.remote_rel_path && song.remote_rel_path.length > 0) {
  249. return song.remote_rel_path.replace(/^\/+/, '');
  250. }
  251. if (!song.filePath) {
  252. return '';
  253. }
  254. const match = song.filePath.match(/^ftp:\/\/[^/]+(?::\d+)?(\/.*)$/i);
  255. if (match && match[1]) {
  256. return match[1].replace(/^\/+/, '');
  257. }
  258. return song.filePath.replace(/^\/+/, '');
  259. }
  260. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  261. interface MetadataExtractionOptions {
  262. context?: common.Context;
  263. autoParseMusicName?: boolean;
  264. }
  265. interface WorkerEditMusicResult {
  266. success: boolean;
  267. error?: string;
  268. coverResult?: boolean;
  269. needRefreshList?: boolean;
  270. metadataResult?: boolean;
  271. }
  272. interface LocalEditMusicPayload {
  273. context: Context;
  274. item: VideoItem;
  275. titleStr: string;
  276. artistStr: string;
  277. ablumStr: string;
  278. yearStr: string;
  279. genreStr: string;
  280. trackStr: string;
  281. albumArtistStr: string;
  282. composerStr: string;
  283. lyricistStr: string;
  284. commentStr: string;
  285. discStr: string;
  286. lyricConStr: string;
  287. imagePathStr: string;
  288. currentPath: string;
  289. packName: string;
  290. modeType: number;
  291. autoParseMusicName: boolean;
  292. }
  293. interface WorkerMetadataPayload {
  294. originFilePath: string;
  295. originId?: string;
  296. bit_rate?: string;
  297. duration?: string;
  298. sampleRate?: string;
  299. mimeType?: string;
  300. md5Str?: string;
  301. videoSize?: number;
  302. size?: string;
  303. pixelMapPath?: string;
  304. artist?: string;
  305. album?: string;
  306. name?: string;
  307. lyricContent?: string;
  308. bits_per_raw_sample?: string;
  309. channels?: string;
  310. channel_layout?: string;
  311. start_time?: string;
  312. genre?: string;
  313. year?: string;
  314. probe_score?: number;
  315. track?: string;
  316. disc?: string;
  317. ALBUMARTIST?: string;
  318. COMPOSER?: string;
  319. COMMENT?: string;
  320. LYRICIST?: string;
  321. nb_streams?: number;
  322. nb_programs?: number;
  323. error?: string;
  324. }
  325. interface WebDavMetadataUpdatePayload {
  326. filePath: string;
  327. pixelMapPath?: string;
  328. name?: string;
  329. artist?: string;
  330. }
  331. const metadataExtractionInFlight: Set<string> = new Set();
  332. const METADATA_RETRY_DELAY_MS = 1500;
  333. const METADATA_MAX_RETRY = 120;
  334. async function scheduleMetadataExtractionFromCache(
  335. song: VideoItem,
  336. cachePath: string,
  337. options?: MetadataExtractionOptions,
  338. expectedSize?: number,
  339. retryCount: number = 0
  340. ): Promise<void> {
  341. if (!song || !cachePath || !song.filePath || !options || !options.context) {
  342. return;
  343. }
  344. if (!isRemoteCloudType(song.type ?? -1)) {
  345. return;
  346. }
  347. if (metadataExtractionInFlight.has(song.filePath)) {
  348. return;
  349. }
  350. if (song.bit_rate && song.sampleRate && song.duration) {
  351. return;
  352. }
  353. const requiredSize = expectedSize && expectedSize > 0 ? expectedSize : undefined;
  354. try {
  355. const stat = await fileIo.stat(cachePath);
  356. const ready = requiredSize !== undefined ? stat.size >= requiredSize : stat.size > 0;
  357. if (!ready) {
  358. if (retryCount >= METADATA_MAX_RETRY) {
  359. Logger.warn(TAG, `缓存尚未完成,放弃解析: ${cachePath}`);
  360. return;
  361. }
  362. setTimeout(() => {
  363. void scheduleMetadataExtractionFromCache(song, cachePath, options, expectedSize, retryCount + 1);
  364. }, METADATA_RETRY_DELAY_MS);
  365. return;
  366. }
  367. } catch (error) {
  368. if (retryCount >= METADATA_MAX_RETRY) {
  369. Logger.warn(TAG, `无法读取缓存文件,放弃解析: ${(error as Error).message}`);
  370. return;
  371. }
  372. setTimeout(() => {
  373. void scheduleMetadataExtractionFromCache(song, cachePath, options, expectedSize, retryCount + 1);
  374. }, METADATA_RETRY_DELAY_MS);
  375. return;
  376. }
  377. metadataExtractionInFlight.add(song.filePath);
  378. workerInstance.postMessage({
  379. code: 5,
  380. data: options.context,
  381. data2: cachePath,
  382. data3: song.type,
  383. data4: {
  384. name: song.name,
  385. originFilePath: song.filePath,
  386. originId: song.id,
  387. autoParseMusicName: options.autoParseMusicName ?? false
  388. }
  389. });
  390. }
  391. function sanitizePlaybackUrl(rawUrl: string | null | undefined): string {
  392. if (!rawUrl) {
  393. return '';
  394. }
  395. try {
  396. const decoded = decodeURI(rawUrl);
  397. const encoded = encodeURI(decoded);
  398. // encodeURI 不会处理 #,手动转义避免播放器把剩余内容当作片段
  399. return encoded.replace(/#/g, '%23');
  400. } catch (error) {
  401. const err = error as Error;
  402. Logger.warn(TAG, `URL 编码失败,使用降级方案: ${err?.message}`);
  403. return rawUrl.replace(/ /g, '%20').replace(/#/g, '%23');
  404. }
  405. }
  406. function cloneVideoItem(item: VideoItem): VideoItem {
  407. const copy = new VideoItem(
  408. item.name,
  409. item.id,
  410. item.filePath,
  411. item.type,
  412. item.videoSize,
  413. item.cTime,
  414. item.size,
  415. item.pixelMapPath,
  416. item.artist,
  417. item.album,
  418. item.fileName,
  419. item.lastPlayed
  420. );
  421. copy.parentPath = item.parentPath;
  422. copy.isFav = item.isFav;
  423. copy.size = item.size;
  424. copy.pixelMapPath = item.pixelMapPath;
  425. copy.artist = item.artist;
  426. copy.album = item.album;
  427. copy.duration = item.duration;
  428. copy.mimeType = item.mimeType;
  429. copy.sampleRate = item.sampleRate;
  430. copy.trackCount = item.trackCount;
  431. copy.lastPlayedStr = item.lastPlayedStr;
  432. copy.playCount = item.playCount;
  433. copy.lyricContent = item.lyricContent;
  434. copy.md5Str = item.md5Str;
  435. copy.extra_json = item.extra_json;
  436. copy.pyStr = item.pyStr;
  437. copy.bit_rate = item.bit_rate;
  438. copy.probe_score = item.probe_score;
  439. copy.year = item.year;
  440. copy.nb_streams = item.nb_streams;
  441. copy.nb_programs = item.nb_programs;
  442. copy.genre = item.genre;
  443. copy.track = item.track;
  444. copy.bits_per_raw_sample = item.bits_per_raw_sample;
  445. copy.channels = item.channels;
  446. copy.channel_layout = item.channel_layout;
  447. copy.start_time = item.start_time;
  448. copy.ALBUMARTIST = item.ALBUMARTIST;
  449. copy.COMPOSER = item.COMPOSER;
  450. copy.LYRICIST = item.LYRICIST;
  451. copy.COMMENT = item.COMMENT;
  452. copy.disc = item.disc;
  453. copy.webdav_account_id = item.webdav_account_id;
  454. copy.remote_rel_path = item.remote_rel_path;
  455. return copy;
  456. }
  457. /**
  458. * 异步设置videoUrl的辅助方法,处理WebDAV URL的构建
  459. * @param song 歌曲对象
  460. * @returns Promise<string> 完整的URL
  461. */
  462. /**
  463. * 设置videoUrl,通过webdav_account_id设置完整的 URL
  464. * @param song 歌曲对象
  465. * @returns Promise<string> 完整的URL
  466. */
  467. async function setVideoUrlForSong(song: VideoItem, options?: MetadataExtractionOptions): Promise<string> {
  468. const metadataOptions = options ?? {};
  469. Logger.info(TAG, `setVideoUrlForSong start -> name=${song.name}, type=${song.type}, path=${song.filePath}, fsId=${song.baiduFsId || song.id}`);
  470. if (isWebDavType(song.type) && song.webdav_account_id) {
  471. try {
  472. Logger.info(TAG, `WebDAV 路径信息 remote_rel_path: ${song.remote_rel_path}`);
  473. Logger.info(TAG, `WebDAV 路径信息 filePath: ${song.filePath}`);
  474. const relativePath = song.remote_rel_path || song.filePath;
  475. const manager = RemoteDriveManager.getInstance();
  476. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  477. if (account) {
  478. const cachePath = await findWebDavCacheIfExists(account, relativePath);
  479. if (cachePath) {
  480. Logger.info(TAG, `WebDAV 缓存命中,直接播放: ${cachePath}`);
  481. void scheduleMetadataExtractionFromCache(song, cachePath, metadataOptions, song.videoSize);
  482. return cachePath;
  483. }
  484. const fullUrlFromAccount = WebDavUrlUtil.buildFullUrl(account, relativePath);
  485. if (fullUrlFromAccount) {
  486. const sanitizedUrl = sanitizePlaybackUrl(fullUrlFromAccount);
  487. const downloadPromise = triggerWebDavCacheDownload(account, relativePath, sanitizedUrl);
  488. if (downloadPromise) {
  489. downloadPromise.then((completedPath?: string | null) => {
  490. if (completedPath) {
  491. void scheduleMetadataExtractionFromCache(song, completedPath, metadataOptions, song.videoSize);
  492. }
  493. }).catch((error: Error) => {
  494. Logger.error(TAG, `WebDAV 缓存后台下载失败: ${error.message}`);
  495. });
  496. }
  497. Logger.info(TAG, `WebDAV 启动异步缓存: ${relativePath}`);
  498. return sanitizedUrl;
  499. }
  500. }
  501. const fallbackUrl = await WebDavUrlUtil.buildFullUrlByAccountId(song.webdav_account_id, relativePath);
  502. if (fallbackUrl) {
  503. Logger.warn(TAG, `WebDAV 使用全局查询到的URL: ${fallbackUrl}`);
  504. return sanitizePlaybackUrl(fallbackUrl);
  505. }
  506. Logger.error(TAG, `WebDAV URL构建失败,使用原始路径: ${relativePath}`);
  507. return sanitizePlaybackUrl(relativePath);
  508. } catch (error) {
  509. Logger.error(TAG, `WebDAV URL构建出错: ${(error as Error).message}`);
  510. const fallbackPath = song.remote_rel_path || song.filePath;
  511. return sanitizePlaybackUrl(fallbackPath);
  512. }
  513. }
  514. if (isNavidromeType(song.type) && song.webdav_account_id) {
  515. try {
  516. const manager = RemoteDriveManager.getInstance();
  517. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  518. if (!account) {
  519. throw new Error('Navidrome账号不可用');
  520. }
  521. const navSongId = song.remote_rel_path || song.id || song.filePath;
  522. const streamUrl = await navidromeApi.buildStreamUrl(account, navSongId);
  523. void ServerLogUtil.info(TAG, `流地址构建成功: ${streamUrl}`);
  524. void ServerLogUtil.debug(TAG, `播放songId=${navSongId}, account=${ServerLogUtil.sanitizeAccount(account)}`);
  525. return sanitizePlaybackUrl(streamUrl);
  526. } catch (error) {
  527. const err = error as Error;
  528. void ServerLogUtil.error(TAG, `URL构建失败: ${err.message}`);
  529. throw new Error(err.message);
  530. }
  531. }
  532. if (isSmbType(song.type) && song.webdav_account_id) {
  533. try {
  534. const manager = RemoteDriveManager.getInstance();
  535. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  536. if (!account) {
  537. throw new Error('SMB账号不可用');
  538. }
  539. const relativePath = extractSmbRelativePath(song, account.smbShare);
  540. const pathInfo = await resolveCacheFilePath(
  541. RemoteCacheType.SMB,
  542. account.id?.toString(),
  543. relativePath
  544. );
  545. const streamMeta: SmbStreamingMeta = {
  546. fileSize: song.videoSize,
  547. mimeType: song.mimeType,
  548. fileName: song.fileName || song.name
  549. };
  550. const streamingUrl = await ensureSmbFileStreaming(account, pathInfo.normalizedRelative, streamMeta);
  551. Logger.info(TAG, `SMB 流地址: ${streamingUrl}`);
  552. void scheduleMetadataExtractionFromCache(song, pathInfo.cachePath, metadataOptions, song.videoSize);
  553. const shouldBypassSanitize = streamingUrl.startsWith('http://127.0.0.1:');
  554. return shouldBypassSanitize ? streamingUrl : sanitizePlaybackUrl(streamingUrl);
  555. } catch (error) {
  556. const err = error as Error;
  557. Logger.error(TAG, `SMB 流式播放失败: ${err.message}`);
  558. throw new Error(err.message);
  559. }
  560. }
  561. if (isFtpType(song.type) && song.webdav_account_id) {
  562. try {
  563. const manager = RemoteDriveManager.getInstance();
  564. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  565. if (!account) {
  566. throw new Error('FTP账号不可用');
  567. }
  568. const relativePath = extractFtpRelativePath(song);
  569. const cachedPath = await RemoteCacheManager.ensureCached(RemoteCacheType.FTP, {
  570. account,
  571. remotePath: relativePath
  572. });
  573. Logger.info(TAG, `FTP 缓存路径: ${cachedPath}`);
  574. void scheduleMetadataExtractionFromCache(song, cachedPath, metadataOptions, song.videoSize);
  575. return cachedPath;
  576. } catch (error) {
  577. const err = error as Error;
  578. Logger.error(TAG, `FTP 缓存失败: ${err.message}`);
  579. throw new Error(err.message);
  580. }
  581. }
  582. if (isBaiduType(song.type) && song.webdav_account_id) {
  583. try {
  584. const manager = RemoteDriveManager.getInstance();
  585. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  586. if (!account) {
  587. throw new Error('百度网盘账户不可用');
  588. }
  589. Logger.info(TAG, `百度网盘播放准备 - accountId: ${account.id}, fsId: ${song.baiduFsId || song.id}`);
  590. const sanitizedAccount = ServerLogUtil.sanitizeAccount(account);
  591. void ServerLogUtil.info('BaiduStream', `准备播放百度歌曲: account=${sanitizedAccount}, fsId=${song.baiduFsId || song.id}`);
  592. const fsId = song.baiduFsId || song.id;
  593. if (!fsId) {
  594. throw new Error('缺少百度网盘文件fs_id');
  595. }
  596. // 优先使用remote_rel_path,回退到文件名
  597. const relativePath = song.remote_rel_path || song.name || song.fileName || song.filePath;
  598. const streamPath = song.remote_rel_path;
  599. const cachedPath = await resolveCacheFilePath(
  600. RemoteCacheType.BAIDU,
  601. account.id?.toString(),
  602. relativePath
  603. );
  604. const fileExists = await FileManager.isExist(cachedPath.cachePath);
  605. if (fileExists) {
  606. const fileSize = await FileManager.getFileSize(cachedPath.cachePath);
  607. if (fileSize > 0) {
  608. Logger.info(TAG, `百度网盘文件已缓存: ${cachedPath.cachePath}`);
  609. void scheduleMetadataExtractionFromCache(song, cachedPath.cachePath, metadataOptions, song.videoSize);
  610. return cachedPath.cachePath;
  611. }
  612. }
  613. // 缓存不存在或无效,获取文件信息(包含大小和下载链接)
  614. Logger.info(TAG, `百度网盘文件未缓存,准备获取文件信息: ${relativePath}`);
  615. const fileInfo = await manager.getBaiduFileInfo(account, fsId, streamPath);
  616. Logger.info(TAG, `百度网盘文件信息获取成功: 大小=${fileInfo.size}字节,流地址已获取`);
  617. void ServerLogUtil.info('BaiduStream', `音频流URL获取成功: ${fileInfo.streamUrl}`);
  618. // 立即返回媒体流地址,开始播放
  619. Logger.info(TAG, `返回音频流链接进行播放,同时后台缓存: ${fileInfo.streamUrl}`);
  620. // 异步进行缓存,不阻塞播放
  621. void (async () => {
  622. try {
  623. Logger.info(TAG, `后台开始缓存百度网盘文件: ${relativePath},大小: ${fileInfo.size}字节`);
  624. void ServerLogUtil.info('BaiduStream', `开始缓存百度文件: account=${sanitizedAccount}, path=${relativePath}`);
  625. const cachedFilePath = await ensureBaiduFileCached(
  626. account,
  627. fsId,
  628. relativePath,
  629. fileInfo.dlink,
  630. fileInfo.size
  631. );
  632. Logger.info(TAG, `后台缓存完成: ${cachedFilePath}`);
  633. void ServerLogUtil.info('BaiduStream', `缓存完成: ${cachedFilePath}`);
  634. void scheduleMetadataExtractionFromCache(song, cachedFilePath, metadataOptions, song.videoSize);
  635. } catch (cacheError) {
  636. const cacheErr = cacheError as Error;
  637. Logger.warn(TAG, `后台缓存失败: ${cacheErr.message}`);
  638. void ServerLogUtil.error('BaiduStream', `缓存失败: ${cacheErr.message}`);
  639. }
  640. })();
  641. return fileInfo.streamUrl;
  642. } catch (error) {
  643. const err = error as Error;
  644. Logger.error(TAG, `百度网盘播放链接获取失败: ${err.message}`);
  645. throw err;
  646. }
  647. }
  648. if (isWebDavType(song.type)) {
  649. Logger.warn(TAG, `WebDAV歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
  650. return sanitizePlaybackUrl(song.filePath);
  651. }
  652. if (isSmbType(song.type)) {
  653. Logger.warn(TAG, `SMB歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
  654. return song.filePath;
  655. }
  656. if (isFtpType(song.type)) {
  657. Logger.warn(TAG, `FTP歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
  658. return song.filePath;
  659. }
  660. if (isBaiduType(song.type)) {
  661. throw new Error('百度网盘歌曲缺少webdav_account_id,无法构建播放链接');
  662. }
  663. if (isNavidromeType(song.type)) {
  664. throw new Error('Navidrome歌曲缺少webdav_account_id,无法构建播放链接');
  665. }
  666. Logger.info(TAG, `setVideoUrlForSong fallback直接返回原始路径: ${song.filePath}`);
  667. return song.filePath;
  668. }
  669. // 定义接口
  670. interface HiCarAspectRatio {
  671. ratio: number;
  672. name: string;
  673. }
  674. interface GeneratedObjectLiteralInterface_1 {
  675. assetId: string;
  676. title: string;
  677. artist: string;
  678. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  679. mediaUri: string;
  680. // 该字段大写,音频'AUDIO',视频'VIDEO'
  681. mediaType: string;
  682. mediaSize: number;
  683. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  684. startPosition: number;
  685. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  686. duration: number;
  687. albumCoverUri: string;
  688. albumTitle: string;
  689. appName: string;
  690. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  691. drmScheme: string;
  692. }
  693. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  694. const ITEM_HEIGHT: number = 65; // 列表项中高度
  695. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  696. //功能强大的音乐播放器
  697. @Preview
  698. @Component
  699. export struct LocalMusic {
  700. @State showZMIndex: boolean = false //是否右侧显示字母索引
  701. private prevOffsetY: number = 0; // 记录上一次的Y轴偏移量
  702. @State autoHideTitle: boolean = true //滚动自动隐藏标题栏
  703. // 字母表
  704. @State alphaBet: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
  705. 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  706. @State alphaBetStyle: GlobalAlphabetIndexerModifier = new GlobalAlphabetIndexerModifier()
  707. @State selectAlphaBetIndex: number = 0
  708. @State isShowAlphaBet: boolean = false
  709. @State isScrolling: boolean = false
  710. @State isTouchingAlphaBet: boolean = false
  711. @State alphabetHeight: number = 0
  712. public enableShowAlphabet: boolean = true // 是否显示字母表
  713. @State isShowPrecious: boolean = false //播控条显示上一首按钮
  714. //背景两侧流光控制器
  715. @State sceneBgController: HdsSceneController|undefined = deviceInfo.sdkApiVersion>=20
  716. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  717. new HdsSceneController()
  718. .setSceneParams({
  719. backgroundMaskColors: [Color.Green, Color.Red],
  720. firstEdgeFlowLight: {
  721. startPos: 0,
  722. endPos: 0.5,
  723. color: Color.Red
  724. },
  725. secondEdgeFlowLight: {
  726. startPos: 0,
  727. endPos: -0.5,
  728. color: Color.Green
  729. }
  730. }) : undefined;
  731. //背景流光控制器
  732. @State bgController: hdsEffect.ShaderEffectController|undefined = deviceInfo.sdkApiVersion>=20
  733. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  734. new hdsEffect.ShaderEffectController():undefined;
  735. @State showAddSheet:boolean = false
  736. searchController: SearchController = new SearchController()
  737. @State rightTopImage:Resource = $r('sys.symbol.sort')
  738. @State isEditAudio:boolean = false
  739. @State isExtractAcc:boolean = false
  740. @State isConverter:boolean = false
  741. @State isAIVoiceSeparation:boolean = false
  742. @State isExtractAudio:boolean = false
  743. @State isMergeAudio:boolean = false
  744. @State isCopyFileToDownLoad: boolean = false
  745. @State isChangeTone:boolean = false
  746. @State offHeight: number = 75
  747. @State currentSongList: Array<VideoItem> = []//当前歌单
  748. @Consume currentSongListName:string //当前歌单名称
  749. @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
  750. @State isRefreshing: boolean = false;
  751. @State maxRefreshingHeight: number = 100.0;
  752. private contentNode?: ComponentContent<Object> = undefined;
  753. // WebDAV相关实例变量(现在改为从内存读取,不再需要存储)
  754. @State ratioL: number = 1;
  755. @State mediaKuCount: number = 0;
  756. @State albumCount: number = 0;
  757. @State artistCount: number = 0;
  758. @State fastForwardSeconds: string = '10'
  759. @State isShowBackFast: boolean = true//快进快退按钮
  760. @State isCanAuto:boolean = true
  761. @State opacityValueImage: number = 1;
  762. @State tipPopup:boolean = false
  763. @Consume mType: number;
  764. @StorageProp('themeColor') themeColor: string =
  765. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  766. themeMode: number = 0;
  767. @State titleName: string = '首页'
  768. @State textStr: string = ''
  769. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  770. // private download_path: string = '';
  771. @Consume rootPath: string //音频根目录
  772. @Consume currentPath: string
  773. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  774. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  775. @State lockPath: string = ''
  776. @State favPath: string = ''
  777. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  778. @State historyPath: string = ''
  779. @State historyList: Array<VideoItem> = []
  780. @Consume isHistory: boolean
  781. static readonly HISTORY_MUSIC: string = 'music_historyList';
  782. private table: MediaTable = new MediaTable(getContext(this))
  783. private playlistTable: PlaylistTable | null = null
  784. private deletionWatcher: FileDeletionWatcher | null = null
  785. @State allPlaylists: Playlist[] = []
  786. @State isZero: boolean = false
  787. @State fileList: Array<string> = []
  788. @State dirList: Array<VideoItem> = []
  789. @Consume videoLocalList:VideoItem[]
  790. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  791. @State listRefreshKey: number = 0
  792. // @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  793. @StorageProp('mediaKuList') mediaKuList: Array<VideoItem> = []; //媒体库文件
  794. @State artistList: Array<VideoItem> = []; //艺术家文件
  795. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  796. @State albumList: Array<VideoItem> = []; //专辑文件
  797. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  798. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  799. @State imageOpacities: number[] = [];
  800. @Consume isCanBack: boolean
  801. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  802. @State showSingleLyric: boolean = false
  803. @State sortType: number = 4 //默认排序方式
  804. @State isShowSimi: boolean = false //是否显示私密音频
  805. @State isShowFAV: boolean = true //是否显示我的收藏
  806. @State isShowTitleBar: boolean = true //是否显示分类导航条
  807. @State isShowAllBar: boolean = true //是否显示播放全部条
  808. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  809. @State isShowHistory: boolean = true //是否显示最近播放
  810. @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
  811. @State isGridMusic: boolean = false //是否网格布局
  812. @State isCircleBtn: boolean = false //是否圆形播放按钮
  813. @State twoFingerType: number = 3 //双支放大缩小的类型
  814. @State isScrollHide: boolean = false //是否滚动隐藏
  815. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  816. @State isStartAutoPlay: boolean = false //启动后自动播放
  817. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  818. @State isShowHeader: boolean = true
  819. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  820. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  821. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  822. @State isSwipe: boolean = false //listItem的左滑开关
  823. @State openSkipSongAnimate: boolean = true//切歌动画效果
  824. @State customizeBgPath: string | undefined = '';
  825. @State isDarkMode: boolean = false
  826. @State lyricTextWeight: number = 400
  827. @State lyricTextWeightPip: number = 400
  828. @State currentSwiperIndex: number = 0
  829. @State blurValue: number = 0 //背景模糊
  830. @State bgBrightness: number = 0 //背景亮度
  831. private listScroller: ListScroller = new ListScroller()
  832. private playListScroller: Scroller = new Scroller()
  833. @State isOneKeyTags:boolean = false
  834. @State isFixMessy:boolean = false
  835. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  836. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  837. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  838. @StorageProp('windowWidth') windowWidth: number = 0;
  839. @StorageProp('windowHeight') windowHeight: number = 0;
  840. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  841. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  842. private UNKONWN:string = '';
  843. private listArea: Area = {
  844. width: 0,
  845. height: 0,
  846. position: {},
  847. globalPosition: {}
  848. }
  849. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  850. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  851. // WebDAV认证信息缓存(作为实例变量,比全局上下文更可靠)
  852. private currentWebDavAuthInfo: WebDavAuthItem | null = null;
  853. //瀑布流的列数横竖屏动态切换
  854. onIsLandscapeChange() {
  855. if(this.isLandscape){
  856. this.columns = 4
  857. }else{
  858. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  859. }
  860. }
  861. onColorModeChange() {
  862. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  863. }
  864. //点击某个歌单id发生变化的时候回调
  865. onIDChange(){
  866. console.log('onecold 歌单id发生变化this.currentSongListID='+this.currentSongListID)
  867. console.log('onecold 歌单id发生变化this.currentSongListName='+this.currentSongListName)
  868. if(this.modeType==4){
  869. this.titleName = this.currentSongListName
  870. this.rightTopImage = $r('sys.symbol.sort')
  871. //获取缓存
  872. const cacheSongs:string =PreferencesUtil.getStringSync(this.currentSongListID+'currentSongList', '')
  873. console.log('onecold 歌单id发生变化获取缓存2 cacheSongs = '+cacheSongs)
  874. if(StrUtil.isNotEmpty(cacheSongs)){
  875. this.currentSongList = JSON.parse(cacheSongs) as VideoItem[]
  876. this.updateListData(this.currentSongList, true)
  877. }
  878. this.doSongListTask()//获取歌单信息
  879. }
  880. }
  881. async doSongListTask() {
  882. // 初始化歌单数据库
  883. const playlistTable = new PlaylistTable(this.context);
  884. // 查询歌单中的所有歌曲
  885. const playlistSongs: PlaylistSong[] = await playlistTable.queryPlaylistSongs(this.currentSongListID);
  886. console.log('onecold 歌单id发生变化获取缓存7 playlistSongs='+playlistSongs.length)
  887. if (ArrayUtil.isEmpty(playlistSongs)) {
  888. this.updateListData([], true)
  889. } else {
  890. this.currentSongList = await convertPlaylistSongsToVideoItems(this.context, playlistSongs);
  891. console.log('onecold 从数据库读取的歌曲为 playlistSongs='+this.currentSongList.length)
  892. this.updateListData(this.currentSongList, true)
  893. if (ArrayUtil.isNotEmpty(this.currentSongList)&&this.currentSongList.length > 100) {
  894. // 只保存前100条记录到缓存中
  895. let canceList = this.currentSongList.slice(0, 100);
  896. PreferencesUtil.putSync(this.currentSongListID+'currentSongList',
  897. JSON.stringify(canceList))
  898. } else {
  899. PreferencesUtil.putSync(this.currentSongListID+'currentSongList', JSON.stringify(this.currentSongList));
  900. }
  901. }
  902. this.isRefreshing = false
  903. }
  904. onModeChange() {
  905. this.isFavMusic = false
  906. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  907. switch (this.modeType) {
  908. case 0:
  909. this.getSortedFiles(this.currentPath)
  910. break
  911. case 1:
  912. this.rightTopImage = $r('sys.symbol.sort')
  913. this.updateListData(this.mediaKuList)
  914. this.titleName = Utility.resourceToString(this.context,$r('app.string.media_ku'))
  915. break
  916. case 2:
  917. this.rightTopImage = $r('sys.symbol.sort')
  918. this.updateListData(this.artistList)
  919. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  920. break
  921. case 3:
  922. this.rightTopImage = $r('sys.symbol.sort')
  923. this.updateListData(this.albumList)
  924. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  925. break
  926. }
  927. }
  928. // @Consume currentSong: VideoItem | undefined;
  929. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  930. // @StorageLink('isPlay') isPlay: boolean = false;
  931. @Consume isShowPlay: boolean ;
  932. @StorageLink('songList') songList: Array<VideoItem> = [];
  933. @State translateY: number = 0;
  934. @State isShowSheet: boolean = false;
  935. @State isShowSheetView: boolean = false;
  936. @State isShowTimeCloseView: boolean = false;
  937. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  938. @StorageLink('currIndex') curIndex: number = 0;
  939. @Consume isShowDrawer: boolean;
  940. @Consume offsetX: number;
  941. @State isFac: boolean = false;
  942. @State favList: Array<VideoItem> = []
  943. @Consume isFavMusic: boolean
  944. @State isClickedPLayAll: boolean = false;
  945. private scrollerForlist: ListScroller = new ListScroller();
  946. private knockController: KnockController | undefined = undefined;
  947. // 修改为:
  948. imagesF: ImageFrameInfo[] = CommonConstants.IMAGE_FRAME_INFO;
  949. @StorageProp('animationState') animationState: AnimationStatus = AnimationStatus.Initial
  950. // 缓存机制
  951. private cache: Map<string, Array<VideoItem>> = new Map();
  952. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  953. // 持久化缓存
  954. private async saveCacheToStorage() {
  955. const cacheArray = Array.from(this.cache.entries());
  956. const stringCacheArray = Array.from(this.stringCache.entries());
  957. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  958. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  959. }
  960. // 载入缓存
  961. private async loadCacheFromStorage() {
  962. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  963. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  964. if (cacheString) {
  965. const parsedCache: Object | null = JSON.parse(cacheString);
  966. if (parsedCache && Array.isArray(parsedCache)) {
  967. const cacheArray: [string, Array<VideoItem>][] = parsedCache;
  968. this.cache = new Map(cacheArray);
  969. }
  970. }
  971. if (stringCacheString) {
  972. const parsedStringCache: Object | null = JSON.parse(stringCacheString);
  973. if (parsedStringCache && Array.isArray(parsedStringCache)) {
  974. const stringCacheArray: [string, string][] = parsedStringCache;
  975. this.stringCache = new Map(stringCacheArray);
  976. }
  977. }
  978. }
  979. // 查找缓存
  980. private findCache(key: string): Array<VideoItem> | undefined {
  981. return this.cache.get(key);
  982. }
  983. // 查找字符串缓存
  984. private findStringCache(key: string): string | undefined {
  985. return this.stringCache.get(key);
  986. }
  987. // 添加缓存
  988. private addCache(key: string, value: Array<VideoItem>) {
  989. this.cache.set(key, value);
  990. }
  991. // 添加字符串缓存
  992. private addStringCache(key: string, value: string) {
  993. this.stringCache.set(key, value);
  994. }
  995. // 删除缓存
  996. private deleteCache(key: string) {
  997. this.cache.delete(key);
  998. this.saveCacheToStorage()
  999. }
  1000. // 删除字符串缓存
  1001. private deleteStringCache(key: string) {
  1002. this.stringCache.delete(key);
  1003. }
  1004. // 多选机制
  1005. @State selectedFiles: Array<VideoItem> = [];
  1006. @Consume isMultiSelect: boolean;
  1007. @State isAllSelected: boolean = false;
  1008. @State appName: string = ''
  1009. @State isHasDir: boolean = false
  1010. @State packName: string = ''
  1011. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  1012. doSwipBack() {
  1013. if(this.isSearchMode){
  1014. console.info('onecold doSwipBack = ' +this.isSearchMode)
  1015. this.isSearchMode = false
  1016. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  1017. this.searchText = ''
  1018. this.getSortedFiles(this.currentPath)
  1019. return
  1020. }
  1021. this.onSearchInput('')
  1022. return
  1023. }
  1024. this.isZero = false
  1025. if (this.modeType !== 0 && this.isCanBack) {
  1026. this.onModeChange()
  1027. this.isCanBack = false
  1028. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  1029. setTimeout(() => {
  1030. if (this.modeType == 2) {
  1031. if (this.isGridMusic||this.twoFingerType==4) {
  1032. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  1033. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  1034. if(this.twoFingerType==4){
  1035. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  1036. }else{
  1037. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1038. }
  1039. } else {
  1040. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  1041. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1042. }
  1043. } else if (this.modeType == 3) {
  1044. if (this.isGridMusic||this.twoFingerType==4) {
  1045. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  1046. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 0
  1047. if(this.twoFingerType==4){
  1048. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  1049. }else{
  1050. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1051. }
  1052. } else {
  1053. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  1054. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1055. }
  1056. }
  1057. }, 200)
  1058. return
  1059. }
  1060. if (this.isHistory || this.isFavMusic) {
  1061. this.isHistory = false
  1062. this.getSortedFiles(this.currentPath)
  1063. return
  1064. }
  1065. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  1066. animateTo({ duration: 555 }, () => {
  1067. // 动画闭包内控制Image组件的出现和消失
  1068. this.isShowDrawer = !this.isShowDrawer
  1069. this.offsetX = 0
  1070. })
  1071. return
  1072. }
  1073. //返回上一级歌单的滚动位置
  1074. setTimeout(() => {
  1075. if (this.modeType == 0) {
  1076. if (this.isGridMusic||this.twoFingerType==4) {
  1077. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  1078. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
  1079. if(this.twoFingerType==4){
  1080. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  1081. }else{
  1082. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1083. }
  1084. } else {
  1085. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  1086. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1087. }
  1088. }
  1089. }, 300)
  1090. this.currentPath = Utility.getParentDirectory(this.currentPath)
  1091. Logger.info('this.currentPath2 = ' + this.currentPath)
  1092. this.getSortedFiles(this.currentPath)
  1093. }
  1094. // 组件生命周期
  1095. aboutToAppear() {
  1096. console.info('onecold aboutToAppear sdkApiVersion = '+deviceInfo.sdkApiVersion)
  1097. if(ArrayUtil.isNotEmpty(this.videoLocalList)&&this.modeType==0){
  1098. this.updateListData(this.videoLocalList)
  1099. }
  1100. // 初始化 PlaylistTable
  1101. this.playlistTable = new PlaylistTable(getContext(this))
  1102. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  1103. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  1104. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  1105. this.tipPopup = !this.tipPopup
  1106. PreferencesUtil.putSync('isFirstTiped',false)
  1107. }
  1108. this.initSetting()
  1109. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  1110. Utility.getAppName(getContext(this)).then((appName: string) => {
  1111. this.appName = appName
  1112. })
  1113. this.packName = AppUtil.getBundleName()
  1114. this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
  1115. this.loadCacheFromStorage(); // 加载文件夹缓存
  1116. // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
  1117. this.initLoadCache()
  1118. this.mkDownLoadDir()
  1119. let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
  1120. // 监听广播事件(打开其他应用处理)
  1121. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  1122. this.saveVideoDatas([eventData.data?.message], true)
  1123. });
  1124. //侧滑广播接收时间
  1125. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
  1126. // 监听广播事件(打开其他应用处理)
  1127. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  1128. animateTo({ duration: 555 }, () => {
  1129. this.doSwipBack()
  1130. })
  1131. });
  1132. //ScanFilePage广播接收时间
  1133. let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
  1134. // 监听ScanFilePage广播事件(更新数据库)
  1135. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  1136. this.doUpdateData()
  1137. });
  1138. // 监听歌单播放请求事件
  1139. let eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY }
  1140. emitter.on(eventPlaylistPlay, async (eventData: emitter.EventData) => {
  1141. const data = eventData.data as Record<string, Object>
  1142. if (!data) {
  1143. Logger.error('heanup eventPlaylistPlay: eventData.data is undefined or null')
  1144. return
  1145. }
  1146. // 检查歌单播放数据结构
  1147. if (data.playlistId && data.songFilePaths && data.startIndex !== undefined) {
  1148. const playlistData: PlaylistEventData = {
  1149. playlistId: data.playlistId as string,
  1150. playlistName: data.playlistName as string,
  1151. songCount: data.songCount as number,
  1152. startIndex: data.startIndex as number,
  1153. isJump: data.isJump as boolean,
  1154. songFilePaths: data.songFilePaths as string[]
  1155. }
  1156. await this.handlePlaylistPlayRequest(
  1157. playlistData.playlistId,
  1158. playlistData.playlistName,
  1159. playlistData.songFilePaths,
  1160. playlistData.startIndex,
  1161. playlistData.isJump,
  1162. )
  1163. return
  1164. }
  1165. Logger.error('heanup eventPlaylistPlay: 接收到无效的数据结构')
  1166. });
  1167. let eventRefreshSort: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_REFRESH_SORT }
  1168. // 监听广播事件(通用设置配置更新)
  1169. emitter.on(eventRefreshSort, (eventData: emitter.EventData) => {
  1170. if(this.modeType ==4){
  1171. this.doSongListTask()//获取歌单信息
  1172. }
  1173. });
  1174. let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
  1175. // 监听广播事件(通用设置配置更新)
  1176. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  1177. this.doChangeSetting()
  1178. });
  1179. let event: Callback<InterruptEvent> = (event) => {
  1180. // LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  1181. console.info(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  1182. this.savePlaybackPosition()
  1183. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  1184. this.pause();
  1185. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  1186. console.info(`onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  1187. console.info('onecold startPlayOrResumePlay 514')
  1188. this.startPlayOrResumePlay();
  1189. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  1190. console.info(`onecold 与其他应用音频冲突 被截断点 INTERRUPT_HINT_STOP`)
  1191. if(!this.isSameTimePlay){
  1192. this.stop();
  1193. }
  1194. }
  1195. }
  1196. this.mIjkMediaPlayer.on('audioInterrupt', event);
  1197. // 音频设备断连回调处理比如蓝牙耳机断开
  1198. let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  1199. LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  1200. if (event.reason === DeviceChangeReason.REASON_NEW_DEVICE_AVAILABLE) { // 音频设备连接
  1201. } else if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  1202. console.info('onecold 音频设备断开连接, 暂停播放')
  1203. this.pause();
  1204. }
  1205. }
  1206. // 订阅音频设备断开和连接事件
  1207. this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  1208. const eventPause: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_PAUSE }
  1209. // 监听广播事件(hicar断开暂停播放)
  1210. emitter.on(eventPause, (eventData: emitter.EventData) => {
  1211. this.pause();
  1212. });
  1213. // 有线耳机断开和连接的监听。监听音频设备状态变化。
  1214. let audioManager = audio.getAudioManager(); // 需要先创建AudioManager实例。
  1215. let audioRoutingManager = audioManager.getRoutingManager(); // 再调用AudioManager的方法创建AudioRoutingManager实例。
  1216. audioRoutingManager.on('deviceChange', audio.DeviceFlag.INPUT_DEVICES_FLAG, (deviceChanged: audio.DeviceChangeAction) => {
  1217. console.info('device change type : ' + deviceChanged.type); // 设备连接状态变化,0为连接,1为断开连接。
  1218. // 设备类型 22是USB耳机,带麦克风,3是有线耳机。
  1219. if(deviceChanged.type==1&&
  1220. (deviceChanged.deviceDescriptors[0].deviceType== 22||
  1221. deviceChanged.deviceDescriptors[0].deviceType==3)){
  1222. this.pause();
  1223. }
  1224. });
  1225. this.makeWorker()
  1226. //折叠屏的屏幕显示模式变化
  1227. display.on('foldDisplayModeChange', (data) => {
  1228. this.doChangeBarHeight()
  1229. });
  1230. display.on('foldStatusChange', (data) => {
  1231. Logger.info('onecold foldStatusChange ')
  1232. });
  1233. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  1234. // 读取 themeMode 并同步 currentColorMode
  1235. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  1236. this.applyThemeMode(this.themeMode)
  1237. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  1238. AppStorage.setOrCreate('themeColor', themeColor);
  1239. this.themeColor = themeColor;
  1240. this.doChangeSetting()
  1241. this.windowClass.on('windowSizeChange', (size) => {
  1242. LogUtil.info('onecold windowSizeChange')
  1243. this.doChangeBarHeight()
  1244. let viewWidth = px2vp(size.width);
  1245. let viewHeight = px2vp(size.height);
  1246. if(this.isPhoneLan()){
  1247. this.is_auto_hide_progress = false
  1248. if(this.isHiCar()){
  1249. return
  1250. }
  1251. setTimeout(() => {
  1252. this.is_auto_hide_progress = true
  1253. }, 6000)
  1254. }else{
  1255. this.startAutoHide()
  1256. }
  1257. });
  1258. this.eventHub.on('onStateChange', (fg: boolean) => {
  1259. if (fg && this.curState === 'STARTED') {
  1260. this.stopPip();
  1261. }
  1262. });
  1263. //NewIndex的博空调收到eventHub消息控制播放
  1264. this.getUIContext().getHostContext()!.eventHub.on('playOrPause', () => {
  1265. if (ArrayUtil.isNotEmpty(this.songList)) {
  1266. this.playOrPause();
  1267. } else {
  1268. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1269. }
  1270. });
  1271. this.getUIContext().getHostContext()!.eventHub.on('playPrevious', () => {
  1272. if (ArrayUtil.isNotEmpty(this.songList)) {
  1273. this.playPrevious();
  1274. } else {
  1275. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1276. }
  1277. });
  1278. this.getUIContext().getHostContext()!.eventHub.on('playNext', () => {
  1279. if (ArrayUtil.isNotEmpty(this.songList)) {
  1280. this.playNext();
  1281. } else {
  1282. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1283. }
  1284. });
  1285. this.getUIContext().getHostContext()!.eventHub.on('showPlayerView', () => {
  1286. this.showPlayerView();
  1287. });
  1288. this.getUIContext().getHostContext()!.eventHub.on('openPlayList', () => {
  1289. this.openPlayList();
  1290. });
  1291. }
  1292. //载入媒体库,艺术家,专辑等缓存
  1293. initLoadCache(){
  1294. this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
  1295. this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
  1296. this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
  1297. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  1298. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  1299. if(ArrayUtil.isNotEmpty(cachedList)){
  1300. this.mediaKuList = cachedList
  1301. if(this.modeType==1){
  1302. this.updateListData(this.mediaKuList)
  1303. }
  1304. }
  1305. let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
  1306. let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
  1307. if(ArrayUtil.isNotEmpty(artistCachedList)){
  1308. this.artistList = artistCachedList
  1309. let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
  1310. const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
  1311. this.artistMap = new Map(parsedArray);
  1312. // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
  1313. if(this.modeType==2){
  1314. this.updateListData(this.artistList)
  1315. }
  1316. }
  1317. let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
  1318. let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
  1319. if(ArrayUtil.isNotEmpty(albumCachedList)){
  1320. this.albumList = albumCachedList
  1321. let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
  1322. const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
  1323. this.albumMap = new Map(parsedArray);
  1324. if(this.modeType==3){
  1325. this.updateListData(this.albumList)
  1326. }
  1327. }
  1328. }
  1329. startAutoHide() {
  1330. if(this.isHiCar()){
  1331. return
  1332. }
  1333. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  1334. console.info('onecold startAutoHide')
  1335. this.is_auto_hide_progress = false
  1336. setTimeout(() => {
  1337. this.is_auto_hide_progress = true
  1338. }, 6000)
  1339. }
  1340. }
  1341. applyThemeMode(mode: number) {
  1342. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  1343. if (mode === 1) {
  1344. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  1345. } else if (mode === 2) {
  1346. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1347. }
  1348. AppStorage.setOrCreate('currentColorMode', colorMode)
  1349. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  1350. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  1351. AppStorage.setOrCreate('themeMode', mode)
  1352. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1353. // 只有强制浅色/深色时才主动设置
  1354. const context = getContext(this) as common.UIAbilityContext
  1355. context.getApplicationContext().setColorMode(colorMode)
  1356. }
  1357. initSetting() {
  1358. this.showZMIndex = PreferencesUtil.getBooleanSync('showZMIndex', false)
  1359. this.autoHideTitle = PreferencesUtil.getBooleanSync('autoHideTitle', true)
  1360. this.isShowPrecious = PreferencesUtil.getBooleanSync('isShowPrecious', false)
  1361. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1362. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  1363. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  1364. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, false)
  1365. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  1366. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  1367. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  1368. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  1369. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  1370. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  1371. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  1372. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  1373. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  1374. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 2)
  1375. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  1376. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  1377. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  1378. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  1379. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  1380. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  1381. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  1382. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  1383. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  1384. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  1385. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  1386. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  1387. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  1388. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  1389. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  1390. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  1391. this.isCopyFileToDownLoad = PreferencesUtil.getBooleanSync(SettingPage.IS_COPYFILE_TO_DOWNLOAD, false)
  1392. let audioManager = audio.getAudioManager();
  1393. let audioSessionManager: audio.AudioSessionManager = audioManager.getSessionManager();
  1394. if(this.isSameTimePlay){
  1395. //与其他应用同时播放,关键代码
  1396. let strategy: audio.AudioSessionStrategy = {
  1397. concurrencyMode: audio.AudioConcurrencyMode.CONCURRENCY_MIX_WITH_OTHERS
  1398. };
  1399. audioSessionManager.activateAudioSession(strategy).then(() => {
  1400. console.info('onecold Succeeded in doing activateAudioSession.');
  1401. }).catch((err: BusinessError) => {
  1402. console.error(`Failed to activateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1403. });
  1404. }else{
  1405. let isActivated = audioSessionManager.isAudioSessionActivated();
  1406. if(isActivated){
  1407. audioSessionManager.deactivateAudioSession().then(() => {
  1408. console.info('Succeeded in doing deactivateAudioSession.');
  1409. }).catch((err: BusinessError) => {
  1410. console.error(`Failed to deactivateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1411. });
  1412. }
  1413. }
  1414. if(this.volumeSmall){
  1415. this.volume = 0.5
  1416. }else{
  1417. this.volume = 1
  1418. }
  1419. //如果是hicar连接状态,这些都是false
  1420. if(this.isHiCar()){
  1421. this.autoHideTitle = false
  1422. this.isCoverRectangle= true
  1423. this.columns=4
  1424. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  1425. {
  1426. this.isGridMusic= false//用list不用网格
  1427. this.isCoverTopBig = false
  1428. }
  1429. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  1430. }
  1431. if (this.isSavePlayMode) {
  1432. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  1433. }
  1434. }
  1435. doChangeSetting() {
  1436. this.initSetting()
  1437. this.deleteCache(this.currentPath)
  1438. if (this.modeType === 0) {
  1439. this.getSortedFiles(this.currentPath)
  1440. }
  1441. }
  1442. doChangeBarHeight() {
  1443. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  1444. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  1445. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  1446. this.setBarHeightNormal()
  1447. }
  1448. }
  1449. onPageShow() {
  1450. this.knockController?.immersiveListening();
  1451. app.setImageCacheCount(100);
  1452. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  1453. app.setImageRawDataCacheSize(104857600);
  1454. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  1455. }
  1456. //开启线程查看各个数据库
  1457. makeWorker() {
  1458. setTimeout(() => {
  1459. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  1460. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  1461. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  1462. // workerInstance.postMessage({
  1463. // code: 1,
  1464. // data1: this.context,
  1465. // data2: this.rootPath,
  1466. // data3: this.lockPath,
  1467. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1468. // data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  1469. // });
  1470. PreferencesUtil.putSync('isFirstApp', false)
  1471. } else {
  1472. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1473. workerInstance.postMessage({ code: 3, data: this.context });
  1474. workerInstance.postMessage({ code: 4, data: this.context });
  1475. this.getHistoryList(false)
  1476. }
  1477. }, 1000)
  1478. workerInstance.onmessage = (e: MessageEvents): void => {
  1479. switch (e.data.code) {
  1480. case 101: //第一次扫描文件夹入库
  1481. ToastUtil.showToast('刷新同步数据库成功!')
  1482. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  1483. this.doAllUpdateData()
  1484. break;
  1485. case 102: //查询媒体库列表
  1486. this.isRefreshing = false
  1487. this.mediaKuList = e.data.data
  1488. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  1489. Utility.doSortListAscending(this.mediaKuList)
  1490. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  1491. if (this.modeType === 1) {
  1492. this.updateListData(this.mediaKuList)
  1493. }
  1494. PreferencesUtil.putSync('mediaKuCount', this.mediaKuList.length)
  1495. // 处理媒体库前100条记录,列表长度并存储到PreferencesUtil
  1496. if (ArrayUtil.isNotEmpty(this.mediaKuList)&&this.mediaKuList.length > 100) {
  1497. // 只保存前100条记录到缓存中
  1498. let truncatedList = this.mediaKuList.slice(0, 100);
  1499. PreferencesUtil.putSync('mediaKuList', JSON.stringify(truncatedList));
  1500. } else {
  1501. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  1502. }
  1503. break;
  1504. case 103: //收到查询艺术家列表
  1505. this.isRefreshing = false
  1506. this.artistMap = e.data.data1;
  1507. this.artistList = e.data.data2;
  1508. PreferencesUtil.putSync('artistCount', this.artistList.length)
  1509. // 处理艺术家前100条记录,列表长度并存储到PreferencesUtil
  1510. if (ArrayUtil.isNotEmpty(this.artistList)&&this.artistList.length > 100) {
  1511. // 只保存前100条记录到缓存中
  1512. let truncatedList = this.artistList.slice(0, 100);
  1513. PreferencesUtil.putSync('artistList', JSON.stringify(truncatedList));
  1514. } else {
  1515. PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
  1516. }
  1517. // 处理并缓存前60条艺术家数据
  1518. const sortedEntries = Array.from(this.artistMap.entries())
  1519. .sort((a, b) => b[1].length - a[1].length)
  1520. .slice(0, 60);
  1521. PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
  1522. break;
  1523. case 104: //收到查询专辑列表
  1524. this.isRefreshing = false
  1525. this.albumMap = e.data.data1;
  1526. this.albumList = e.data.data2
  1527. //查询完毕在启动是否自动播放
  1528. if (this.isStartAutoPlay&&this.isCanAuto) {
  1529. this.isCanAuto = false
  1530. console.info('onecold startPlayOrResumePlay 757')
  1531. this.startPlayOrResumePlay()
  1532. }
  1533. PreferencesUtil.putSync('albumCount', this.albumList.length)
  1534. // 处理专辑前100条记录,列表长度并存储到PreferencesUtil
  1535. if (ArrayUtil.isNotEmpty(this.albumList)&&this.albumList.length > 100) {
  1536. // 只保存前100条记录到缓存中
  1537. let truncatedList = this.albumList.slice(0, 100);
  1538. PreferencesUtil.putSync('albumList', JSON.stringify(truncatedList));
  1539. } else {
  1540. PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
  1541. }
  1542. const mapArrayAlbum = Array.from(this.albumMap.entries())
  1543. .sort((a, b) => b[1].length - a[1].length)
  1544. .slice(0, 60);
  1545. PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
  1546. break;
  1547. case 105: // 缓存完成后返回的元数据
  1548. this.handleWorkerMetadataPayload(e.data.data as WorkerMetadataPayload);
  1549. break;
  1550. case 106: // 编辑音乐元数据和封面完成
  1551. this.handleEditMusicResult(e.data);
  1552. break;
  1553. }
  1554. };
  1555. // 在调用terminate后,执行onexit
  1556. workerInstance.onexit = (code) => {
  1557. metadataExtractionInFlight.clear();
  1558. Logger.info(TAG, 'workerInstance 线程已退出,code: ' + code);
  1559. }
  1560. workerInstance.onerror = (err: ErrorEvent) => {
  1561. metadataExtractionInFlight.clear();
  1562. console.error('workerInstance 线程执行发生异常: ' + err.message)
  1563. }
  1564. }
  1565. private handleWorkerMetadataPayload(payload: WorkerMetadataPayload | undefined): void {
  1566. if (!payload || !payload.originFilePath) {
  1567. return;
  1568. }
  1569. metadataExtractionInFlight.delete(payload.originFilePath);
  1570. if (payload.error) {
  1571. Logger.warn(TAG, `缓存文件元数据解析失败: ${payload.error}`);
  1572. return;
  1573. }
  1574. this.applyMetadataToCollections(payload.originFilePath, payload);
  1575. }
  1576. private applyMetadataToCollections(filePath: string, payload: WorkerMetadataPayload): void {
  1577. const targets: Array<VideoItem> = [];
  1578. let mainListUpdated = false;
  1579. let playlistUpdated = false;
  1580. if (this.currentSong && this.currentSong.filePath === filePath) {
  1581. targets.push(this.currentSong);
  1582. }
  1583. const collectFromList = (list?: Array<VideoItem>, markUpdated?: () => void) => {
  1584. if (!list || list.length === 0) {
  1585. return;
  1586. }
  1587. const found = Utility.getItemByFilePath(list, filePath);
  1588. if (found) {
  1589. markUpdated?.();
  1590. targets.push(found);
  1591. }
  1592. };
  1593. collectFromList(this.videoLocalList, () => {
  1594. mainListUpdated = true;
  1595. });
  1596. collectFromList(this.songList, () => {
  1597. playlistUpdated = true;
  1598. });
  1599. collectFromList(this.historyList);
  1600. collectFromList(this.favList);
  1601. const remoteManager = RemoteDriveManager.getInstance();
  1602. collectFromList(remoteManager.webDavSongs);
  1603. const updated = new Set<VideoItem>();
  1604. const remoteMetadataUpdates: Map<string, WebDavMetadataUpdatePayload> = new Map();
  1605. for (let i = 0; i < targets.length; i++) {
  1606. const target = targets[i];
  1607. if (!target || updated.has(target)) {
  1608. continue;
  1609. }
  1610. updated.add(target);
  1611. this.mergeVideoItemWithPayload(target, payload);
  1612. if (isRemoteCloudType(target.type) && StrUtil.isNotEmpty(target.filePath)) {
  1613. remoteMetadataUpdates.set(target.filePath, {
  1614. filePath: target.filePath,
  1615. pixelMapPath: target.pixelMapPath,
  1616. name: target.name,
  1617. artist: target.artist
  1618. });
  1619. }
  1620. }
  1621. if (this.currentSong && this.currentSong.filePath === filePath) {
  1622. this.mergeVideoItemWithPayload(this.currentSong, payload);
  1623. if (payload.name) {
  1624. this.name = payload.name;
  1625. }
  1626. if (payload.artist) {
  1627. this.artist = payload.artist;
  1628. }
  1629. if (payload.pixelMapPath) {
  1630. this.cover = payload.pixelMapPath;
  1631. }
  1632. if (payload.lyricContent) {
  1633. this.applyInlineLyricContent(payload.lyricContent);
  1634. }
  1635. let avSessionDurationMs = this.duration;
  1636. if (payload.duration) {
  1637. const durationSeconds = Number(payload.duration);
  1638. if (!Number.isNaN(durationSeconds) && durationSeconds > 0) {
  1639. avSessionDurationMs = durationSeconds * 1000;
  1640. this.duration = avSessionDurationMs;
  1641. this.durationTime = Math.floor(avSessionDurationMs / 1000);
  1642. this.durationStringTime = secondToTime(this.durationTime);
  1643. }
  1644. }
  1645. if (avSessionDurationMs > 0) {
  1646. this.avSessionController.setAVMetadataMusic(this.currentSong, avSessionDurationMs, this.lyricContent);
  1647. }
  1648. this.currentSong = cloneVideoItem(this.currentSong);
  1649. AppStorage.setOrCreate('currentSong', this.currentSong);
  1650. }
  1651. const primaryTarget = targets.length > 0 ? targets[0] : undefined;
  1652. if (primaryTarget) {
  1653. this.persistRemoteMetadataToDb(primaryTarget).catch((error: Error) => {
  1654. Logger.error(TAG, `缓存元数据持久化失败: ${error.message}`);
  1655. });
  1656. }
  1657. if (remoteMetadataUpdates.size > 0) {
  1658. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  1659. emitter.emit(eventUpdate, { data: Array.from(remoteMetadataUpdates.values()) });
  1660. }
  1661. this.refreshLazyListViews(mainListUpdated, playlistUpdated);
  1662. }
  1663. private handleEditMusicResult(result: WorkerEditMusicResult): void {
  1664. // 关闭进度条
  1665. DialogHelper.closeLoading();
  1666. if (result.success) {
  1667. console.log("heanup 编辑信息成功,数据库已同步");
  1668. if (result.coverResult) {
  1669. ToastUtil.showToast('内嵌封面成功');
  1670. }
  1671. ToastUtil.showToast('内嵌音乐标签成功');
  1672. this.isShowMoreView = false;
  1673. this.name = this.titleStr;
  1674. // 同步当前播放的歌曲信息
  1675. if (this.editingItem && this.editingItem.filePath == this.currentSong?.filePath) {
  1676. this.currentSong.name = this.titleStr;
  1677. this.artist = this.artistStr;
  1678. this.currentSong.artist = this.artistStr;
  1679. this.currentSong.album = this.ablumStr;
  1680. this.currentSong.year = this.yearStr;
  1681. this.currentSong.genre = this.genreStr;
  1682. this.currentSong.track = this.trackStr;
  1683. this.currentSong.lyricContent = this.lyricConStr;
  1684. this.currentSong.ALBUMARTIST = this.albumArtistStr;
  1685. this.currentSong.COMPOSER = this.composerStr;
  1686. this.currentSong.LYRICIST = this.lyricistStr;
  1687. this.currentSong.COMMENT = this.commentStr;
  1688. }
  1689. // if (result.needRefreshList && this.modeType == 0) {
  1690. // this.deleteCache(this.currentPath);
  1691. // this.getSortedFiles(this.currentPath);
  1692. // }
  1693. // 同步编辑字段到本地列表
  1694. if (this.editingItem) {
  1695. this.syncEditedFields(this.editingItem);
  1696. this.syncListsAfterEdit(this.editingItem.filePath);
  1697. this.doUpateEditedFields(this.editingItem);
  1698. }
  1699. // 清理临时变量
  1700. this.longItemFilePath = '';
  1701. this.tempLyricContent = '';
  1702. this.isShowEdit = false;
  1703. this.imagePathStr = '';
  1704. } else {
  1705. console.error("heanup 编辑信息失败: " + result.error);
  1706. ToastUtil.showToast('编辑失败: ' + (result.error || '未知错误'));
  1707. // 清理临时变量
  1708. this.longItemFilePath = '';
  1709. this.tempLyricContent = '';
  1710. this.isShowEdit = false;
  1711. this.imagePathStr = '';
  1712. }
  1713. }
  1714. private assignStringMetadata(target: VideoItem, key: keyof VideoItem, value?: string | null, allowEmpty = false): void {
  1715. if (value === undefined || value === null) {
  1716. return;
  1717. }
  1718. const text = value.toString();
  1719. if (!allowEmpty && text.trim().length === 0) {
  1720. return;
  1721. }
  1722. Reflect.set(target, key as string, value);
  1723. }
  1724. private assignNumberMetadata(target: VideoItem, key: keyof VideoItem, value?: number | null): void {
  1725. if (value === undefined || value === null || Number.isNaN(value)) {
  1726. return;
  1727. }
  1728. Reflect.set(target, key as string, value);
  1729. }
  1730. private mergeVideoItemWithPayload(target: VideoItem, payload: WorkerMetadataPayload): void {
  1731. if (!target || !payload) {
  1732. return;
  1733. }
  1734. this.assignStringMetadata(target, 'name', payload.name);
  1735. this.assignStringMetadata(target, 'artist', payload.artist);
  1736. this.assignStringMetadata(target, 'album', payload.album);
  1737. this.assignStringMetadata(target, 'bit_rate', payload.bit_rate);
  1738. this.assignStringMetadata(target, 'duration', payload.duration);
  1739. this.assignStringMetadata(target, 'sampleRate', payload.sampleRate);
  1740. this.assignStringMetadata(target, 'mimeType', payload.mimeType);
  1741. this.assignStringMetadata(target, 'size', payload.size);
  1742. this.assignStringMetadata(target, 'pixelMapPath', payload.pixelMapPath);
  1743. this.assignStringMetadata(target, 'lyricContent', payload.lyricContent, true);
  1744. this.assignStringMetadata(target, 'genre', payload.genre);
  1745. this.assignStringMetadata(target, 'track', payload.track);
  1746. this.assignStringMetadata(target, 'bits_per_raw_sample', payload.bits_per_raw_sample);
  1747. this.assignStringMetadata(target, 'channels', payload.channels);
  1748. this.assignStringMetadata(target, 'channel_layout', payload.channel_layout);
  1749. this.assignStringMetadata(target, 'start_time', payload.start_time);
  1750. this.assignStringMetadata(target, 'year', payload.year);
  1751. this.assignStringMetadata(target, 'disc', payload.disc);
  1752. this.assignStringMetadata(target, 'ALBUMARTIST', payload.ALBUMARTIST);
  1753. this.assignStringMetadata(target, 'COMPOSER', payload.COMPOSER);
  1754. this.assignStringMetadata(target, 'LYRICIST', payload.LYRICIST);
  1755. this.assignStringMetadata(target, 'COMMENT', payload.COMMENT, true);
  1756. this.assignNumberMetadata(target, 'videoSize', payload.videoSize);
  1757. this.assignNumberMetadata(target, 'probe_score', payload.probe_score);
  1758. this.assignNumberMetadata(target, 'nb_streams', payload.nb_streams);
  1759. this.assignNumberMetadata(target, 'nb_programs', payload.nb_programs);
  1760. }
  1761. private mergeVideoItemFromSource(target: VideoItem, source: VideoItem): void {
  1762. if (!target || !source) {
  1763. return;
  1764. }
  1765. this.assignStringMetadata(target, 'name', source.name);
  1766. this.assignStringMetadata(target, 'artist', source.artist);
  1767. this.assignStringMetadata(target, 'album', source.album);
  1768. this.assignStringMetadata(target, 'bit_rate', source.bit_rate);
  1769. this.assignStringMetadata(target, 'duration', source.duration);
  1770. this.assignStringMetadata(target, 'sampleRate', source.sampleRate);
  1771. this.assignStringMetadata(target, 'trackCount', source.trackCount);
  1772. this.assignStringMetadata(target, 'mimeType', source.mimeType);
  1773. this.assignStringMetadata(target, 'size', source.size);
  1774. this.assignStringMetadata(target, 'pixelMapPath', source.pixelMapPath);
  1775. this.assignStringMetadata(target, 'lyricContent', source.lyricContent, true);
  1776. this.assignStringMetadata(target, 'genre', source.genre);
  1777. this.assignStringMetadata(target, 'track', source.track);
  1778. this.assignStringMetadata(target, 'bits_per_raw_sample', source.bits_per_raw_sample);
  1779. this.assignStringMetadata(target, 'channels', source.channels);
  1780. this.assignStringMetadata(target, 'channel_layout', source.channel_layout);
  1781. this.assignStringMetadata(target, 'start_time', source.start_time);
  1782. this.assignStringMetadata(target, 'year', source.year);
  1783. this.assignStringMetadata(target, 'disc', source.disc);
  1784. this.assignStringMetadata(target, 'ALBUMARTIST', source.ALBUMARTIST);
  1785. this.assignStringMetadata(target, 'COMPOSER', source.COMPOSER);
  1786. this.assignStringMetadata(target, 'LYRICIST', source.LYRICIST);
  1787. this.assignStringMetadata(target, 'COMMENT', source.COMMENT, true);
  1788. this.assignNumberMetadata(target, 'videoSize', source.videoSize);
  1789. this.assignNumberMetadata(target, 'probe_score', source.probe_score);
  1790. this.assignNumberMetadata(target, 'nb_streams', source.nb_streams);
  1791. this.assignNumberMetadata(target, 'nb_programs', source.nb_programs);
  1792. if (source.remote_rel_path && StrUtil.isEmpty(target.remote_rel_path)) {
  1793. target.remote_rel_path = source.remote_rel_path;
  1794. }
  1795. }
  1796. private async hydrateRemoteSongFromDb(item: VideoItem | undefined): Promise<void> {
  1797. if (!item || !isRemoteCloudType(item.type)) {
  1798. return;
  1799. }
  1800. const storagePath = item.remote_rel_path || WebDavUrlUtil.toStoragePath(item.filePath);
  1801. if (!storagePath) {
  1802. return;
  1803. }
  1804. try {
  1805. const cached = await this.table.queryVideoByFilePath(storagePath);
  1806. if (!cached) {
  1807. return;
  1808. }
  1809. this.mergeVideoItemFromSource(item, cached);
  1810. if (StrUtil.isEmpty(item.remote_rel_path)) {
  1811. item.remote_rel_path = storagePath;
  1812. }
  1813. if (item === this.currentSong) {
  1814. if (StrUtil.isNotEmpty(item.name)) {
  1815. this.name = item.name;
  1816. }
  1817. if (StrUtil.isNotEmpty(item.artist)) {
  1818. this.artist = item.artist!;
  1819. }
  1820. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  1821. this.cover = item.pixelMapPath!;
  1822. }
  1823. if (StrUtil.isNotEmpty(item.lyricContent) && StrUtil.isEmpty(this.lyricContent)) {
  1824. this.applyInlineLyricContent(item.lyricContent as string);
  1825. }
  1826. }
  1827. } catch (error) {
  1828. Logger.error(TAG, `hydrateRemoteSongFromDb 失败: ${(error as Error).message}`);
  1829. }
  1830. }
  1831. private applyInlineLyricContent(content: string): void {
  1832. if (StrUtil.isEmpty(content)) {
  1833. return;
  1834. }
  1835. this.lyricContent = content;
  1836. const lines = content.split('\n').map(line => line.trim());
  1837. const lyric = this.parser.parse(lines);
  1838. this.lyricController.setLyric(lyric);
  1839. this.lyricControllerXF.setLyric(lyric);
  1840. this.lyricControllerSingle.setLyric(lyric);
  1841. }
  1842. private extractParentPathFromStoragePath(path: string): string {
  1843. if (!path) {
  1844. return '';
  1845. }
  1846. const lastSlash = path.lastIndexOf('/');
  1847. if (lastSlash <= 0) {
  1848. return '';
  1849. }
  1850. return path.substring(0, lastSlash);
  1851. }
  1852. private resolveRemoteStoragePath(target: VideoItem): string | null {
  1853. if (!target || !isRemoteCloudType(target.type)) {
  1854. return null;
  1855. }
  1856. if (isWebDavType(target.type)) {
  1857. const storagePath = target.remote_rel_path || WebDavUrlUtil.toStoragePath(target.filePath);
  1858. if (storagePath) {
  1859. target.remote_rel_path = storagePath;
  1860. return storagePath;
  1861. }
  1862. return null;
  1863. }
  1864. if (target.remote_rel_path && target.remote_rel_path.length > 0) {
  1865. return target.remote_rel_path;
  1866. }
  1867. return null;
  1868. }
  1869. private async persistRemoteMetadataToDb(target: VideoItem): Promise<void> {
  1870. if (!this.context || !target || !isRemoteCloudType(target.type)) {
  1871. return;
  1872. }
  1873. const storagePath = this.resolveRemoteStoragePath(target);
  1874. if (!storagePath) {
  1875. return;
  1876. }
  1877. const table = new MediaTable(this.context);
  1878. await new Promise<void>((resolve) => {
  1879. table.getRdbStore(this.context as Context, () => resolve());
  1880. });
  1881. const cloneItem = cloneVideoItem(target);
  1882. cloneItem.filePath = storagePath;
  1883. cloneItem.remote_rel_path = storagePath;
  1884. cloneItem.parentPath = this.extractParentPathFromStoragePath(storagePath);
  1885. await table.saveOrUpdateWebDavItem(cloneItem);
  1886. }
  1887. onPageHide(): void {
  1888. this.knockController?.immersiveDisableListening();
  1889. }
  1890. @State isFirstStartPlay: boolean = false
  1891. private async startFileDeletionWatcher(): Promise<void> {
  1892. if (!this.rootPath) {
  1893. return;
  1894. }
  1895. if (!this.deletionWatcher) {
  1896. this.deletionWatcher = new FileDeletionWatcher(this.context, this.table);
  1897. }
  1898. try {
  1899. await this.deletionWatcher.watchDirectories([
  1900. this.rootPath,
  1901. this.lockPath,
  1902. this.favPath,
  1903. this.historyPath
  1904. ]);
  1905. } catch (error) {
  1906. Logger.error(TAG, `初始化文件删除监听失败: ${(error as Error).message}`);
  1907. }
  1908. }
  1909. //获取download_path
  1910. async mkDownLoadDir() {
  1911. const documentViewPicker = new picker.DocumentViewPicker()
  1912. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  1913. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  1914. PreferencesUtil.putSync('download_path', this.rootPath+'/')
  1915. this.currentPath = this.rootPath
  1916. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  1917. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  1918. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  1919. Logger.info('onecold rootPath = ' + this.rootPath)
  1920. Logger.info('onecold lockPath = ' + this.lockPath)
  1921. if (!FileUtil.accessSync(this.lockPath)) {
  1922. FileUtil.mkdirSync(this.lockPath)
  1923. }
  1924. if (!FileUtil.accessSync(this.favPath)) {
  1925. FileUtil.mkdirSync(this.favPath)
  1926. }
  1927. if (!FileUtil.accessSync(this.historyPath)) {
  1928. FileUtil.mkdirSync(this.historyPath)
  1929. }
  1930. // await this.startFileDeletionWatcher();
  1931. this.getSortedFiles(this.rootPath).then(async () => {
  1932. this.isFavMusic = false
  1933. //穿山甲
  1934. // this.loadBannerAd(CSJUtil.getBannerID())
  1935. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  1936. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  1937. if (ArrayUtil.isEmpty(this.songList)) {
  1938. this.songList = this.getCurFileList()
  1939. } else {
  1940. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  1941. }
  1942. if (ArrayUtil.isNotEmpty(this.songList)) {
  1943. this.isFirstStartPlay = true
  1944. this.sonDataSource.pushArrayData(this.songList)
  1945. if (this.currentSong === undefined) {
  1946. this.isFirstStartPlay = false
  1947. this.currentSong = this.songList[0]
  1948. }
  1949. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  1950. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  1951. context: this.context,
  1952. autoParseMusicName: this.autoParseMusicName
  1953. });
  1954. Logger.info(TAG, `WebDAV URL同步构建完成: ${this.videoUrl}`);
  1955. this.name = this.currentSong.name
  1956. this.cover = this.currentSong.pixelMapPath
  1957. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  1958. } else {
  1959. this.name = '空空如也'
  1960. }
  1961. })
  1962. this.getFavList(false)
  1963. }
  1964. getFavList(isFavRefresh: boolean) {
  1965. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  1966. this.favList = result
  1967. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  1968. this.videoLocalList = this.favList
  1969. this.updateListData(this.videoLocalList)
  1970. }
  1971. })
  1972. }
  1973. getHistoryList(isRefresh: boolean) {
  1974. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  1975. this.historyList = result
  1976. // for (let i = 0; i < this.historyList.length; i++) {
  1977. //
  1978. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  1979. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  1980. // }
  1981. if (isRefresh) {
  1982. this.videoLocalList = this.historyList
  1983. this.updateListData(this.videoLocalList, true)
  1984. }
  1985. })
  1986. }
  1987. // 组件消失生命周期
  1988. aboutToDisappear() {
  1989. console.info('LifeCycleComponent aboutToDisappear');
  1990. this.deletionWatcher?.stop();
  1991. this.knockController?.immersiveDisableListening();
  1992. this.curIndex = 0
  1993. emitter.off(EventConstants.EVENT_AUDIO_OPEN);
  1994. emitter.off(EventConstants.EVENT_SCAN_UPDATE);
  1995. emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
  1996. emitter.off(EventConstants.EVENT_SETTING_UPDATE);
  1997. this.mDestroyPage = true;
  1998. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  1999. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  2000. this.stop();
  2001. }
  2002. this.mIjkMediaPlayer.off('audioInterrupt');
  2003. this.mIjkMediaPlayer.off('deviceChange');
  2004. if (workerInstance) {
  2005. workerInstance.terminate();
  2006. }
  2007. this.stopPip();
  2008. this.destroyPipController()
  2009. this.getUIContext().getHostContext()!.eventHub.off('playOrPause');
  2010. this.getUIContext().getHostContext()!.eventHub.off('playPrevious');
  2011. this.getUIContext().getHostContext()!.eventHub.off('playNext');
  2012. this.getUIContext().getHostContext()!.eventHub.off('showPlayerView');
  2013. this.getUIContext().getHostContext()!.eventHub.off('openPlayList');
  2014. }
  2015. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean,openItem?:VideoItem) {
  2016. this.isFavMusic = false
  2017. console.info('onecold getSortedFiles 1 curPath '+curPath)
  2018. if (isWorkerPost) {
  2019. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  2020. }
  2021. if (this.modeType !== 0) {
  2022. return
  2023. }
  2024. console.info('onecold getSortedFiles 2')
  2025. this.isCanBack = false
  2026. this.currentPath = curPath
  2027. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  2028. this.titleName = getFileDirName(this.currentPath,this.rootPath)
  2029. if (curPath === this.rootPath) {
  2030. this.rightTopImage = $r('sys.symbol.sort')
  2031. } else {
  2032. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  2033. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  2034. this.rightTopImage = $r('sys.symbol.chevron_left')
  2035. }
  2036. }
  2037. // Get the current file list and calculate its hash
  2038. this.fileList = FileUtil.listFileSync(curPath);
  2039. const currentHash = simpleHash(this.fileList);
  2040. // Check cache
  2041. const cachedValue = this.findCache(curPath);
  2042. Logger.info('onecold cachedValue = ' + cachedValue)
  2043. const cachedHash = this.findStringCache(curPath + '_hash');
  2044. const cachedDirList = this.findCache(curPath + "_dirList");
  2045. if (cachedValue !== undefined&&!this.isRefreshing) {
  2046. // this.videoLocalList = cachedValue;
  2047. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  2048. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  2049. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  2050. }
  2051. this.isRefreshing = false
  2052. this.updateListData(cachedValue)
  2053. }
  2054. if (cachedDirList !== undefined) {
  2055. this.dirList = cachedDirList
  2056. }
  2057. //通过当前hash值和缓存hash判断list有没有变化
  2058. if (cachedValue && cachedHash === currentHash) {
  2059. return;
  2060. }
  2061. // this.fileList = FileUtil.listFileSync(curPath)
  2062. let directories: Array<VideoItem> = [];
  2063. let files: Array<VideoItem> = [];
  2064. for (let i = 0; i < this.fileList.length; i++) {
  2065. console.info(`The name of file: ${this.fileList[i]}`);
  2066. let path = curPath + '/' + this.fileList[i]
  2067. if (FileUtil.isDirectory(path)) {
  2068. let item: VideoItem =
  2069. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  2070. '')
  2071. if (this.isShowDir(item.name)) {
  2072. directories.push(item);
  2073. }
  2074. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2075. // Utility.doSortListAscending(directories)
  2076. } else {
  2077. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  2078. let item: VideoItem =
  2079. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  2080. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  2081. files.push(item);
  2082. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2083. // this.doSortListAscending(files)
  2084. }
  2085. }
  2086. }
  2087. }
  2088. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  2089. if (this.currentPath !== this.lockPath) {
  2090. files = result;
  2091. }
  2092. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2093. Utility.doSortListAscending(files)
  2094. if (this.currentPath === this.rootPath) {
  2095. this.dirList = directories
  2096. this.addCache(curPath + "_dirList", this.dirList);
  2097. }
  2098. //插入广告先注释掉
  2099. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  2100. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  2101. // directories.push(adItem)
  2102. // }
  2103. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  2104. this.videoLocalList = directories.concat(files);
  2105. this.updateListData(this.videoLocalList)
  2106. if (ArrayUtil.isNotEmpty(files)) {
  2107. if (this.currentPath != this.rootPath) {
  2108. if (files) {
  2109. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  2110. }
  2111. }
  2112. // 缓存结果
  2113. this.addCache(curPath, this.videoLocalList);
  2114. await this.saveCacheToStorage(); // 保存缓存至本地存储
  2115. this.addStringCache(curPath + '_hash', currentHash);
  2116. }
  2117. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  2118. for (let i = 0; i < this.videoLocalList.length; i++) {
  2119. console.info(`onecold gengxin 1: ${this.videoLocalList[i].name}`);
  2120. }
  2121. // this.setButtonStatus()
  2122. this.openMusic(isOpen, destPath,openItem)
  2123. this.isRefreshing = false
  2124. });
  2125. }
  2126. //第三方app打开天天静听导入音乐后播放
  2127. openMusic(isOpen?: boolean, destPath?: string,openItem?:VideoItem){
  2128. if (isOpen&&destPath) {
  2129. if (destPath === undefined) {
  2130. // 处理 destPath 为 undefined 的情况
  2131. return
  2132. }
  2133. if (destPath.endsWith('.lrc')) {
  2134. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  2135. if (StrUtil.isNotEmpty(this.videoUrl)) {
  2136. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  2137. this.initLyric(lyricPath);
  2138. }
  2139. return
  2140. }
  2141. if(openItem){
  2142. this.doPlay(openItem,0,false,true)
  2143. // this.isShowPlay = true
  2144. this.setShowPlayTrue()
  2145. }
  2146. }
  2147. }
  2148. //扫描文件夹入库
  2149. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  2150. const files = FileUtil.listFileSync(curPath);
  2151. let mediaItems: VideoItem[] = [];
  2152. Logger.info('onecold scanDirectory start ')
  2153. for (const file of files) {
  2154. const fPath = `${curPath}/${file}`;
  2155. if (fPath === this.lockPath) {
  2156. Logger.info(`Skipping locked path: ${fPath}`);
  2157. continue;
  2158. }
  2159. if (FileUtil.isDirectory(fPath)) {
  2160. // Recursively scan subdirectories
  2161. const subDirItems = await this.scanDirectory(fPath);
  2162. mediaItems = mediaItems.concat(subDirItems);
  2163. } else {
  2164. Logger.info('onecold scanDirectory filePath = ' + fPath)
  2165. // Process media files
  2166. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  2167. let mediaItem: VideoItem =
  2168. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2169. mediaItems.push(mediaItem);
  2170. this.table.insert(mediaItem, (id: number) => {
  2171. });
  2172. }
  2173. }
  2174. }
  2175. return mediaItems;
  2176. }
  2177. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  2178. animateTo({ duration: 666 }, () => {
  2179. this.opacityItem = 0.5;
  2180. });
  2181. setTimeout(() => {
  2182. this.videoLocalList = mList;
  2183. if (!noSort) {
  2184. if (this.modeType === 0 || this.modeType === 1) {
  2185. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  2186. this.doSortType(this.sortType)
  2187. }
  2188. }
  2189. this.dataSource.pushArrayData(this.videoLocalList)
  2190. animateTo({ duration: 666 }, () => {
  2191. this.opacityItem = 1;
  2192. });
  2193. this.setButtonStatus()
  2194. //添加到字母索引表
  2195. this.setAlphaBet()
  2196. }, 200);
  2197. }
  2198. getCurFileList(): Array<VideoItem> {
  2199. if(this.isSearchMode){
  2200. return this.filteredList
  2201. }
  2202. let files: Array<VideoItem> = [];
  2203. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2204. for (let i = 0; i < this.videoLocalList.length; i++) {
  2205. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  2206. files.push(this.videoLocalList[i]);
  2207. }
  2208. }
  2209. }
  2210. return files
  2211. }
  2212. setButtonStatus() {
  2213. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2214. this.isZero = false
  2215. } else {
  2216. this.isZero = true
  2217. }
  2218. if (this.currentPath !== this.rootPath &&
  2219. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  2220. this.isHasDir = true //不为空,说明有子文件夹
  2221. } else {
  2222. this.isHasDir = false
  2223. }
  2224. }
  2225. @Builder
  2226. SortMenuBuilder() {
  2227. Menu() {
  2228. MenuItem({
  2229. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2230. content: "按艺术家升序"
  2231. })
  2232. .onClick(async () => {
  2233. this.doSortType(0)
  2234. PreferencesUtil.put(SettingPage.SORT_TYPE, 0)
  2235. this.updateListData(this.videoLocalList, true)
  2236. })
  2237. MenuItem({
  2238. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2239. content: "按艺术家降序"
  2240. })
  2241. .onClick(async () => {
  2242. this.doSortType(1)
  2243. PreferencesUtil.put(SettingPage.SORT_TYPE, 1)
  2244. this.updateListData(this.videoLocalList, true)
  2245. })
  2246. MenuItem({
  2247. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat_size_square')),
  2248. content: "按专辑升序"
  2249. })
  2250. .onClick(async () => {
  2251. this.doSortType(2)
  2252. PreferencesUtil.put(SettingPage.SORT_TYPE, 2)
  2253. this.updateListData(this.videoLocalList, true)
  2254. })
  2255. MenuItem({
  2256. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.character_arrow_clockwise')),
  2257. content: "按专辑降序"
  2258. })
  2259. .onClick(async () => {
  2260. this.doSortType(3)
  2261. PreferencesUtil.put(SettingPage.SORT_TYPE, 3)
  2262. this.updateListData(this.videoLocalList, true)
  2263. })
  2264. MenuItem({
  2265. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2266. content: $r('app.string.sort_by_name')
  2267. })
  2268. .onClick(async () => {
  2269. this.doSortType(4)
  2270. PreferencesUtil.put(SettingPage.SORT_TYPE, 4)
  2271. this.updateListData(this.videoLocalList, true)
  2272. })
  2273. MenuItem({
  2274. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2275. content: '按名称降序'
  2276. })
  2277. .onClick(async () => {
  2278. this.doSortType(5)
  2279. PreferencesUtil.put(SettingPage.SORT_TYPE, 5)
  2280. this.updateListData(this.videoLocalList, true)
  2281. })
  2282. MenuItem({
  2283. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2284. content: $r('app.string.sort_by_time')
  2285. })
  2286. .onClick(async () => {
  2287. this.doSortType(6)
  2288. PreferencesUtil.put(SettingPage.SORT_TYPE, 6)
  2289. this.updateListData(this.videoLocalList, true)
  2290. })
  2291. MenuItem({
  2292. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  2293. content: '按添加时间降序'
  2294. })
  2295. .onClick(async () => {
  2296. this.doSortType(7)
  2297. PreferencesUtil.put(SettingPage.SORT_TYPE, 7)
  2298. this.updateListData(this.videoLocalList, true)
  2299. })
  2300. }.attributeModifier(new MenuModifier())
  2301. }
  2302. @Builder
  2303. SortMenuForArtistAblumBuilder() {
  2304. Menu() {
  2305. MenuItem({
  2306. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2307. content: $r('app.string.sort_by_name')
  2308. })
  2309. .onClick(async () => {
  2310. this.doSortType(4)
  2311. // PreferencesUtil.put(SettingPage.SORT_TYPE, 2)
  2312. this.updateListData(this.videoLocalList, true)
  2313. })
  2314. MenuItem({
  2315. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2316. content: '按名称降序'
  2317. })
  2318. .onClick(async () => {
  2319. this.doSortType(5)
  2320. this.updateListData(this.videoLocalList, true)
  2321. })
  2322. MenuItem({
  2323. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2324. content: '按数量升序'
  2325. })
  2326. .onClick(async () => {
  2327. this.doSortType(8)
  2328. this.updateListData(this.videoLocalList, true)
  2329. })
  2330. MenuItem({
  2331. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  2332. content: '按数量降序'
  2333. })
  2334. .onClick(async () => {
  2335. this.doSortType(9)
  2336. this.updateListData(this.videoLocalList, true)
  2337. })
  2338. }.attributeModifier(new MenuModifier())
  2339. }
  2340. doSortType(index: number) {
  2341. switch (index) {
  2342. case 0:
  2343. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2344. // 类型排序优先级
  2345. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2346. if (typeOrder !== 0) {
  2347. return typeOrder;
  2348. }
  2349. // 处理艺术家可能为undefined的字符串比较
  2350. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  2351. const artistB = b.artist?.trim() || '';
  2352. return artistA.localeCompare(artistB);
  2353. });
  2354. break;
  2355. case 1:
  2356. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2357. // 类型排序优先级
  2358. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2359. if (typeOrder !== 0) {
  2360. return typeOrder;
  2361. }
  2362. // 处理艺术家可能为undefined的字符串比较
  2363. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  2364. const artistB = b.artist?.trim() || '';
  2365. return artistB.localeCompare(artistA);
  2366. });
  2367. break;
  2368. case 2:
  2369. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2370. // 类型排序优先级
  2371. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2372. if (typeOrder !== 0) {
  2373. return typeOrder;
  2374. }
  2375. // 处理专辑可能为undefined的字符串比较
  2376. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  2377. const albumB = b.album?.trim() || '';
  2378. return albumA.localeCompare(albumB);
  2379. });
  2380. break;
  2381. case 3:
  2382. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2383. // 类型排序优先级
  2384. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2385. if (typeOrder !== 0) {
  2386. return typeOrder;
  2387. }
  2388. // 处理专辑可能为undefined的字符串比较
  2389. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  2390. const albumB = b.album?.trim() || '';
  2391. return albumB.localeCompare(albumA);
  2392. });
  2393. break;
  2394. case 4:
  2395. Utility.doSortListAscending(this.videoLocalList,this.isShowFileName)
  2396. break;
  2397. case 5:
  2398. Utility.doSortListDescending(this.videoLocalList,this.isShowFileName)
  2399. break;
  2400. case 6:
  2401. this.videoLocalList.sort((a, b) => {
  2402. // First, sort by type
  2403. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2404. if (typeOrder !== 0) {
  2405. return typeOrder;
  2406. }
  2407. // If types are the same, sort by cTime in ascending order
  2408. return a.cTime.localeCompare(b.cTime);
  2409. });
  2410. break;
  2411. case 7:
  2412. this.videoLocalList.sort((a, b) => {
  2413. // First, sort by type
  2414. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2415. if (typeOrder !== 0) {
  2416. return typeOrder;
  2417. }
  2418. // If types are the same, sort by cTime in descending order
  2419. return b.cTime.localeCompare(a.cTime);
  2420. });
  2421. break;
  2422. case 8:
  2423. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  2424. // 1. Sort by type first
  2425. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  2426. if (typeOrder !== 0) {
  2427. return typeOrder;
  2428. }
  2429. // 2. Then sort by artist count (numeric comparison)
  2430. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  2431. if(this.modeType === 2){
  2432. sortMap = this.artistMap
  2433. }else{
  2434. sortMap = this.albumMap
  2435. }
  2436. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  2437. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  2438. return aArtistCount - bArtistCount;
  2439. });
  2440. break;
  2441. case 9:
  2442. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  2443. // 1. Sort by type first
  2444. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  2445. if (typeOrder !== 0) {
  2446. return typeOrder;
  2447. }
  2448. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  2449. if(this.modeType === 2){
  2450. sortMap = this.artistMap
  2451. }else{
  2452. sortMap = this.albumMap
  2453. }
  2454. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  2455. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  2456. return bArtistCount - aArtistCount;
  2457. });
  2458. break;
  2459. }
  2460. }
  2461. showSheelDialog() {
  2462. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  2463. // this.showTips()
  2464. // return
  2465. // }
  2466. this.showAddDialog()
  2467. }
  2468. showAddDialog() {
  2469. if (this.modeType === 2 || this.modeType === 3) {
  2470. return
  2471. }
  2472. DialogHelper.showActionSheetDialog({
  2473. title: "请选择添加方式(建议歌词文件一起导入)",
  2474. sheets: [
  2475. { value: "新建文件夹", fontColor: $r('app.color.text_color') },
  2476. { value: "手动导入", fontColor: $r('app.color.text_color') },
  2477. { value: "自动导入", fontColor: $r('app.color.text_color') },
  2478. { value: "全选导入", fontColor: $r('app.color.text_color') },
  2479. ],
  2480. maskColor: Color.Transparent,
  2481. backgroundColor: $r('app.color.bg_card'),
  2482. transition: AnimationHelper.transitionInDown(555),
  2483. onAction: (index) => {
  2484. switch (index) {
  2485. case 0:
  2486. if (this.modeType === 0) {
  2487. this.showMkDialog()
  2488. } else {
  2489. ToastUtil.showToast('请切换到首页才能新建文件夹!')
  2490. }
  2491. break;
  2492. case 1:
  2493. this.callFilePickerSelectFile()
  2494. break;
  2495. case 2:
  2496. this.showTips()
  2497. break;
  2498. case 3:
  2499. this.goSelectMusic()
  2500. break;
  2501. }
  2502. }
  2503. })
  2504. }
  2505. //拉起音频
  2506. goSelectMusic() {
  2507. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  2508. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  2509. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  2510. ) {
  2511. ToastUtil.showToast('暂时不支持该设备')
  2512. return
  2513. }
  2514. try {
  2515. let documentSelectOptions = new picker.DocumentSelectOptions();
  2516. documentSelectOptions.authMode = true
  2517. documentSelectOptions.multiAuthMode = true
  2518. if( deviceInfo.sdkApiVersion>=21){//如果api大于21 ,可以支持1w首歌以上
  2519. documentSelectOptions.maxSelectNumber = 20000
  2520. }
  2521. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  2522. let documentPicker = new picker.DocumentViewPicker(this.context);
  2523. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  2524. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  2525. this.saveVideoDatas(documentSelectResult)
  2526. }
  2527. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  2528. JSON.stringify(documentSelectResult));
  2529. }).catch((err: BusinessError) => {
  2530. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  2531. });
  2532. } catch (error) {
  2533. let err: BusinessError = error as BusinessError;
  2534. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2535. }
  2536. }
  2537. async showTips() {
  2538. try {
  2539. this.getUIContext().getPromptAction().showDialog({
  2540. title: '导入指南',
  2541. message:'用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2542. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2543. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2544. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后去文件扫描一下。\n',
  2545. buttons: [
  2546. {
  2547. text: '知道了',
  2548. color: '#000000'
  2549. },
  2550. ]
  2551. }, (err, data) => {
  2552. if (err) {
  2553. console.error('showDialog err: ' + err);
  2554. return;
  2555. }
  2556. console.info('showDialog success callback, click button: ' + data.index);
  2557. });
  2558. } catch (error) {
  2559. let message = (error as BusinessError).message;
  2560. let code = (error as BusinessError).code;
  2561. console.error(`showDialog args error code is ${code}, message is ${message}`);
  2562. };
  2563. // DialogHelper.showTipsDialog({
  2564. // title: '使用提示:自动导入教程',
  2565. //
  2566. // content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2567. // + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2568. // '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2569. // '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  2570. // onAction: (action) => {
  2571. // if (action == DialogAction.TWO) {
  2572. // PreferencesUtil.putSync('isFirstMusic', false)
  2573. // router.pushUrl({
  2574. // url: 'pages/ScanFilePage'
  2575. // });
  2576. // }
  2577. // }
  2578. // })
  2579. }
  2580. showMkDialog() {
  2581. DialogHelper.showTextInputDialog({
  2582. title: '新建歌单',
  2583. maskColor: Color.Transparent,
  2584. text: '',
  2585. transition: AnimationHelper.transitionInDown(666),
  2586. onChange: (text) => {
  2587. console.error("onChange: " + text);
  2588. },
  2589. onAction: (action, dialogId, content) => {
  2590. // ToastUtil.showToast('content = ' +content)
  2591. if (action == DialogAction.TWO) {
  2592. const newName = content
  2593. const newPath = this.currentPath + '/' + newName
  2594. FileUtil.mkdir(newPath, true).then(() => {
  2595. this.cache.delete(this.currentPath); // 删除目标路径缓存
  2596. this.getSortedFiles(this.currentPath)
  2597. }).catch((error: BusinessError) => {
  2598. console.error(error.message);
  2599. });
  2600. }
  2601. }
  2602. })
  2603. }
  2604. @State progress: number = 0;
  2605. async saveVideoDatas(uris:string[],isOpen?:boolean){
  2606. if (ArrayUtil.isEmpty(uris)) {
  2607. return;
  2608. }
  2609. console.info('onecold this.isCopyFileToDownLoad = ' + this.isCopyFileToDownLoad);
  2610. if(this.isCopyFileToDownLoad||this.currentPath==this.lockPath||isOpen){
  2611. this.saveVideoDatasToDownLoad(uris,isOpen)
  2612. return
  2613. }
  2614. // 初始化进度条
  2615. this.progress = 0;
  2616. DialogHelper.showLoadingProgress({
  2617. progress: this.progress,
  2618. backCancel: false,
  2619. autoCancel: false,
  2620. loadColor: $r('app.color.title_bar_bg'),
  2621. fontColor: $r('app.color.title_bar_bg')
  2622. });
  2623. // 计算处理总数用于进度计算
  2624. const totalItems = uris.length;
  2625. let processedItems = 0;
  2626. for (let i = 0; i < uris.length; i++) {
  2627. let filePath = uris[i];
  2628. try {
  2629. if (this.currentPath !== this.lockPath) { // 判断不是私密音乐,才入库
  2630. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2631. let mediaItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context,
  2632. filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2633. console.info('onecold saveVideoDatas filePath = ' + filePath)
  2634. if (!filePath.includes(this.rootPath)) {
  2635. console.info('onecold saveVideoDatas mediaItem.parentPath111 = ' + mediaItem.parentPath)
  2636. mediaItem.parentPath = this.currentPath;
  2637. }
  2638. console.info('onecold saveVideoDatas mediaItem.parentPath = ' + mediaItem.parentPath)
  2639. this.table.insert(mediaItem, (id: number) => {
  2640. // 插入完成回调
  2641. });
  2642. }
  2643. }
  2644. // 更新进度
  2645. processedItems++;
  2646. this.progress = Math.floor((processedItems / totalItems) * 100);
  2647. DialogHelper.updateLoading(' 正在处理', this.progress);
  2648. } catch (error) {
  2649. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2650. // 即使出错也更新进度
  2651. processedItems++;
  2652. this.progress = Math.floor((processedItems / totalItems) * 100);
  2653. DialogHelper.updateLoading(' 正在处理', this.progress);
  2654. }
  2655. }
  2656. // 关闭进度条
  2657. DialogHelper.closeLoading();
  2658. this.isZero = false
  2659. // 删除目标路径缓存
  2660. setTimeout(() => {
  2661. this.cache.delete(this.currentPath);
  2662. this.getSortedFiles(this.currentPath,false,uris[0],isOpen)
  2663. this.setButtonStatus()
  2664. }, 500);
  2665. }
  2666. async saveVideoDatasToDownLoad(uris: string[], isOpen?: boolean) {
  2667. if (ArrayUtil.isEmpty(uris)) {
  2668. return;
  2669. }
  2670. let newUris: string[] = [];
  2671. this.progress = 0
  2672. DialogHelper.showLoadingProgress({
  2673. progress: this.progress,
  2674. backCancel: false,
  2675. autoCancel: false,
  2676. loadColor: this.themeColor,
  2677. fontColor: this.themeColor
  2678. });
  2679. // 计算所有文件的总大小
  2680. let totalSize = 0;
  2681. for (let uri of uris) {
  2682. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  2683. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  2684. await fileIo.close(sourceFile.fd);
  2685. }
  2686. let totalRead = 0;
  2687. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  2688. Logger.info(TAG, 'destPath uri: ' + destPath);
  2689. for (let i = 0; i < uris.length; i++) {
  2690. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  2691. Logger.info(TAG, 'filePath uri: ' + filePath);
  2692. newUris.push(filePath);
  2693. try {
  2694. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  2695. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  2696. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  2697. const buffer = new ArrayBuffer(buffSize);
  2698. let len = await fileIo.read(sourceFile.fd, buffer);
  2699. while (len > 0) {
  2700. await fileIo.write(destFile.fd, buffer.slice(0, len));
  2701. totalRead += len;
  2702. // 计算总进度
  2703. this.progress = Math.floor((totalRead / totalSize) * 100);
  2704. DialogHelper.updateLoading('正在导入', this.progress);
  2705. len = await fileIo.read(sourceFile.fd, buffer);
  2706. }
  2707. await fileIo.close(sourceFile.fd);
  2708. await fileIo.close(destFile.fd);
  2709. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  2710. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2711. let mediaItem: VideoItem =
  2712. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2713. this.table.insert(mediaItem, (id: number) => {
  2714. // 删除目标路径缓存
  2715. this.cache.delete(this.currentPath);
  2716. this.getSortedFiles(this.currentPath, true, destPath, isOpen,mediaItem)
  2717. });
  2718. }
  2719. }
  2720. } catch (error) {
  2721. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2722. }
  2723. }
  2724. DialogHelper.closeLoading()
  2725. this.isZero = false
  2726. // setTimeout(() => {
  2727. // // 删除目标路径缓存
  2728. // this.cache.delete(this.currentPath);
  2729. // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
  2730. // }, 500);
  2731. Logger.info(TAG, 'scan select video result:' + newUris)
  2732. }
  2733. //拉起音频
  2734. // goSelectMusic(){
  2735. //
  2736. // try {
  2737. // let audioSelectOptions = new picker.AudioSelectOptions();
  2738. // let audioPicker = new picker.AudioViewPicker(this.context);
  2739. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  2740. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  2741. // this.saveVideoDatas(audioSelectResult)
  2742. // }
  2743. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  2744. // }).catch((err: BusinessError) => {
  2745. //
  2746. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  2747. // });
  2748. // } catch (error) {
  2749. // let err: BusinessError = error as BusinessError;
  2750. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2751. // }
  2752. //
  2753. //
  2754. //
  2755. // }
  2756. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  2757. if (!item) {
  2758. return undefined;
  2759. }
  2760. try {
  2761. let selectUris: Array<string> = [];
  2762. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  2763. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  2764. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  2765. photoSelectOptions.maxSelectNumber = 1;
  2766. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  2767. selectUris = photoSelectResult.photoUris;
  2768. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  2769. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  2770. console.info('file fd: ' + file.fd);
  2771. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  2772. let imagePath = this.context.filesDir + FileUtil.separator + name
  2773. imagePath = fileUri.getUriFromPath(imagePath)
  2774. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  2775. fileIo.copyFileSync(file.fd, file2.fd)
  2776. fileIo.closeSync(file);
  2777. fileIo.closeSync(file2);
  2778. if (item.filePath == this.currentSong?.filePath) {
  2779. this.cover = imagePath
  2780. }
  2781. if (item) {
  2782. item.pixelMapPath = imagePath
  2783. }
  2784. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  2785. if (success) {
  2786. this.doUpdateData()
  2787. console.log("onecold 更新音乐封面成功,数据库已同步");
  2788. } else {
  2789. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  2790. }
  2791. });
  2792. LogUtil.debug("onecold this.cover =" + this.cover)
  2793. return FileUtil.getFilePath(imagePath); // Return the image path here
  2794. } catch (err) {
  2795. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  2796. return undefined;
  2797. }
  2798. }
  2799. // 拉起picker选择文件管理器
  2800. async callFilePickerSelectFile(): Promise<void> {
  2801. try {
  2802. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  2803. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  2804. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  2805. } else {
  2806. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  2807. }
  2808. let documentPicker = new picker.DocumentViewPicker();
  2809. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  2810. Logger.info(TAG,
  2811. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  2812. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  2813. this.saveVideoDatas(DocumentSelectResult)
  2814. }
  2815. }).catch((err: BusinessError) => {
  2816. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  2817. });
  2818. } catch (err) {
  2819. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  2820. }
  2821. }
  2822. //重命名的对话框
  2823. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  2824. if(!item.filePath.includes(this.packName)){
  2825. ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限重命名')
  2826. return
  2827. }
  2828. DialogHelper.showTextInputDialog({
  2829. title: '重命名',
  2830. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  2831. maskColor: Color.Transparent,
  2832. backgroundColor: Color.Grey,
  2833. transition: AnimationHelper.transitionInDown(666),
  2834. onChange: (text) => {
  2835. console.error("onChange: " + text);
  2836. },
  2837. onAction: (action, dialogId, content) => {
  2838. // ToastUtil.showToast('content = ' +content)
  2839. if (action == DialogAction.TWO) {
  2840. const newName = content
  2841. const newPath = this.currentPath + '/' + newName
  2842. console.log("onecold item = " + item.type);
  2843. this.doReName(index, newName, filePath, newPath, item)
  2844. }
  2845. }
  2846. })
  2847. }
  2848. //剪切 移动到另个文件夹的对话框
  2849. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2850. Logger.info('onecold showCutDialog')
  2851. let mList: Array<string> = []
  2852. let rPath = this.rootPath
  2853. if (isCurrent) {
  2854. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2855. rPath = this.currentPath
  2856. } else {
  2857. mList = Utility.getNameList(this.dirList);
  2858. rPath = this.rootPath
  2859. }
  2860. let dataBean = new BubbleBean()
  2861. dataBean.data = mList
  2862. dataBean.color = this.themeColor
  2863. dataBean.onItemClick = (i) => {
  2864. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2865. Logger.info('newPath = ' + newPath)
  2866. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  2867. ToastUtil.showToast('移动成功')
  2868. this.table.deleteData(item, () => {
  2869. });
  2870. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2871. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2872. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2873. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2874. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2875. this.table.insert(newItem, (id: number) => {
  2876. //加入数据库
  2877. });
  2878. }
  2879. this.cache.delete(this.currentPath); // 删除原路径缓存
  2880. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2881. this.getSortedFiles(this.currentPath, true)
  2882. }).catch((error: BusinessError) => {
  2883. console.error(error.message);
  2884. });
  2885. XPopup.dismissTop()
  2886. }
  2887. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2888. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2889. popupPosition = PopupPosition.TOP
  2890. }
  2891. if (index <= 3) {
  2892. popupPosition = PopupPosition.BOTTOM
  2893. }
  2894. let pup: XPopup
  2895. if (this.isDarkMode) {
  2896. pup = XPopup.Builder()
  2897. .setPopupPosition(popupPosition)
  2898. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  2899. .setBackgroundColor(Color.Black)
  2900. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2901. .show()
  2902. } else {
  2903. pup = XPopup.Builder()
  2904. .setPopupPosition(popupPosition)
  2905. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  2906. .setBackgroundColor(Color.White)
  2907. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2908. .show()
  2909. }
  2910. }
  2911. //复制 到另个文件夹的对话框
  2912. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2913. Logger.info('onecoldv showCopyDialog')
  2914. let mList: Array<string> = []
  2915. let rPath = this.rootPath
  2916. if (isCurrent) {
  2917. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2918. rPath = this.currentPath
  2919. } else {
  2920. mList = Utility.getNameList(this.dirList);
  2921. rPath = this.rootPath
  2922. }
  2923. let dataBean = new BubbleBean()
  2924. dataBean.data = mList
  2925. dataBean.isCopy = true
  2926. dataBean.color = this.themeColor
  2927. dataBean.onItemClick = (i) => {
  2928. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2929. Logger.info('newPath = ' + newPath)
  2930. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2931. ToastUtil.showToast('复制成功')
  2932. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2933. this.getSortedFiles(this.currentPath)
  2934. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2935. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2936. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2937. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2938. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2939. this.table.insert(newItem, (id: number) => {
  2940. //加入数据库
  2941. });
  2942. }
  2943. }).catch((error: BusinessError) => {
  2944. console.error(error.message);
  2945. });
  2946. XPopup.dismissTop()
  2947. }
  2948. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2949. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2950. popupPosition = PopupPosition.TOP
  2951. }
  2952. if (index <= 3) {
  2953. popupPosition = PopupPosition.BOTTOM
  2954. }
  2955. let pup: XPopup
  2956. if (this.isDarkMode) {
  2957. pup = XPopup.Builder()
  2958. .setPopupPosition(popupPosition)
  2959. .atView(id)
  2960. .setMaxHeight('60%')
  2961. .setBackgroundColor(Color.Black)
  2962. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2963. .show();
  2964. } else {
  2965. pup = XPopup.Builder()
  2966. .setPopupPosition(popupPosition)
  2967. .atView(id)
  2968. .setMaxHeight('60%')
  2969. .setBackgroundColor(Color.White)
  2970. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2971. .show();
  2972. }
  2973. }
  2974. //重命名索引index的视频
  2975. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  2976. FileUtil.rename(oldPath, newPath).then(async () => {
  2977. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2978. if (info.type === CommonConstants.TYPE_IS_DIR) {
  2979. //如果是文件夹先删除源数据,再添加新数据
  2980. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  2981. if (success) {
  2982. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  2983. } else {
  2984. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  2985. }
  2986. });
  2987. this.scanDirectory(newPath)
  2988. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  2989. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  2990. if (success) {
  2991. console.log(" onecold 重命名成功,数据库已同步");
  2992. } else {
  2993. console.error(" onecold 重命名数据库失败原因: " + error);
  2994. }
  2995. });
  2996. }
  2997. let mediaItem: VideoItem =
  2998. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2999. this.videoLocalList[index] = mediaItem;
  3000. }
  3001. this.cache.delete(this.currentPath)
  3002. this.getSortedFiles(this.currentPath, true)
  3003. }).catch((error: BusinessError) => {
  3004. console.error(error.message);
  3005. });
  3006. }
  3007. build() {
  3008. Stack() {
  3009. this.ContentBuild()
  3010. Stack() {
  3011. Column()
  3012. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  3013. height: '95%',
  3014. dragBar: true,
  3015. showClose: true,
  3016. blurStyle: BlurStyle.Thin,
  3017. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3018. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  3019. title: {
  3020. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  3021. + `(${this.songList.length}首)`
  3022. }
  3023. })
  3024. }
  3025. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  3026. modalTransition: this.isCoverRectangle?ModalTransition.DEFAULT:ModalTransition.NONE,
  3027. transition: this.isCoverRectangle?null:AnimationHelper.transitionInDown(500),
  3028. onWillDisappear: () => {
  3029. this.setShowPlayFalse()
  3030. },
  3031. })
  3032. }
  3033. .alignContent(Alignment.Bottom)
  3034. .width('100%')
  3035. .height('100%')
  3036. }
  3037. @Builder
  3038. ContentBuild() {
  3039. Scroll() {
  3040. Column() {
  3041. Stack() {
  3042. //libraryname加上去后onKeyEvent监听不了,因为目前的解决方案是上面的XComponent,去掉libraryname
  3043. XComponent({ id: 'for_onKeyEvent',type: XComponentType.SURFACE,
  3044. controller: this.xcomponentController })
  3045. .onLoad(async (event?: object) => {
  3046. })
  3047. .focusable(true)
  3048. .height(0)
  3049. .focusOnTouch(true)
  3050. .defaultFocus(true) // 自动获取键盘焦点
  3051. .onKeyEvent((event?: KeyEvent) => {
  3052. console.info('onecold点击 onKeyEvent')
  3053. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  3054. if (!event || event.type !== KeyType.Down) {
  3055. return;
  3056. }
  3057. console.info('onecold点击 onKeyEvent event.keyCode: ' + event.keyCode)
  3058. //空格键 Space key controls pause/play
  3059. if (event.keyCode === KeyCode.KEYCODE_SPACE|| event.keyCode === KeyCode.KEYCODE_MEDIA_PLAY_PAUSE) {
  3060. this.playOrPause()
  3061. }
  3062. if (event.keyCode === KeyCode.KEYCODE_DPAD_UP) {
  3063. this.playPrevious()
  3064. }
  3065. if (event.keyCode === KeyCode.KEYCODE_DPAD_DOWN) {
  3066. this.playNext()
  3067. }
  3068. // Right-click to fast forward
  3069. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  3070. this.fastForward()
  3071. }
  3072. // Left-click to rewind
  3073. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  3074. this.backForward()
  3075. }
  3076. })
  3077. Column() {
  3078. XComponent({
  3079. id: 'xcomponentId',
  3080. type: 'surface',
  3081. libraryname: 'ijkplayer_napi',
  3082. controller: this.xcomponentController
  3083. })
  3084. .onLoad((event?: object) => {
  3085. if (!!event) {
  3086. this.initDelayPlay(event);
  3087. }
  3088. })
  3089. .onDestroy(() => {
  3090. })
  3091. .width('100%')// .width(this.videoWidth)
  3092. .aspectRatio(this.videoAspectRatio)
  3093. }
  3094. .aspectRatio(this.videoAspectRatio)
  3095. .justifyContent(FlexAlign.Center)
  3096. .backgroundColor(Color.Transparent)
  3097. .visibility(Visibility.Hidden)
  3098. .height(CommonConstants.FULL_PERCENT)
  3099. .width(CommonConstants.FULL_PERCENT)
  3100. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  3101. height:this.isLandscape?'80%': '43%',
  3102. dragBar: true,
  3103. showClose: true,
  3104. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3105. blurStyle:BlurStyle.Thin,
  3106. backgroundColor:Color.Transparent,
  3107. title: { title: 'AB循环' }
  3108. })
  3109. Stack() {
  3110. Column() {
  3111. if(this.twoFingerType==4){
  3112. this.getWaterView()
  3113. }else{
  3114. if(this.isGridMusic){
  3115. this.getGridView()
  3116. }else {
  3117. this.getList()
  3118. }
  3119. }
  3120. if (this.modeType ==0||this.modeType==4) {
  3121. Column() {
  3122. emptyView(this.themeColor)
  3123. }
  3124. .onClick(()=>{
  3125. this.asyncCurrentPathOnlyFile()
  3126. })
  3127. .position({ top: 200 })
  3128. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  3129. .animation({ duration: 500 }),
  3130. TransitionEffect.scale({ x: 0, y: 0 })))
  3131. .justifyContent(FlexAlign.Center)
  3132. .opacity(this.isZero ? 1 : 0)
  3133. .visibility(this.isZero && !this.isFavMusic && !this.isHistory
  3134. ? Visibility.Visible : Visibility.None)
  3135. .animation({
  3136. duration: 500,
  3137. curve: Curve.Friction // 可选动画曲线
  3138. })
  3139. .width('100%')
  3140. }
  3141. }
  3142. .layoutWeight(1)
  3143. .height('100%')
  3144. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  3145. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3146. .onDrop((event?: DragEvent) => {
  3147. try {
  3148. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3149. if (dragData !== undefined) {
  3150. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3151. if (records.length > 0) {
  3152. for (let i = 0; i < records.length; i++) {
  3153. let types = records[i].getTypes();
  3154. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3155. const fileUriUds =
  3156. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3157. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3158. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3159. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3160. this.targetFile = fileUriUds.oriUri;
  3161. this.saveVideoDatas([this.targetFile])
  3162. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3163. }
  3164. }
  3165. }
  3166. } else {
  3167. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3168. }
  3169. } else {
  3170. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3171. }
  3172. } catch (error) {
  3173. const err = error as BusinessError;
  3174. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3175. }
  3176. })
  3177. // 右侧居中的字母表索引
  3178. if(this.showZMIndex){
  3179. this.indexBuilder()
  3180. }
  3181. this.topTitleBar()
  3182. }
  3183. .alignContent(Alignment.Top)
  3184. .layoutWeight(1)
  3185. .height('100%')
  3186. Row() {
  3187. Button(this.isAllSelected ? '反选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  3188. .width(45)
  3189. .height(45)
  3190. .fontSize(10)
  3191. .margin({ top: 10, bottom: 10, right: 6 })
  3192. .backgroundColor(this.themeColor)
  3193. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3194. .onClick(() => {
  3195. if (this.isAllSelected) {
  3196. // 全不选
  3197. this.selectedFiles = [];
  3198. } else {
  3199. // 全选
  3200. this.selectedFiles = [...this.getCurFileList()];
  3201. }
  3202. this.isAllSelected = !this.isAllSelected;
  3203. })
  3204. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  3205. .width(72)
  3206. .height(45)
  3207. .fontSize(10)
  3208. .margin({ top: 10, bottom: 10, right: 6 })
  3209. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3210. .backgroundColor(this.themeColor)
  3211. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  3212. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3213. })
  3214. .onClick(() => {
  3215. // if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  3216. this.isOneKeyTags = !this.isOneKeyTags
  3217. // }else{
  3218. // ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限批量内嵌标签,导入的时候请勾选复制一份。')
  3219. // }
  3220. })
  3221. Button('合并', { type: ButtonType.Circle, stateEffect: true })
  3222. .width(45)
  3223. .height(45)
  3224. .fontSize(10)
  3225. .margin({ top: 10, bottom: 10, right: 6 })
  3226. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3227. .backgroundColor(this.themeColor)
  3228. .bindContentCover($$this.isMergeAudio, this.MergeAudioBuilder(), {
  3229. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3230. })
  3231. .onClick(() => {
  3232. if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  3233. this.isMergeAudio = !this.isMergeAudio
  3234. }else{
  3235. ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限合并')
  3236. }
  3237. })
  3238. Button('+歌单', { type: ButtonType.Circle, stateEffect: true })
  3239. .width(45)
  3240. .height(45)
  3241. .fontSize(10)
  3242. .margin({ top: 10, bottom: 10, right: 6 })
  3243. .backgroundColor(this.themeColor)
  3244. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3245. .onClick(async () => {
  3246. this.longItemFilePath = ''
  3247. await this.openAddToPlaylistDialog(this.selectedFiles)
  3248. })
  3249. // Button('乱码', { type: ButtonType.Circle, stateEffect: true })
  3250. // .width(45)
  3251. // .height(45)
  3252. // .fontSize(10)
  3253. // .margin({ top: 10, bottom: 10, right: 6 })
  3254. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3255. // .backgroundColor(this.themeColor)
  3256. // .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  3257. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3258. // })
  3259. // .onClick(() => {
  3260. // this.isFixMessy = !this.isFixMessy
  3261. // })
  3262. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  3263. // .width('35%')
  3264. // .height(60)
  3265. // .id('music_cut')
  3266. // .margin({ top: 10, bottom: 10, right: 6 })
  3267. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3268. // .backgroundColor(this.themeColor)
  3269. // .onClick(() => {
  3270. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  3271. // })
  3272. //
  3273. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  3274. // .width('35%')
  3275. // .height(60)
  3276. // .id('music_cut_current')
  3277. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  3278. // .margin({ top: 10, bottom: 10, right: 6 })
  3279. // .backgroundColor(this.themeColor)
  3280. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3281. // .onClick(() => {
  3282. //
  3283. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  3284. // })
  3285. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  3286. // .width('35%')
  3287. // .height(60)
  3288. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  3289. // .margin({ top: 10, bottom: 10, right: 6 })
  3290. // .backgroundColor(this.themeColor)
  3291. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3292. // .onClick(() => {
  3293. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  3294. // })
  3295. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  3296. .width(45)
  3297. .height(45)
  3298. .fontSize(10)
  3299. .margin({ top: 10, bottom: 10, right: 6 })
  3300. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  3301. .backgroundColor(this.themeColor)
  3302. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3303. .onClick(() => {
  3304. this.showWarnIsDelete()
  3305. })
  3306. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  3307. .width(45)
  3308. .height(45)
  3309. .fontSize(10)
  3310. .margin({ top: 10, bottom: 10, right: 6 })
  3311. .backgroundColor(this.themeColor)
  3312. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3313. .onClick(() => {
  3314. this.selectedFiles = [];
  3315. this.isAllSelected = false
  3316. this.isMultiSelect = false
  3317. })
  3318. }
  3319. .width('100%')
  3320. .justifyContent(FlexAlign.Center)
  3321. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  3322. .opacity(this.isMultiSelect ? 1 : 0)
  3323. .animation({
  3324. duration: 666,
  3325. curve: 'ease-in-out' // 可选动画曲线
  3326. })
  3327. .position({ bottom: 20 }) // 将 Row 固定在底部
  3328. }
  3329. .width('100%')
  3330. .height('100%')
  3331. .alignContent(Alignment.Top)
  3332. }
  3333. .width('100%')
  3334. .height('100%')
  3335. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  3336. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  3337. .backgroundImagePosition(Alignment.Center)
  3338. .backdropBlur(this.blurValue)
  3339. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  3340. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  3341. }
  3342. }
  3343. //字母表索引
  3344. @Builder
  3345. indexBuilder(){
  3346. if(this.enableShowAlphabet){
  3347. Column({space: 5}){
  3348. if(this.isShowAlphaBet&&!(this.modeType==2&&!this.isCanBack)
  3349. &&!(this.modeType==3&&!this.isCanBack)){
  3350. AlphabetIndexer({arrayValue: this.alphaBet,selected: this.selectAlphaBetIndex})
  3351. .attributeModifier(this.alphaBetStyle)
  3352. .usingPopup(this.isTouchingAlphaBet)
  3353. .onAreaChange((old_value,new_value)=>{
  3354. this.alphabetHeight = new_value.height as number
  3355. })
  3356. .popupPosition({
  3357. x: 40,
  3358. y: this.alphabetHeight / 2
  3359. })
  3360. .onSelect((index: number) => {
  3361. this.onSelectIndexItem(this.alphaBet[index])
  3362. })
  3363. .onTouch((event: TouchEvent) =>{
  3364. this.isShowAlphaBet = true
  3365. if(event.type === TouchType.Up || event.type === TouchType.Cancel){
  3366. this.isTouchingAlphaBet = false
  3367. }else{
  3368. this.isTouchingAlphaBet = true
  3369. }
  3370. })
  3371. .transition(
  3372. TransitionEffect.translate({x: 10})
  3373. .combine(TransitionEffect.opacity(0.1))
  3374. .animation({
  3375. duration: 150,
  3376. curve: Curve.EaseInOut,
  3377. })
  3378. )
  3379. }else{
  3380. Blank()
  3381. .layoutWeight(1)
  3382. }
  3383. // ListLocateButton()
  3384. // .onClick(() =>{
  3385. // this.locateSong()
  3386. // })
  3387. // .clickEffect({level:ClickEffectLevel.LIGHT,scale: 0.5})
  3388. // .margin({
  3389. // bottom: 10
  3390. // })
  3391. }
  3392. .padding({
  3393. bottom: 0
  3394. })
  3395. .position({x:'92%'})
  3396. .height('100%')
  3397. .justifyContent(FlexAlign.Center)
  3398. }
  3399. }
  3400. onSelectIndexItem(letter: string) {
  3401. let songs = this.videoLocalList
  3402. let targetIndex = -1;
  3403. for (let i = 0; i < songs.length; i++) {
  3404. let song = songs[i]
  3405. let text = this.isShowFileName?song.fileName:
  3406. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  3407. if(this.sortType === 0||this.sortType==1){
  3408. text = song.artist
  3409. }else if(this.sortType === 2||this.sortType==3){
  3410. text = song.album
  3411. }
  3412. if(text){
  3413. let firstPinyin = getFirstLetter(text)
  3414. if (firstPinyin&&firstPinyin === letter) {
  3415. targetIndex = i;
  3416. break;
  3417. }
  3418. }
  3419. }
  3420. if (targetIndex !== -1) {
  3421. this.listScroller.scrollToIndex(targetIndex);
  3422. }
  3423. }
  3424. // 找到对应字母表的索引
  3425. findAlphaBetIndex(song: VideoItem):number{
  3426. let text = this.isShowFileName?song.fileName:
  3427. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  3428. if(this.sortType === 0||this.sortType==1){
  3429. text = song.artist
  3430. }else if(this.sortType === 2||this.sortType==3){
  3431. text = song.album
  3432. }
  3433. if(text){
  3434. let firstLetter = getFirstLetter(text)
  3435. for(let i=0;i<this.alphaBet.length;i++){
  3436. if(this.alphaBet[i] === firstLetter){
  3437. return i
  3438. }
  3439. }
  3440. }
  3441. return 0
  3442. }
  3443. async setAlphaBet(){
  3444. if(!this.showZMIndex){
  3445. return
  3446. }
  3447. return new Promise<void>((resolve,reject) => {
  3448. try {
  3449. let songs = this.videoLocalList
  3450. if(songs.length > 40000){
  3451. this.alphaBet = []
  3452. resolve()
  3453. return
  3454. }
  3455. let alphabetSet = new Set<string>();
  3456. for (let song of songs) {
  3457. let text = this.isShowFileName?song.fileName:
  3458. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  3459. if(this.sortType === 0||this.sortType==1){
  3460. text = song.artist
  3461. }else if(this.sortType === 2||this.sortType==3){
  3462. text = song.album
  3463. }
  3464. if(text){
  3465. let firstPinyin = getFirstLetter(text)
  3466. if(!alphabetSet.has(firstPinyin)){
  3467. alphabetSet.add(firstPinyin)
  3468. }
  3469. }
  3470. // const pyStr = song.pyStr
  3471. // if(pyStr){
  3472. // if(!alphabetSet.has(pyStr)){
  3473. // alphabetSet.add(pyStr)
  3474. // }
  3475. // }
  3476. }
  3477. this.alphaBet = Array.from(alphabetSet).sort((a,b)=>{
  3478. if(this.sortType ===4||this.sortType==0||this.sortType==2||this.sortType==6){
  3479. return a.localeCompare(b)
  3480. }else{
  3481. return b.localeCompare(a)
  3482. }
  3483. })
  3484. if(this.videoLocalList.length > 0){
  3485. this.listScroller.scrollToIndex(0)
  3486. this.selectAlphaBetIndex = 0
  3487. }
  3488. resolve()
  3489. }catch (e) {
  3490. console.error('testTag','排序字母表出错',JSON.stringify(e))
  3491. resolve()
  3492. }
  3493. })
  3494. }
  3495. @Builder
  3496. topTitleBar(){
  3497. Column() {
  3498. Row({ space: 15 }) {
  3499. if (!this.isSearchMode ) {
  3500. //左侧滑动按钮
  3501. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3502. SymbolGlyph(this.rightTopImage)
  3503. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3504. }
  3505. .attributeModifier(new ButtonFancyModifier(40, 40))
  3506. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3507. .animation({ duration: 300, curve: Curve.Ease })
  3508. .onClick(() => {
  3509. this.doSwipBack()
  3510. })
  3511. .attributeModifier(new ShadowModifier())
  3512. .zIndex(0)
  3513. }else{
  3514. //左侧搜索返回按钮
  3515. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3516. SymbolGlyph($r('sys.symbol.chevron_left'))
  3517. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3518. }
  3519. .attributeModifier(new ButtonFancyModifier(40, 40))
  3520. .margin({bottom:5})
  3521. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3522. .animation({ duration: 300, curve: Curve.Ease })
  3523. .onClick(() => {
  3524. this.isSearchMode = false
  3525. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  3526. this.searchText = ''
  3527. this.getSortedFiles(this.currentPath)
  3528. return
  3529. }
  3530. this.onSearchInput('')
  3531. })
  3532. .attributeModifier(new ShadowModifier())
  3533. .zIndex(0)
  3534. }
  3535. if (!this.isSearchMode) {
  3536. Text(this.modeType==1?`${this.titleName}(${this.mediaKuCount}首)`:this.titleName)
  3537. .margin({left:3,right:10})
  3538. .fontColor($r('app.color.text_color'))
  3539. .fontSize(this.twoFingerType==3?17:16)
  3540. .maxLines(1)
  3541. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3542. .layoutWeight(1)
  3543. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3544. }
  3545. //搜索框
  3546. Search({ controller: this.searchController,value: this.searchText, placeholder: '搜索标题、艺术家...' })
  3547. .searchButton('搜索',{fontColor:this.themeColor})
  3548. .searchIcon({
  3549. src: $r('sys.media.ohos_ic_public_search_filled')
  3550. })
  3551. .cancelButton({
  3552. style: CancelButtonStyle.CONSTANT,
  3553. icon: {
  3554. src: $r('sys.media.ohos_ic_public_cancel_filled')
  3555. }
  3556. })
  3557. .layoutWeight(1)
  3558. .height(40)
  3559. .maxLength(20)
  3560. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  3561. .placeholderColor(Color.Grey)
  3562. .placeholderFont({ size: 14, weight: 400 })
  3563. .textFont({ size: 14, weight: 400 })
  3564. .onSubmit((value: string) => {
  3565. console.log('onecold onSubmit ='+value)
  3566. this.searchController.stopEditing()
  3567. this.onSearchInput(this.searchText);
  3568. })
  3569. .onChange((value: string) => {
  3570. console.log('onecold onChange ='+value)
  3571. this.onSearchInput(value);
  3572. })
  3573. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  3574. .animation({ duration: 300, curve: Curve.Ease })
  3575. //搜索按钮
  3576. if (!this.isSearchMode) {
  3577. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3578. SymbolGlyph($r('sys.symbol.magnifyingglass'))
  3579. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3580. }
  3581. .attributeModifier(new ButtonFancyModifier(40, 40))
  3582. .animation({ duration: 300, curve: Curve.Ease })
  3583. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3584. .attributeModifier(new ShadowModifier())
  3585. .zIndex(0)
  3586. .onClick(()=>{
  3587. this.isSearchMode = true
  3588. })
  3589. //排序按钮
  3590. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3591. SymbolGlyph($r('sys.symbol.list_number'))
  3592. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3593. }
  3594. .attributeModifier(new ButtonFancyModifier(40, 40))
  3595. .animation({ duration: 300, curve: Curve.Ease })
  3596. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3597. .bindMenu((this.modeType==2&&!this.isCanBack)||(this.modeType==3&&!this.isCanBack)
  3598. ?this.SortMenuForArtistAblumBuilder:this.SortMenuBuilder)
  3599. .attributeModifier(new ShadowModifier())
  3600. .zIndex(0)
  3601. //添加按钮
  3602. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3603. SymbolGlyph($r('sys.symbol.plus'))
  3604. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3605. }
  3606. .attributeModifier(new ButtonFancyModifier(40, 40))
  3607. .animation({ duration: 300, curve: Curve.Ease })
  3608. .visibility(this.modeType==0||this.modeType==1?Visibility.Visible:Visibility.None)
  3609. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3610. .bindSheet($$this.showAddSheet, this.addSheet(), {
  3611. height: SheetSize.FIT_CONTENT,
  3612. dragBar: true,
  3613. showClose: true,
  3614. preferType: SheetType.CENTER ,
  3615. title: {
  3616. title: '导入音乐'
  3617. }
  3618. })
  3619. .onClick(() => {
  3620. this.showAddSheet = !this.showAddSheet;
  3621. })
  3622. .attributeModifier(new ShadowModifier())
  3623. .zIndex(0)
  3624. }
  3625. }
  3626. }
  3627. .padding({ top: this.topSafeHeight+10, left: 10, right: 10 })
  3628. .width('100%')
  3629. .visibility(this.isShowTitleBar?Visibility.Visible:
  3630. this.autoHideTitle?Visibility.None:Visibility.Visible)
  3631. .animation({
  3632. duration: 500,
  3633. curve: Curve.Friction // 可选动画曲线
  3634. })
  3635. }
  3636. @Builder
  3637. addSheet() {
  3638. Scroll() {
  3639. Column() {
  3640. Column() {
  3641. Row() {
  3642. Text('导入音乐复制到DownLoad目录')
  3643. .margin({ left: 18 })
  3644. .fontSize(14)
  3645. .fontColor($r('app.color.text_color'))
  3646. .fontWeight(480)
  3647. .layoutWeight(1)
  3648. Toggle({ type: ToggleType.Switch, isOn: this.isCopyFileToDownLoad })
  3649. .selectedColor(this.themeColor)
  3650. .switchPointColor(Color.White)
  3651. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  3652. .margin({ right: 18 })
  3653. .onChange((checked: boolean) => {
  3654. this.isCopyFileToDownLoad = checked;
  3655. PreferencesUtil.put(SettingPage.IS_COPYFILE_TO_DOWNLOAD, this.isCopyFileToDownLoad)
  3656. })
  3657. .width(50)
  3658. .height(30);
  3659. }
  3660. .height(88)
  3661. }
  3662. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3663. .backgroundColor($r('app.color.start_window_background'))
  3664. .borderRadius(15)
  3665. .margin({
  3666. left: 30,
  3667. right: 30,
  3668. top: 10,
  3669. bottom: 10
  3670. })
  3671. .padding(0)
  3672. .border({
  3673. color: Color.White,
  3674. width: 1.8
  3675. })
  3676. Menu() {
  3677. MenuItem({
  3678. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder_badge_plus')),
  3679. content: "新建文件夹"
  3680. })
  3681. .backgroundColor($r('app.color.silvery'))
  3682. .border({
  3683. width: { bottom: 1 },
  3684. color: '#12ec5c87'
  3685. })
  3686. .margin(10)
  3687. .padding({left:15,right:15})
  3688. .onClick(async () => {
  3689. this.showMkDialog()
  3690. this.showAddSheet = !this.showAddSheet
  3691. })
  3692. MenuItem({
  3693. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder')),
  3694. content: $r('app.string.import_from_files')
  3695. })
  3696. .padding({left:15,right:15})
  3697. .backgroundColor($r('app.color.silvery'))
  3698. .border({
  3699. width: { bottom: 1 },
  3700. color: '#12ec5c87'
  3701. })
  3702. .margin(10)
  3703. .onClick(async () => {
  3704. this.callFilePickerSelectFile()
  3705. this.showAddSheet = !this.showAddSheet
  3706. })
  3707. MenuItem({
  3708. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square')),
  3709. content: '全选导入'
  3710. // content: '从下载文件夹导入(路径:Download/' +
  3711. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  3712. })
  3713. .padding({left:15,right:15})
  3714. .backgroundColor($r('app.color.silvery'))
  3715. .border({
  3716. width: { bottom: 1 },
  3717. color: '#12ec5c87'
  3718. })
  3719. .margin(10)
  3720. .onClick(async () => {
  3721. this.goSelectMusic()
  3722. this.showAddSheet = !this.showAddSheet
  3723. })
  3724. MenuItem({
  3725. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.save')),
  3726. content: '自动导入教程'
  3727. // content: '从下载文件夹导入(路径:Download/' +
  3728. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  3729. })
  3730. .padding({left:15,right:15})
  3731. .backgroundColor($r('app.color.silvery'))
  3732. .border({
  3733. width: { bottom: 1 },
  3734. color: '#12ec5c87'
  3735. })
  3736. .margin(10)
  3737. .onClick(async () => {
  3738. this.showTips()
  3739. this.showAddSheet = !this.showAddSheet
  3740. })
  3741. }.attributeModifier(new MenuModifier())
  3742. .margin({bottom:30})
  3743. }
  3744. .layoutWeight(1)
  3745. }
  3746. }
  3747. @Builder
  3748. TagsContentCoverBuilder() {
  3749. Scroll() {
  3750. Column() {
  3751. TagsContentCover(
  3752. {
  3753. selectedFiles:this.selectedFiles,
  3754. isOneKeyTags:this.isOneKeyTags,
  3755. onSeePath:(path:string)=>{
  3756. this.modeType = 0
  3757. this.deleteCache(path)
  3758. this.getSortedFiles(path)
  3759. },
  3760. onTagsResult:(result: boolean,deleteCache_path?:string)=>{
  3761. this.isMultiSelect = false
  3762. if(result){//如果嵌入成功,更新数据
  3763. this.listRefreshKey++
  3764. setTimeout(()=>{
  3765. this.doUpdateData()
  3766. },500)
  3767. }
  3768. console.info('onecold onTagsResult deleteCache_path =' +deleteCache_path)
  3769. if(deleteCache_path){
  3770. this.deleteCache(deleteCache_path)
  3771. }
  3772. }
  3773. }
  3774. )
  3775. }
  3776. }
  3777. .width('100%')
  3778. .height('100%')
  3779. }
  3780. @Builder
  3781. FixMessyViewBuilder() {
  3782. Scroll() {
  3783. Column() {
  3784. FixMessyView(
  3785. {
  3786. selectedFiles:this.selectedFiles,
  3787. isFixMessy:this.isFixMessy,
  3788. onFixResult:(result: boolean)=>{
  3789. this.isMultiSelect = false
  3790. if(result){//如果嵌入成功,更新数据
  3791. this.deleteCache(this.currentPath)
  3792. this.doUpdateData()
  3793. }
  3794. }
  3795. }
  3796. )
  3797. }
  3798. }
  3799. .width('100%')
  3800. .height('100%')
  3801. }
  3802. //剪辑音频
  3803. @Builder
  3804. EditAudioBuilder(item:VideoItem) {
  3805. Scroll() {
  3806. Column() {
  3807. EditAudio(
  3808. {
  3809. mVideoItem:item,
  3810. currentPath:this.currentPath,
  3811. videoUrl:this.videoUrl,
  3812. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3813. currentTime:this.currentTime,
  3814. progressValue:this.progressValue,
  3815. onBack:()=>{
  3816. this.isEditAudio = !this.isEditAudio
  3817. },
  3818. onSeeOutputPath:(outPutPath:string)=>{
  3819. this.isEditAudio = !this.isEditAudio
  3820. this.longItemFilePath = ''
  3821. this.modeType = 0
  3822. this.isShowFileName = true
  3823. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3824. },
  3825. onPlayOrPause:()=>{
  3826. if(this.videoUrl==item.filePath){
  3827. this.playOrPause()
  3828. }else{//如果不是当前播放的,则播放该文件
  3829. this.videoUrl==item.filePath
  3830. this.doPlay(item,0,false,true)
  3831. }
  3832. },
  3833. onSliderChange:(value:number)=>{
  3834. if(this.videoUrl!=item.filePath){
  3835. this.videoUrl==item.filePath
  3836. return
  3837. }
  3838. this.isSeekTo = true;
  3839. this.mDestroyPage = false;
  3840. this.showLoadIng();
  3841. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  3842. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3843. this.seekTo(seekValue + "");
  3844. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  3845. this.isSeekTo = false;
  3846. },
  3847. onResult:(result: boolean,outPath:string)=>{
  3848. if(result){//如果剪辑成功,更新数据
  3849. this.doUpdateData()
  3850. }else{
  3851. ToastUtil.showToast('剪辑失败')
  3852. }
  3853. }
  3854. }
  3855. )
  3856. }
  3857. }
  3858. .width('100%')
  3859. .height('100%')
  3860. }
  3861. //提取伴奏
  3862. @Builder
  3863. ConverterBuilder(item:VideoItem) {
  3864. Scroll() {
  3865. Column() {
  3866. AudioFormatConverter(
  3867. {
  3868. mVideoItem:item,
  3869. videoUrl:this.videoUrl,
  3870. currentPath:this.currentPath,
  3871. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3872. currentTime:this.currentTime,
  3873. progressValue:this.progressValue,
  3874. onBack:()=>{
  3875. this.isConverter = !this.isConverter
  3876. this.longItemFilePath = ''
  3877. },
  3878. onPlayOrPause:()=>{
  3879. if(this.videoUrl==item.filePath){
  3880. this.playOrPause()
  3881. }else{//如果不是当前播放的,则播放该文件
  3882. this.videoUrl==item.filePath
  3883. this.doPlay(item,0,false,true)
  3884. }
  3885. },
  3886. onSeeOutputPath:(outPutPath:string)=>{
  3887. this.isConverter = !this.isConverter
  3888. this.longItemFilePath = ''
  3889. this.modeType = 0
  3890. this.isShowFileName = true
  3891. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3892. },
  3893. onSliderChange:(value:number)=>{
  3894. if(this.videoUrl!=item.filePath){
  3895. this.videoUrl==item.filePath
  3896. return
  3897. }
  3898. this.isSeekTo = true;
  3899. this.mDestroyPage = false;
  3900. this.showLoadIng();
  3901. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3902. this.seekTo(seekValue + "");
  3903. this.isSeekTo = false;
  3904. },
  3905. onResult:(result: boolean,outPath:string)=>{
  3906. if(result){//如果成功,更新数据
  3907. this.doUpdateData()
  3908. }else{
  3909. ToastUtil.showToast('格式转化失败')
  3910. }
  3911. }
  3912. }
  3913. )
  3914. }
  3915. }
  3916. .width('100%')
  3917. .height('100%')
  3918. }
  3919. //提取伴奏
  3920. @Builder
  3921. ExtractAccBuilder(item:VideoItem) {
  3922. Scroll() {
  3923. Column() {
  3924. ExtractAccompaniment(
  3925. {
  3926. mVideoItem:item,
  3927. currentPath:this.currentPath,
  3928. videoUrl:this.videoUrl,
  3929. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3930. currentTime:this.currentTime,
  3931. progressValue:this.progressValue,
  3932. onBack:()=>{
  3933. this.isExtractAcc = !this.isExtractAcc
  3934. this.longItemFilePath = ''
  3935. },
  3936. onPlayOrPause:()=>{
  3937. if(this.videoUrl==item.filePath){
  3938. this.playOrPause()
  3939. }else{//如果不是当前播放的,则播放该文件
  3940. this.videoUrl==item.filePath
  3941. this.doPlay(item,0,false,true)
  3942. }
  3943. },
  3944. onSeeOutputPath:(outPutPath:string)=>{
  3945. this.isExtractAcc = !this.isExtractAcc
  3946. this.longItemFilePath = ''
  3947. this.modeType = 0
  3948. this.isShowFileName = true
  3949. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3950. },
  3951. onSliderChange:(value:number)=>{
  3952. if(this.videoUrl!=item.filePath){
  3953. this.videoUrl==item.filePath
  3954. return
  3955. }
  3956. this.isSeekTo = true;
  3957. this.mDestroyPage = false;
  3958. this.showLoadIng();
  3959. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3960. this.seekTo(seekValue + "");
  3961. this.isSeekTo = false;
  3962. },
  3963. onResult:(result: boolean,outPath:string)=>{
  3964. if(result){//如果成功,更新数据
  3965. this.doUpdateData()
  3966. }else{
  3967. ToastUtil.showToast('提取伴奏失败')
  3968. }
  3969. }
  3970. }
  3971. )
  3972. }
  3973. }
  3974. .width('100%')
  3975. .height('100%')
  3976. }
  3977. //AI人声分离
  3978. @Builder
  3979. AiBuilder(item:VideoItem) {
  3980. Scroll() {
  3981. Column() {
  3982. AIVoiceSeparation(
  3983. {
  3984. mVideoItem:item,
  3985. videoUrl:this.videoUrl,
  3986. currentPath:this.currentPath,
  3987. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3988. currentTime:this.currentTime,
  3989. progressValue:this.progressValue,
  3990. onBack:()=>{
  3991. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  3992. this.longItemFilePath = ''
  3993. },
  3994. onPlayOrPause:()=>{
  3995. if(this.videoUrl==item.filePath||this.isPlaying){
  3996. this.playOrPause()
  3997. }else{//如果不是当前播放的,则播放该文件
  3998. this.videoUrl==item.filePath
  3999. this.doPlay(item,0,false,true)
  4000. }
  4001. },
  4002. onPlayPath:(path:string)=>{
  4003. this.videoUrl==path
  4004. const itemP = Utility.getItemByFilePath(this.videoLocalList,path)
  4005. if(itemP)
  4006. this.doPlay(itemP,0,false,true)
  4007. },
  4008. onSeeOutputPath:(outPutPath:string)=>{
  4009. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  4010. this.longItemFilePath = ''
  4011. this.modeType = 0
  4012. this.isShowFileName = true
  4013. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4014. },
  4015. onSliderChange:(value:number)=>{
  4016. if(this.videoUrl!=item.filePath){
  4017. this.videoUrl==item.filePath
  4018. return
  4019. }
  4020. this.isSeekTo = true;
  4021. this.mDestroyPage = false;
  4022. this.showLoadIng();
  4023. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  4024. this.seekTo(seekValue + "");
  4025. this.isSeekTo = false;
  4026. },
  4027. onResult:(result: boolean,outPath:string)=>{
  4028. if(result){//如果成功,更新数据
  4029. this.doUpdateData()
  4030. }else{
  4031. ToastUtil.showToast('Ai人声分离失败')
  4032. }
  4033. }
  4034. }
  4035. )
  4036. }
  4037. }
  4038. .width('100%')
  4039. .height('100%')
  4040. }
  4041. //变速变调
  4042. @Builder
  4043. ChangeToneBuilder(item:VideoItem) {
  4044. Scroll() {
  4045. Column() {
  4046. ChangeTone(
  4047. {
  4048. mVideoItem:item,
  4049. currentPath:this.currentPath,
  4050. videoUrl:this.videoUrl,
  4051. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4052. currentTime:this.currentTime,
  4053. progressValue:this.progressValue,
  4054. onBack:()=>{
  4055. this.isChangeTone = !this.isChangeTone
  4056. this.longItemFilePath = ''
  4057. },
  4058. onPlayOrPause:()=>{
  4059. if(this.videoUrl==item.filePath){
  4060. this.playOrPause()
  4061. }else{//如果不是当前播放的,则播放该文件
  4062. this.videoUrl==item.filePath
  4063. this.doPlay(item,0,false,true)
  4064. }
  4065. },
  4066. onSeeOutputPath:(outPutPath:string)=>{
  4067. this.isChangeTone = !this.isChangeTone
  4068. this.longItemFilePath = ''
  4069. this.modeType = 0
  4070. this.isShowFileName = true
  4071. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4072. },
  4073. onSliderChange:(value:number)=>{
  4074. if(this.videoUrl!=item.filePath){
  4075. this.videoUrl==item.filePath
  4076. return
  4077. }
  4078. this.isSeekTo = true;
  4079. this.mDestroyPage = false;
  4080. this.showLoadIng();
  4081. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  4082. this.seekTo(seekValue + "");
  4083. this.isSeekTo = false;
  4084. },
  4085. onResult:(result: boolean,outPath:string)=>{
  4086. if(result){//如果成功,更新数据
  4087. this.doUpdateData()
  4088. }else{
  4089. ToastUtil.showToast('变速变调失败')
  4090. }
  4091. }
  4092. }
  4093. )
  4094. }
  4095. }
  4096. .width('100%')
  4097. .height('100%')
  4098. }
  4099. //提取视频中的音频
  4100. @Builder
  4101. extractAudioFromVideoBuilder(item:VideoItem) {
  4102. Scroll() {
  4103. Column() {
  4104. ExtractAudioFromVideo(
  4105. {
  4106. mVideoItem:item,
  4107. currentPath:this.currentPath,
  4108. videoUrl:this.videoUrl,
  4109. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4110. currentTime:this.currentTime,
  4111. progressValue:this.progressValue,
  4112. onBack:()=>{
  4113. this.isExtractAudio = !this.isExtractAudio
  4114. this.longItemFilePath = ''
  4115. },
  4116. onPlayOrPause:()=>{
  4117. if(this.videoUrl==item.filePath){
  4118. this.playOrPause()
  4119. }else{//如果不是当前播放的,则播放该文件
  4120. this.videoUrl==item.filePath
  4121. this.doPlay(item,0,false,true)
  4122. }
  4123. },
  4124. onSeeOutputPath:(outPutPath:string)=>{
  4125. this.isExtractAudio = !this.isExtractAudio
  4126. this.longItemFilePath = ''
  4127. this.modeType = 0
  4128. this.isShowFileName = true
  4129. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4130. },
  4131. onSliderChange:(value:number)=>{
  4132. if(this.videoUrl!=item.filePath){
  4133. this.videoUrl==item.filePath
  4134. return
  4135. }
  4136. this.isSeekTo = true;
  4137. this.mDestroyPage = false;
  4138. this.showLoadIng();
  4139. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  4140. this.seekTo(seekValue + "");
  4141. this.isSeekTo = false;
  4142. },
  4143. onResult:(result: boolean,outPath:string)=>{
  4144. if(result){//如果成功,更新数据
  4145. this.doUpdateData()
  4146. }else{
  4147. ToastUtil.showToast('提取音频失败')
  4148. }
  4149. }
  4150. }
  4151. )
  4152. }
  4153. }
  4154. .width('100%')
  4155. .height('100%')
  4156. }
  4157. //合并音频
  4158. @Builder
  4159. MergeAudioBuilder() {
  4160. Scroll() {
  4161. Column() {
  4162. MergeAudio(
  4163. {
  4164. videoUrl:this.videoUrl,
  4165. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4166. currentPath:this.currentPath,
  4167. selectedFiles:this.selectedFiles,
  4168. currentTime:this.currentTime,
  4169. progressValue:this.progressValue,
  4170. onBack:()=>{
  4171. this.isMergeAudio = !this.isMergeAudio
  4172. this.longItemFilePath = ''
  4173. },
  4174. // onPlayPath:(path:string)=>{
  4175. // if(this.videoUrl==item.filePath){
  4176. // this.playOrPause()
  4177. // }else{//如果不是当前播放的,则播放该文件
  4178. // this.videoUrl==item.filePath
  4179. // this.doPlay(item,0,false,true)
  4180. // }
  4181. //
  4182. // },
  4183. onSeeOutputPath:(outPutPath:string)=>{
  4184. this.isMergeAudio = !this.isMergeAudio
  4185. this.longItemFilePath = ''
  4186. this.modeType = 0
  4187. this.isShowFileName = true
  4188. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4189. },
  4190. onResult:(result: boolean,outPath:string)=>{
  4191. if(result){//如果成功,更新数据
  4192. this.doUpdateData()
  4193. }else{
  4194. if(this.selectedFiles.length>=3){
  4195. ToastUtil.showToast('合并数量太多导致失败')
  4196. }else{
  4197. ToastUtil.showToast('合并失败')
  4198. }
  4199. }
  4200. }
  4201. }
  4202. )
  4203. }
  4204. }
  4205. .width('100%')
  4206. .height('100%')
  4207. }
  4208. asyncCurrentPathData() {
  4209. if (this.modeType == 0) {
  4210. workerInstance.postMessage({
  4211. code: 1,
  4212. data1: this.context,
  4213. data2: this.currentPath,
  4214. data3: this.lockPath,
  4215. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  4216. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  4217. });
  4218. }
  4219. }
  4220. // 处理文件选择的函数
  4221. handleFileSelection(item: VideoItem, checked: boolean) {
  4222. if (checked) {
  4223. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  4224. this.selectedFiles.push(item);
  4225. }
  4226. } else {
  4227. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  4228. if (index > -1) {
  4229. this.selectedFiles.splice(index, 1);
  4230. }
  4231. }
  4232. }
  4233. private deleteComponentId: number = 0
  4234. //多选删除文件
  4235. showWarnIsDelete(){
  4236. this.getUIContext().getPromptAction().openCustomDialog({
  4237. builder: () => {
  4238. this.deleteComptentBuilder()
  4239. },
  4240. isModal:true,
  4241. showInSubWindow:false,
  4242. maskColor: Color.Transparent,
  4243. dialogTransition: // 设置弹窗内容显示的过渡效果
  4244. TransitionEffect.translate({ x: 0, y: 290, z: 0 })
  4245. .animation({ duration: 600, curve: Curve.Smooth }),
  4246. maskTransition: // 设置蒙层显示的过渡效果
  4247. TransitionEffect.opacity(0)
  4248. .animation({ duration: 600, curve: Curve.Smooth })
  4249. }).then((dialogId: number) => {
  4250. this.deleteComponentId = dialogId
  4251. })
  4252. .catch((error: BusinessError) => {
  4253. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  4254. })
  4255. }
  4256. @Builder
  4257. deleteComptentBuilder(){
  4258. DeleteComptent({
  4259. selectedFiles:this.selectedFiles,
  4260. onCancel:()=>{
  4261. this.isMultiSelect = false
  4262. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  4263. },
  4264. onDeleteResult:(result: boolean)=>{
  4265. this.isMultiSelect = false
  4266. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  4267. if(result){//如果删除成功,更新数据
  4268. this.selectedFiles = [];
  4269. this.isAllSelected = false
  4270. this.cache.delete(this.currentPath);
  4271. this.getSortedFiles(this.currentPath, true);
  4272. }
  4273. }
  4274. })
  4275. }
  4276. //多选移动文件
  4277. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  4278. Logger.info('onecold showCutDialogForMultipleFiles')
  4279. let mList: Array<string> = []
  4280. let rPath = this.rootPath
  4281. if (isCurrent) {
  4282. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  4283. rPath = this.currentPath
  4284. } else {
  4285. mList = Utility.getNameList(this.dirList);
  4286. rPath = this.rootPath
  4287. }
  4288. let dataBean = new BubbleBean();
  4289. dataBean.data = mList;
  4290. dataBean.color = this.themeColor
  4291. dataBean.onItemClick = (i) => {
  4292. const newDirPath = rPath + '/' + mList[i];
  4293. // Logger.info('newDirPath = ' + newDirPath)
  4294. this.selectedFiles.forEach((item) => {
  4295. const newPath = newDirPath + '/' + item.fileName;
  4296. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  4297. ToastUtil.showToast('移动成功');
  4298. this.table.deleteData(item, () => {
  4299. this.cache.delete(this.currentPath); // 删除原路径缓存
  4300. this.cache.delete(newDirPath); // 删除目标路径缓存
  4301. this.getSortedFiles(this.currentPath, true);
  4302. });
  4303. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  4304. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  4305. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  4306. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  4307. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  4308. this.table.insert(newItem, (id: number) => {
  4309. //加入数据库
  4310. });
  4311. }
  4312. }).catch((error: Error) => {
  4313. console.error(error.message);
  4314. });
  4315. });
  4316. this.isMultiSelect = false
  4317. this.selectedFiles = [];
  4318. this.isAllSelected = false
  4319. XPopup.dismissTop();
  4320. };
  4321. let pup: XPopup
  4322. if (this.isDarkMode) {
  4323. pup = XPopup.Builder()
  4324. .setPopupPosition(PopupPosition.TOP)
  4325. .atView(viewId)
  4326. .setBackgroundColor(Color.Black)
  4327. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4328. .show();
  4329. } else {
  4330. pup = XPopup.Builder()
  4331. .setPopupPosition(PopupPosition.TOP)
  4332. .atView(viewId)
  4333. .setBackgroundColor(Color.White)
  4334. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4335. .show();
  4336. }
  4337. }
  4338. /**
  4339. * 加载所有歌单
  4340. */
  4341. async loadAllPlaylists() {
  4342. try {
  4343. this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
  4344. LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
  4345. } catch (error) {
  4346. LogUtil.error('heaunp Failed to load playlists: ' + error.message)
  4347. }
  4348. }
  4349. /**
  4350. * 显示添加到歌单对话框
  4351. */
  4352. async openAddToPlaylistDialog(items: VideoItem | VideoItem[]) {
  4353. const songs = Array.isArray(items) ? items : [items]
  4354. const musicItems = songs.filter(song => song.type !== CommonConstants.TYPE_IS_DIR)
  4355. if (musicItems.length === 0) {
  4356. ToastUtil.showToast('请选择要添加的歌曲')
  4357. return
  4358. }
  4359. // 加载最新的歌单列表
  4360. await this.loadAllPlaylists()
  4361. showAddToPlaylistDialog(
  4362. musicItems,
  4363. this.allPlaylists,
  4364. async (playlistId: string) => {
  4365. // 添加歌曲到歌单
  4366. const success = await this.playlistTable?.addSongsToPlaylist(playlistId,
  4367. musicItems.map(song => song.filePath))
  4368. if (success) {
  4369. const count = musicItems.length
  4370. ToastUtil.showToast(count > 1 ? `已添加 ${count} 首歌曲` : '已添加到歌单')
  4371. // 重新加载歌单列表
  4372. await this.loadAllPlaylists()
  4373. } else {
  4374. ToastUtil.showToast(musicItems.length > 1 ? '选中的歌曲已在该歌单中' : '歌曲已在该歌单中')
  4375. }
  4376. this.longItemFilePath = ''
  4377. if (this.isMultiSelect) {
  4378. this.isMultiSelect = false
  4379. this.isAllSelected = false
  4380. this.selectedFiles = []
  4381. }
  4382. },
  4383. () => {
  4384. LogUtil.info('取消添加到歌单')
  4385. },
  4386. () => {
  4387. // 创建新歌单
  4388. showCreatePlaylistDialog(
  4389. async (name: string, description: string, coverPath?: string) => {
  4390. const success = await this.playlistTable?.createPlaylist(name, description, coverPath)
  4391. if (success) {
  4392. ToastUtil.showToast('歌单创建成功')
  4393. // 重新加载歌单列表并打开添加对话框
  4394. await this.loadAllPlaylists()
  4395. await this.openAddToPlaylistDialog(musicItems)
  4396. } else {
  4397. ToastUtil.showToast('歌单创建失败')
  4398. }
  4399. },
  4400. () => {
  4401. // 取消创建歌单
  4402. }
  4403. )
  4404. }
  4405. )
  4406. }
  4407. doFav(item: VideoItem) {
  4408. LogUtil.info('onecold doFav isFav=' + item.isFav)
  4409. let isFav = 0
  4410. if (Utility.getIsFav(this.favList, item)) {
  4411. isFav = 0
  4412. } else {
  4413. isFav = 1
  4414. }
  4415. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  4416. if (result) {
  4417. if (isFav === 1) {
  4418. ToastUtil.showToast('收藏成功');
  4419. } else {
  4420. ToastUtil.showToast('取消收藏成功');
  4421. }
  4422. this.deleteCache(this.currentPath)
  4423. this.getFavList(false)
  4424. if (this.modeType === 0 && !this.isFavMusic) {
  4425. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  4426. this.getSortedFiles(this.currentPath)
  4427. }
  4428. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  4429. workerInstance.postMessage({ code: 3, data: this.context });
  4430. workerInstance.postMessage({ code: 4, data: this.context });
  4431. }
  4432. })
  4433. }
  4434. //多选复制文件
  4435. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  4436. console.log('onecold showCopyDialogForMultipleFiles');
  4437. let mList: Array<string> = []
  4438. let rPath = this.rootPath
  4439. if (isCurrent) {
  4440. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  4441. rPath = this.currentPath
  4442. } else {
  4443. mList = Utility.getNameList(this.dirList);
  4444. rPath = this.rootPath
  4445. }
  4446. let dataBean = new BubbleBean();
  4447. dataBean.data = mList;
  4448. dataBean.isCopy = true
  4449. dataBean.color = this.themeColor
  4450. dataBean.onItemClick = (i) => {
  4451. const newDirPath = rPath + '/' + mList[i];
  4452. // Logger.info('newDirPath = ' + newDirPath)
  4453. this.selectedFiles.forEach((item) => {
  4454. const newPath = newDirPath + '/' + item.fileName;
  4455. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  4456. ToastUtil.showToast('复制成功');
  4457. this.cache.delete(newDirPath); // 删除目标路径缓存
  4458. this.getSortedFiles(this.currentPath);
  4459. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  4460. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  4461. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  4462. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  4463. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  4464. this.table.insert(newItem, (id: number) => {
  4465. //加入数据库
  4466. });
  4467. }
  4468. }).catch((error: Error) => {
  4469. console.error(error.message);
  4470. });
  4471. });
  4472. this.isMultiSelect = false
  4473. this.selectedFiles = [];
  4474. this.isAllSelected = false
  4475. XPopup.dismissTop();
  4476. };
  4477. let pup: XPopup
  4478. if (this.isDarkMode) {
  4479. pup = XPopup.Builder()
  4480. .setPopupPosition(PopupPosition.TOP)
  4481. .atView(viewId)
  4482. .setBackgroundColor(Color.Black)
  4483. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4484. .show();
  4485. } else {
  4486. pup = XPopup.Builder()
  4487. .setPopupPosition(PopupPosition.TOP)
  4488. .atView(viewId)
  4489. .setBackgroundColor(Color.White)
  4490. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4491. .show();
  4492. }
  4493. }
  4494. @Builder
  4495. private DirItem(item: VideoItem, index?: number) {
  4496. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  4497. Row() {
  4498. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  4499. $r('app.media.music_group'))
  4500. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4501. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4502. .fillColor(this.themeColor)// .fontSize(33)
  4503. .alt($r('app.media.music_group'))
  4504. .borderRadius(this.isCoverRectangle?9:'100%')
  4505. .clip(true)
  4506. .shadow({
  4507. radius: 2,
  4508. type: ShadowType.BLUR,
  4509. color: 'on_primary'
  4510. })
  4511. .sourceSize({width:38, height:38})
  4512. .margin({ left: 20, top: 8, bottom: 8 })
  4513. Column() {
  4514. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4515. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4516. .maxLines(1)// .width('88%')
  4517. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4518. .animation({
  4519. duration: 555,
  4520. curve: 'ease-in-out',
  4521. })
  4522. .transition({
  4523. type: TransitionType.Insert,
  4524. opacity: 0,
  4525. translate: { x: 160 }
  4526. })
  4527. .margin({ left: 10, right: 20 })
  4528. .fontColor($r('app.color.text_color'))
  4529. Row() {
  4530. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  4531. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4532. .padding({ top: 8 })
  4533. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  4534. .fontColor($r('app.color.text_color'))
  4535. .margin({ left: 10 })
  4536. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  4537. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4538. .padding({ top: 8 })
  4539. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  4540. .fontColor($r('app.color.text_color'))
  4541. .margin({ left: 10 })
  4542. Blank()
  4543. }
  4544. }
  4545. .height('100%')
  4546. .layoutWeight(1)
  4547. .justifyContent(FlexAlign.Center)
  4548. .alignItems(HorizontalAlign.Start)
  4549. Blank()
  4550. Image($r('app.media.arrow_right'))
  4551. .height(25)
  4552. .alignSelf(ItemAlign.Center)
  4553. .id(item.filePath)
  4554. .visibility(this.isShowAlphaBet?Visibility.None:Visibility.Visible)
  4555. .animation({ duration: 300, curve: Curve.Ease })
  4556. }
  4557. }
  4558. .backgroundColor(Color.Transparent)
  4559. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  4560. .width('98%')
  4561. .reuseId('dir_item')
  4562. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  4563. .opacity(this.opacityItem) // 绑定透明度
  4564. }
  4565. isShowDir(dirName: string) {
  4566. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  4567. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  4568. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  4569. if (dirName === undefined) {
  4570. return true
  4571. }
  4572. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  4573. return this.isShowSimi
  4574. }
  4575. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  4576. return this.isShowFAV
  4577. }
  4578. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  4579. return this.isShowHistory
  4580. }
  4581. return true
  4582. }
  4583. @State opacityItem: number = 1; // 控制透明度的状态变量
  4584. @Builder
  4585. private MusicItem(item: VideoItem, index?: number) {
  4586. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  4587. Row() {
  4588. Stack() {
  4589. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  4590. .fillColor(this.themeColor)
  4591. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4592. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4593. .alt($r('app.media.alt'))
  4594. .borderRadius(this.isCoverRectangle?9:'100%')
  4595. .clip(true)
  4596. .draggable(false)
  4597. .sourceSize({width:38, height:38})
  4598. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4599. // .autoResize(true) // 重采样,可减少内存占用
  4600. .opacity(this.opacityItem)// 绑定透明度
  4601. .margin({ left: 20 })
  4602. .shadow({
  4603. radius: StrUtil.isEmpty(item.pixelMapPath) ?6:14,
  4604. type: ShadowType.BLUR,
  4605. color: 'on_primary'
  4606. })
  4607. .gesture(LongPressGesture()
  4608. .onAction(async () => {
  4609. //如果是专辑和艺术家的首页,不能长按
  4610. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4611. return
  4612. //如果是我的收藏 最近播放等也不能长按
  4613. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4614. item.name === LocalMusic.STR_HISTORY_MUSIC
  4615. )
  4616. return
  4617. this.longItemFilePath = item.filePath
  4618. this.tempLyricContent = await this.getLyricContent(item)
  4619. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4620. })
  4621. .onActionEnd((event: GestureEvent) => {
  4622. }))
  4623. .onClick(()=>{
  4624. if (this.isMultiSelect) {
  4625. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4626. this.handleFileSelection(item, !isChecked);
  4627. } else {
  4628. this.doPlay(item,index)
  4629. this.setShowPlayTrue()
  4630. }
  4631. })
  4632. }
  4633. Column() {
  4634. Column() {
  4635. Text(this.isShowFileName?item.fileName :item.name)
  4636. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4637. .maxLines(1)
  4638. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4639. .animation({
  4640. duration: 555,
  4641. curve: 'Linear',
  4642. })
  4643. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4644. $r('app.color.text_color'))
  4645. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4646. .padding({right:25})
  4647. .bindPopup(this.longItemFilePath === item.filePath, {
  4648. builder: this.MenuBuilder(item,index,item.filePath),
  4649. placement: Placement.Top,
  4650. // autoCancel: true,
  4651. mask: {color:'#33000000'},
  4652. // popupColor: Color.Yellow,
  4653. enableArrow: false,//是否显示箭头
  4654. showInSubWindow: false,
  4655. onStateChange: (e) => {
  4656. if (!e.isVisible) {
  4657. this.longItemFilePath = ''
  4658. this.tempLyricContent = ''
  4659. }
  4660. }
  4661. })
  4662. .gesture(LongPressGesture()
  4663. .onAction(async () => {
  4664. //如果是专辑和艺术家的首页,不能长按
  4665. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4666. return
  4667. //如果是我的收藏 最近播放等也不能长按
  4668. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4669. item.name === LocalMusic.STR_HISTORY_MUSIC
  4670. )
  4671. return
  4672. this.longItemFilePath = item.filePath
  4673. this.tempLyricContent = await this.getLyricContent(item)
  4674. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4675. })
  4676. .onActionEnd((event: GestureEvent) => {
  4677. })
  4678. )
  4679. Row() {
  4680. Column(){
  4681. Text(item.md5Str?.includes('Lossless')?
  4682. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4683. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  4684. .padding({ top: 3,right:6,left:6,bottom:3 })
  4685. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4686. $r('app.color.text_color'))
  4687. .fontWeight(500)
  4688. .borderRadius(12)
  4689. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  4690. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4691. .backgroundColor('#FFC107')
  4692. }
  4693. .padding({ top: 8 })
  4694. Text(StrUtil.isEmpty(item.artist) ? item.duration
  4695. :this.twoFingerType==2? item.artist +' ' + item.duration
  4696. : item.artist + ' ' + item?.duration)
  4697. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4698. .padding({ top: 8 ,right:25})
  4699. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  4700. .maxLines(1)
  4701. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4702. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4703. Color.Gray)
  4704. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4705. Blank()
  4706. Text(this.isShowFileName?item.duration:item.size)
  4707. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4708. .padding({ top: 8 })
  4709. .maxLines(1)
  4710. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  4711. ? Visibility.Visible : Visibility.None)
  4712. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4713. Color.Gray)
  4714. .margin({ left: StrUtil.isEmpty(item.artist) ?0:10 })
  4715. }
  4716. .gesture(LongPressGesture()
  4717. .onAction(async () => {
  4718. //如果是专辑和艺术家的首页,不能长按
  4719. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4720. return
  4721. //如果是我的收藏 最近播放等也不能长按
  4722. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4723. item.name === LocalMusic.STR_HISTORY_MUSIC
  4724. )
  4725. return
  4726. this.longItemFilePath = item.filePath
  4727. this.tempLyricContent = await this.getLyricContent(item)
  4728. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4729. })
  4730. .onActionEnd((event: GestureEvent) => {
  4731. })
  4732. )
  4733. }
  4734. .height('100%')
  4735. .width('100%')
  4736. .margin({ right: 10 })
  4737. .justifyContent(FlexAlign.Center)
  4738. .alignItems(HorizontalAlign.Start)
  4739. }
  4740. .height('100%')
  4741. .margin({ left: 5 })
  4742. .layoutWeight(1)
  4743. Column() {
  4744. Checkbox({ name: 'checkbox' + index })
  4745. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  4746. .selectedColor(this.themeColor)
  4747. .shape(CheckBoxShape.CIRCLE)
  4748. .opacity(this.isMultiSelect ? 1 : 0)
  4749. .animation({
  4750. duration: 666,
  4751. curve: 'Smooth' // 可选动画曲线
  4752. })
  4753. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  4754. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  4755. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  4756. .width(22)
  4757. .height(22)
  4758. ImageAnimator()
  4759. .images(this.imagesF)// 动画数组
  4760. .duration(1000)// 持续
  4761. .state(this.animationState)// 动画状态
  4762. .fillMode(FillMode.Forwards)
  4763. .width(18)
  4764. .margin({ right: 20, top: 8, bottom: 8 })
  4765. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  4766. Visibility.None)
  4767. .height(18)
  4768. .iterations(-1) // 播放次数
  4769. }
  4770. }
  4771. }
  4772. .backgroundColor(Color.Transparent)
  4773. .width('100%')
  4774. .reuseId('file_item')
  4775. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  4776. }
  4777. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  4778. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  4779. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  4780. direction: Direction.Ltr,
  4781. buttonPadding:{top:12,bottom:12},
  4782. backgroundColor: Color.Transparent,
  4783. fontSize:14,
  4784. selectedFontSize:15,
  4785. selectedFontColor:Color.White,
  4786. selectedBackgroundColor: this.themeColor,
  4787. localizedTextPadding: {
  4788. end: LengthMetrics.vp(20),
  4789. start: LengthMetrics.vp(20)
  4790. }
  4791. })
  4792. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  4793. //当胶囊按钮的选择发生变化时调用此函数
  4794. capsuleSelectedIndexesChanged() {
  4795. this.modeType = this.tabSelectedIndexes[0]
  4796. }
  4797. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  4798. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  4799. isShowCoverHeader() {
  4800. if (!this.isShowHeader) {
  4801. return false
  4802. }
  4803. if (this.modeType == 0) {
  4804. if (this.isHistory || this.isFavMusic) {
  4805. return true
  4806. }
  4807. if (this.currentPath != this.rootPath) {
  4808. return true
  4809. }
  4810. }
  4811. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  4812. }
  4813. getCoverTitleBg(): ResourceStr | image.PixelMap {
  4814. if (this.isCustomizeBg) {
  4815. return ('rgba(255,255,255,0.2)')
  4816. }
  4817. if (this.isDarkMode) {
  4818. return $r('app.color.user_center_card_background')
  4819. }
  4820. return this.currentTitleCover
  4821. }
  4822. // 第二步:popup构造器定义弹框内容
  4823. @Builder popupBuilder() {
  4824. Column({ space: 2 }) {
  4825. Text('友情提示:双指缩放可以放大缩小列表')
  4826. .fontSize(12)
  4827. .fontWeight(FontWeight.Regular)
  4828. .fontColor($r('app.color.text_color'))
  4829. }
  4830. .justifyContent(FlexAlign.SpaceAround)
  4831. .width(220)
  4832. .height(55)
  4833. .padding(15)
  4834. }
  4835. //搜索功能的实现
  4836. @State searchText: string = ''; // 用户输入内容
  4837. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  4838. @State isSearchMode: boolean = false
  4839. // 实时搜索逻辑(带防抖)
  4840. private onSearchInput(value: string) {
  4841. this.searchText = value.trim();
  4842. let mSearchList: Array<VideoItem> = []
  4843. switch (this.modeType) {
  4844. case 0:
  4845. case 1:
  4846. mSearchList = this.mediaKuList
  4847. break;
  4848. case 2:
  4849. mSearchList = this.artistList
  4850. break;
  4851. case 3:
  4852. mSearchList = this.albumList
  4853. break;
  4854. default :
  4855. mSearchList = this.videoLocalList
  4856. break;
  4857. }
  4858. // 新增条件判断:空输入时显示所有数据
  4859. if (this.searchText === '') {
  4860. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  4861. } else {
  4862. this.filteredList = mSearchList.filter((item: VideoItem) => {
  4863. //支持模糊匹配和艺术家 专辑匹配
  4864. const regex = new RegExp(this.searchText.toLowerCase().replace(/\s+/g, '.*'), 'i');
  4865. return regex.test(item.name.toLowerCase())||
  4866. regex.test(item.fileName?.toLowerCase() ?? "") ||
  4867. regex.test(item.artist?.toLowerCase() ?? "") ||
  4868. regex.test(item.album?.toLowerCase() ?? "")
  4869. });
  4870. }
  4871. this.updateListData(this.filteredList);
  4872. // this.isSearchMode = false; // 根据业务需求决定是否启用
  4873. }
  4874. @State dragItem: number = -1
  4875. @State scaleItem: number = -1
  4876. @State neighborItem: number = -1
  4877. @State neighborScale: number = -1
  4878. @State offsetY: number = 0
  4879. private dragRefOffset: number = 0
  4880. private ITEM_INTV: number = 78
  4881. scaleSelect(item: number): number {
  4882. if (this.scaleItem === item) {
  4883. return 1.05
  4884. } else if (this.neighborItem === item) {
  4885. return this.neighborScale
  4886. } else {
  4887. return 1
  4888. }
  4889. }
  4890. itemMove(index: number, newIndex: number): void {
  4891. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  4892. return;
  4893. }
  4894. let tmp = this.videoLocalList.splice(index, 1);
  4895. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  4896. this.dataSource.pushArrayData(this.videoLocalList)
  4897. if(this.modeType==4&&this.playlistTable){
  4898. updateAllSongsSortOrder(this.playlistTable, this.videoLocalList,this.currentSongListID)
  4899. }
  4900. }
  4901. //瀑布流布局 支持双指缩放
  4902. @State columns: number = 2;
  4903. @State waterFlowScale: number = 1;
  4904. @State imageScale: number = 1;
  4905. @State waterFlowOpacity: number = 1;
  4906. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  4907. private columnChanged: boolean = false;
  4908. private oldColumn: number = this.columns;
  4909. private pinchTime: number = 0;
  4910. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  4911. changeColumns(scale: number) {
  4912. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  4913. this.columns--;
  4914. this.columnChanged = true;
  4915. } else if (scale < 1 && this.columns < 4) {
  4916. this.columns++;
  4917. this.columnChanged = true;
  4918. }
  4919. }
  4920. @Builder
  4921. getWaterView(){
  4922. Scroll(this.scroller) {
  4923. Column() {
  4924. Blank().height(this.topSafeHeight + 55)
  4925. WaterFlow({
  4926. scroller:this.waterScroller,
  4927. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  4928. }) {
  4929. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  4930. FlowItem() {
  4931. this.MusicWaterCardItem(item,index)
  4932. }
  4933. .width('100%')
  4934. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  4935. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  4936. {
  4937. preview: MenuPreviewMode.IMAGE,
  4938. previewAnimationOptions: { scale: [0.8, 1.0] },
  4939. })
  4940. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  4941. {
  4942. preview: MenuPreviewMode.IMAGE,
  4943. previewAnimationOptions: { scale: [0.8, 1.0] },
  4944. })
  4945. .transition(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }))
  4946. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  4947. TransitionEffect.scale({ x: 0, y: 0 })))
  4948. .gesture(
  4949. GestureGroup(GestureMode.Exclusive,
  4950. SwipeGesture({ direction: SwipeDirection.Horizontal })
  4951. .onAction((event: GestureEvent) => {
  4952. if (event) {
  4953. // this.sideBarController.openSideBar()
  4954. }
  4955. }),
  4956. TapGesture({ count: 1, fingers: 1 })
  4957. .onAction(async () => {
  4958. })
  4959. )
  4960. )
  4961. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  4962. }
  4963. // .columnsTemplate('repeat(auto-fit, 160)')
  4964. .id('waterflow') // 设置id用于截图
  4965. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  4966. .columnsGap(12) // 列间距
  4967. .rowsGap(16) // 行间距
  4968. .cachedCount(6)
  4969. .padding({bottom:this.bottomBarHeight+10})
  4970. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4971. .animation({ duration: 500, curve: Curve.Ease }))
  4972. .scrollBar(BarState.Off)
  4973. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  4974. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  4975. .edgeEffect(EdgeEffect.Spring, { alwaysEnabled: true })
  4976. .width('90%')
  4977. .height('100%')
  4978. .opacity(this.waterFlowOpacity)
  4979. .scale({
  4980. x: this.waterFlowScale,
  4981. y: this.waterFlowScale,
  4982. centerX: 0,
  4983. centerY: 0
  4984. })
  4985. .onAppear(() => {
  4986. this.scroller.scrollEdge(Edge.Top)
  4987. })
  4988. .nestedScroll({
  4989. scrollForward: NestedScrollMode.PARENT_FIRST,
  4990. scrollBackward: NestedScrollMode.SELF_FIRST
  4991. })
  4992. .priorityGesture(
  4993. PinchGesture()
  4994. .onActionStart((event: GestureEvent) => {
  4995. // 双指捏合手势识别成功时截图
  4996. this.pinchTime = event.timestamp;
  4997. this.columnChanged = false;
  4998. this.oldColumn = this.columns;
  4999. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  5000. if (error) {
  5001. console.info('error:' + JSON.stringify(error));
  5002. return;
  5003. }
  5004. this.waterFlowSnapshot = pixmap;
  5005. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  5006. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  5007. if (this.oldColumn ===4) {
  5008. this.twoFingerType =3
  5009. this.isGridMusic = true
  5010. }else if (this.oldColumn ===1) {
  5011. this.twoFingerType =1
  5012. this.isGridMusic = false
  5013. }
  5014. return;
  5015. }
  5016. })
  5017. })
  5018. .onActionUpdate((event: GestureEvent) => {
  5019. // 手势更新:处理缩放逻辑和视觉效果
  5020. // 边界限制:防止超出列数范围时继续缩放
  5021. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  5022. return;
  5023. }
  5024. // 节流处理:避免过于频繁的更新,提升性能
  5025. if (event.timestamp - this.pinchTime < 10000000) {
  5026. return;
  5027. }
  5028. this.pinchTime = event.timestamp;
  5029. this.waterFlowScale = event.scale;
  5030. this.imageScale = event.scale;
  5031. // 根据缩放比例设置WaterFlow透明度
  5032. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  5033. this.waterFlowOpacity *= 3;
  5034. if (!this.columnChanged) {
  5035. this.changeColumns(event.scale);
  5036. }
  5037. // 列数改变后的缩放比例调整:避免出现空白区域
  5038. if (this.columnChanged) {
  5039. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  5040. // 限制缩放范围,确保视觉效果自然
  5041. if (event.scale < 1) {
  5042. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  5043. } else {
  5044. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  5045. }
  5046. }
  5047. })
  5048. .onActionEnd((event: GestureEvent) => {
  5049. // 手势结束:执行归位动画并保存状态
  5050. // 执行归位动画:平滑过渡到正常状态
  5051. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  5052. this.waterFlowScale = 1;
  5053. this.waterFlowOpacity = 1;
  5054. })
  5055. // 持久化保存当前列数:下次启动时恢复
  5056. PreferencesUtil.putSync('lastColumns', this.columns);
  5057. })
  5058. )
  5059. .onScrollFrameBegin((offset: number) => {
  5060. // 获取当前滚动偏移量
  5061. if(this.autoHideTitle){
  5062. const currentOffsetY = this.waterScroller.currentOffset().yOffset;
  5063. // 判断滚动方向
  5064. if (currentOffsetY > this.prevOffsetY) {
  5065. // console.log("onecold 向上滚动");
  5066. this.isShowTitleBar = false
  5067. } else if (currentOffsetY < this.prevOffsetY) {
  5068. // console.log("onecold 向下滚动");
  5069. this.isShowTitleBar = true
  5070. }
  5071. // 更新前一次偏移量
  5072. this.prevOffsetY = currentOffsetY;
  5073. }
  5074. return { offsetRemain: offset };
  5075. })
  5076. }
  5077. }
  5078. .scrollBar(BarState.Off)
  5079. }
  5080. //瀑布流卡片布局
  5081. @Builder
  5082. private MusicWaterCardItem(item: VideoItem, index: number) {
  5083. Button({ type: ButtonType.Normal, stateEffect: false }) {
  5084. Stack() {
  5085. Column() {
  5086. Image(item.pixelMapPath)
  5087. .backgroundImageSize(ImageSize.Auto)
  5088. .borderRadius({
  5089. topLeft: 12,
  5090. topRight : 12,
  5091. bottomLeft: 0,
  5092. bottomRight: 0
  5093. })
  5094. .draggable(false)// 禁止长按手势拖动
  5095. .autoResize(true) // 重采样,可减少内存占用
  5096. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  5097. .width('100%')
  5098. .height('auto')
  5099. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  5100. .objectFit(ImageFit.Auto)
  5101. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  5102. height: '99%' ,
  5103. dragBar: true,
  5104. onDisappear: () => {
  5105. this.longItemFilePath = '';
  5106. this.tempLyricContent = ''
  5107. },
  5108. showClose: true,
  5109. preferType: SheetType.CENTER ,
  5110. title: { title: '编辑标签' }
  5111. })
  5112. .draggable(false)
  5113. .opacity(this.opacityItem)// 绑定透明度
  5114. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  5115. // .animation({ duration: 500, curve: Curve.Ease }))
  5116. .animation({
  5117. duration: 666,
  5118. curve: 'ease-in-out' // 可选动画曲线
  5119. })
  5120. .margin({
  5121. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5122. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5123. })
  5124. Column() {
  5125. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5126. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  5127. .maxLines(1)
  5128. .fontWeight(FontWeight.Bold)
  5129. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5130. .animation({
  5131. duration: 555,
  5132. curve: 'Linear',
  5133. })
  5134. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  5135. height: '95%',
  5136. dragBar: true,
  5137. showClose: true,
  5138. onDisappear: () => {
  5139. this.longItemFilePathDetail = '';
  5140. },
  5141. blurStyle:BlurStyle.Thin,
  5142. backgroundColor:Color.Transparent,
  5143. preferType: SheetType.CENTER ,
  5144. title: { title: '详情' }
  5145. })
  5146. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5147. $r('app.color.text_color'))
  5148. Column() {
  5149. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  5150. .fontSize(11)
  5151. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  5152. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5153. .fontColor($r('app.color.text_color'))
  5154. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  5155. .fontSize(11)
  5156. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  5157. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5158. .fontColor($r('app.color.text_color'))
  5159. Row(){
  5160. Column(){
  5161. Text(item.md5Str?.includes('Lossless')?
  5162. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5163. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  5164. .padding({ top: 3,right:6,left:6,bottom:3 })
  5165. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5166. $r('app.color.text_color'))
  5167. .fontWeight(500)
  5168. .borderRadius(12)
  5169. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5170. .backgroundColor('#FFC107')
  5171. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  5172. }
  5173. .margin({ top: 2 ,right:6})
  5174. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  5175. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  5176. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  5177. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  5178. .maxLines(1)
  5179. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5180. .margin({ top: 2})
  5181. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  5182. || item.type == CommonConstants.TYPE_IS_ALBUM
  5183. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5184. .fontWeight(FontWeight.Medium)
  5185. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5186. $r('app.color.text_color'))
  5187. }
  5188. }
  5189. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  5190. }
  5191. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  5192. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  5193. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  5194. .width('100%')
  5195. .justifyContent(FlexAlign.Center)
  5196. .margin({
  5197. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5198. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5199. })
  5200. }
  5201. .width('100%')
  5202. .borderRadius(12)
  5203. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  5204. .backgroundImageSize({ height: '100%', width: '100%' })
  5205. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  5206. .animation({ curve: Curve.Sharp, duration: 300 })
  5207. Checkbox({ name: 'checkbox' + index })
  5208. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  5209. .selectedColor(this.themeColor)
  5210. .shape(CheckBoxShape.CIRCLE)
  5211. .opacity(this.isMultiSelect ? 1 : 0)
  5212. .animation({
  5213. duration: 666,
  5214. curve: 'Smooth' // 可选动画曲线
  5215. })
  5216. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  5217. Visibility.None)
  5218. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5219. .margin({ left: 20, top: 8, bottom: 8 })
  5220. .width(38)
  5221. .height(38)
  5222. }
  5223. }
  5224. .backgroundColor(Color.Transparent)
  5225. .width('100%')
  5226. .height('auto')
  5227. .padding({top:2})
  5228. .shadow({
  5229. radius: 10,
  5230. type: ShadowType.BLUR,
  5231. color: 'on_primary'
  5232. })
  5233. .reuseId('card_item')
  5234. .onClick(() => {
  5235. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5236. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5237. this.handleFileSelection(item, !isChecked);
  5238. } else {
  5239. this.doPlay(item, index)
  5240. }
  5241. })
  5242. }
  5243. // Grid布局的开始
  5244. private dragRefOffSetX: number = 0;
  5245. private dragRefOffSetY: number = 0;
  5246. private FIX_VP_X: number = 180;
  5247. private FIX_VP_Y: number = 84;
  5248. isDraggable(index: number): boolean {
  5249. return index >= 0;
  5250. }
  5251. getRowEnd(item: number) {
  5252. if (item.toString() === '0') {
  5253. return 1;
  5254. } else {
  5255. return 0;
  5256. }
  5257. }
  5258. isInLeft(index: number) {
  5259. return index % 2 == 0;
  5260. }
  5261. down(index: number): void {
  5262. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  5263. return;
  5264. }
  5265. this.offsetY -= this.FIX_VP_Y;
  5266. this.dragRefOffSetY += this.FIX_VP_Y;
  5267. this.itemMove(index, index + 1);
  5268. }
  5269. up(index: number): void {
  5270. if (!this.isDraggable(index - 2)) {
  5271. return;
  5272. }
  5273. this.offsetY += this.FIX_VP_Y;
  5274. this.dragRefOffSetY -= this.FIX_VP_Y;
  5275. this.itemMove(index, index - 1);
  5276. }
  5277. left(index: number): void {
  5278. if (this.isInLeft(index)) {
  5279. return;
  5280. }
  5281. if (!this.isDraggable(index - 1)) {
  5282. return;
  5283. }
  5284. this.offsetX += this.FIX_VP_X;
  5285. this.dragRefOffSetX -= this.FIX_VP_X;
  5286. this.itemMove(index, index - 1)
  5287. }
  5288. right(index: number): void {
  5289. if (!this.isInLeft(index)) {
  5290. return;
  5291. }
  5292. if (!this.isDraggable(index + 1)) {
  5293. return;
  5294. }
  5295. this.offsetX -= this.FIX_VP_X;
  5296. this.dragRefOffSetX += this.FIX_VP_X;
  5297. this.itemMove(index, index + 1)
  5298. }
  5299. private scroller: Scroller = new Scroller();
  5300. private waterScroller: Scroller = new Scroller();
  5301. @State startIndex: number = 0
  5302. @State endIndex: number = 0
  5303. @State scaleValue: number = 1
  5304. @State pinchValue: number = 1
  5305. layoutOptionsForHeader: GridLayoutOptions = {
  5306. regularSize: [1, 1], // 只支持[1, 1]
  5307. irregularIndexes: [0], // 索引为0的GridItem占用一行
  5308. };
  5309. @Builder
  5310. getGridView() {
  5311. Grid(this.scroller, this.layoutOptionsForHeader) {
  5312. GridItem() {
  5313. Column(){
  5314. Blank().height(this.topSafeHeight + 45)
  5315. }
  5316. }
  5317. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5318. GridItem() {
  5319. Stack({ alignContent: Alignment.Center }) {
  5320. this.MusicItemGrid(item, index)
  5321. }
  5322. }
  5323. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  5324. {
  5325. preview: MenuPreviewMode.IMAGE,
  5326. previewAnimationOptions: { scale: [0.8, 1.0] },
  5327. })
  5328. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  5329. {
  5330. preview: MenuPreviewMode.IMAGE,
  5331. previewAnimationOptions: { scale: [0.8, 1.0] },
  5332. })
  5333. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  5334. TransitionEffect.scale({ x: 0, y: 0 })))
  5335. .clickEffect({ level: ClickEffectLevel.LIGHT })
  5336. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  5337. .zIndex(this.dragItem === index ? 1 : 0)
  5338. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  5339. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5340. }
  5341. .width('94%')
  5342. .height('100%')
  5343. .editMode(true)
  5344. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  5345. .animation({ duration: 500, curve: Curve.Ease }))
  5346. .padding({bottom:this.bottomBarHeight+this.bottomSafeHeight+10})
  5347. .reuseId('grid_item')
  5348. .layoutWeight(1)
  5349. .scrollBar(BarState.Off)
  5350. .supportAnimation(true)
  5351. .cachedCount(this.twoFingerType==1?5:this.twoFingerType==2?4:3)
  5352. .columnsTemplate(
  5353. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  5354. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  5355. )
  5356. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  5357. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  5358. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5359. .gesture(PinchGesture({ fingers: 2 })
  5360. .onActionEnd((event: GestureEvent) => {
  5361. this.setGridTwoFingers()
  5362. })
  5363. .onActionUpdate(e => {
  5364. this.scaleValue = this.pinchValue * e.scale
  5365. })
  5366. .onActionStart(e => {
  5367. }))
  5368. .enableScrollInteraction(true)
  5369. .onScrollIndex((start: number, end: number) => {
  5370. this.startIndex = start
  5371. this.endIndex = end
  5372. })
  5373. .onScrollFrameBegin((offset: number) => {
  5374. if(this.autoHideTitle){
  5375. const currentOffsetY = this.scroller.currentOffset().yOffset;
  5376. // 判断滚动方向
  5377. if (currentOffsetY > this.prevOffsetY) {
  5378. // console.log("onecold 向上滚动");
  5379. this.isShowTitleBar = false
  5380. } else if (currentOffsetY < this.prevOffsetY) {
  5381. // console.log("onecold 向下滚动");
  5382. this.isShowTitleBar = true
  5383. }
  5384. // 更新前一次偏移量
  5385. this.prevOffsetY = currentOffsetY;
  5386. }
  5387. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  5388. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  5389. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  5390. if (this.isScrollHide) {
  5391. this.setBarHeightHide2(offset)
  5392. } else {
  5393. this.setBarHeightNormal()
  5394. }
  5395. } else {
  5396. this.setBarHeightHide(offset)
  5397. }
  5398. return { offsetRemain: offset };
  5399. })
  5400. }
  5401. @State targetFile: string = '';
  5402. setGridTwoFingers() {
  5403. this.pinchValue = this.scaleValue;
  5404. Logger.info('this.pinchValue = ' + this.pinchValue);
  5405. if (this.pinchValue >= 1) {
  5406. this.twoFingerType++
  5407. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  5408. if(this.twoFingerType >= 4){
  5409. this.twoFingerType = 4//切换成瀑布流
  5410. this.columns = 4
  5411. }
  5412. } else {
  5413. this.twoFingerType--
  5414. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  5415. if (this.twoFingerType < 1) {
  5416. this.twoFingerType = 3
  5417. this.isGridMusic = false
  5418. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5419. }
  5420. }
  5421. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5422. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5423. this.pinchValue = 1;
  5424. this.scaleValue = 1;
  5425. }
  5426. @State longItemFilePath: string = ''
  5427. @State tempLyricContent: string = ''
  5428. @State editingItem: VideoItem | null = null
  5429. @Builder
  5430. private MusicItemGrid(item: VideoItem, index: number) {
  5431. Button({ type: ButtonType.Normal, stateEffect: false }) {
  5432. Stack() {
  5433. Column() {
  5434. Image(item.pixelMapPath)
  5435. .height(this.getGridHeight())
  5436. .width(this.getGridWight())
  5437. .draggable(false)
  5438. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  5439. .autoResize(true) // 重采样,可减少内存占用
  5440. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  5441. .clip(true)
  5442. .borderRadius({
  5443. topLeft: 12,
  5444. topRight: 12,
  5445. bottomLeft: 0,
  5446. bottomRight: 0
  5447. })
  5448. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  5449. height: '99%' ,
  5450. dragBar: true,
  5451. onDisappear: () => {
  5452. this.longItemFilePath = '';
  5453. this.tempLyricContent = ''
  5454. },
  5455. showClose: true,
  5456. preferType: SheetType.CENTER ,
  5457. title: { title: '编辑标签' }
  5458. })
  5459. .draggable(false)
  5460. .opacity(this.opacityItem)// 绑定透明度
  5461. .animation({
  5462. duration: 666,
  5463. curve: 'ease-in-out' // 可选动画曲线
  5464. })
  5465. .margin({
  5466. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5467. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5468. })
  5469. Column() {
  5470. Text(this.isShowFileName&&item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5471. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5472. .maxLines(1)
  5473. .fontWeight(FontWeight.Bold)
  5474. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5475. .animation({
  5476. duration: 555,
  5477. curve: 'Linear',
  5478. })
  5479. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  5480. height: '100%',
  5481. dragBar: true,
  5482. showClose: true,
  5483. onDisappear: () => {
  5484. this.longItemFilePathDetail = '';
  5485. },
  5486. blurStyle:BlurStyle.Thin,
  5487. backgroundColor:Color.Transparent,
  5488. preferType: SheetType.CENTER ,
  5489. title: { title: '详情' }
  5490. })
  5491. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5492. $r('app.color.text_color'))
  5493. Column() {
  5494. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  5495. .fontSize(11)
  5496. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  5497. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5498. .fontColor($r('app.color.text_color'))
  5499. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  5500. .fontSize(11)
  5501. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  5502. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5503. .fontColor($r('app.color.text_color'))
  5504. Row(){
  5505. Column(){
  5506. Text(item.md5Str?.includes('Lossless')?
  5507. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5508. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5509. .padding({ top: 3,right:6,left:6,bottom:3 })
  5510. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5511. $r('app.color.text_color'))
  5512. .fontWeight(500)
  5513. .borderRadius(12)
  5514. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5515. .backgroundColor('#FFC107')
  5516. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  5517. }
  5518. .margin({ top: 2 ,right:6})
  5519. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  5520. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  5521. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  5522. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  5523. .maxLines(1)
  5524. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5525. .margin({ top: 2})
  5526. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  5527. || item.type == CommonConstants.TYPE_IS_ALBUM
  5528. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5529. .fontWeight(FontWeight.Medium)
  5530. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5531. $r('app.color.text_color'))
  5532. }
  5533. }
  5534. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  5535. }
  5536. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  5537. .width(this.getGridWight())
  5538. .justifyContent(FlexAlign.Center)
  5539. .margin({
  5540. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5541. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5542. })
  5543. }
  5544. .width(this.getGridWight())
  5545. .borderRadius(12)
  5546. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?$r('app.media.alt'):item.pixelMapPath)
  5547. .backgroundImageSize({ height: '100%', width: '100%' })
  5548. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  5549. .animation({ curve: Curve.Sharp, duration: 300 })
  5550. Checkbox({ name: 'checkbox' + index })
  5551. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  5552. .selectedColor(this.themeColor)
  5553. .shape(CheckBoxShape.CIRCLE)
  5554. .opacity(this.isMultiSelect ? 1 : 0)
  5555. .animation({
  5556. duration: 666,
  5557. curve: 'Smooth' // 可选动画曲线
  5558. })
  5559. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  5560. Visibility.None)
  5561. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5562. .margin({ left: 20, top: 8, bottom: 8 })
  5563. .width(38)
  5564. .height(38)
  5565. }
  5566. }
  5567. .backgroundColor(Color.Transparent)
  5568. .width('100%')
  5569. .padding({ top: 15 })
  5570. .height(this.getGridAllHeight())
  5571. .onClick(() => {
  5572. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5573. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5574. this.handleFileSelection(item, !isChecked);
  5575. } else {
  5576. this.doPlay(item, index)
  5577. }
  5578. })
  5579. }
  5580. getGridAllHeight() {
  5581. let heightG = 222
  5582. switch (this.twoFingerType) {
  5583. case 1:
  5584. heightG = 143
  5585. break;
  5586. case 2:
  5587. heightG = 178
  5588. break;
  5589. case 3:
  5590. heightG = 222
  5591. break;
  5592. }
  5593. return heightG
  5594. }
  5595. getGridHeight() {
  5596. let heightG = 150
  5597. switch (this.twoFingerType) {
  5598. case 1:
  5599. heightG = 80
  5600. break;
  5601. case 2:
  5602. heightG = 110
  5603. break;
  5604. case 3:
  5605. heightG = 150
  5606. break;
  5607. }
  5608. return heightG
  5609. }
  5610. getGridWight() {
  5611. let wightG = 158
  5612. switch (this.twoFingerType) {
  5613. case 1:
  5614. wightG = 80
  5615. break;
  5616. case 2:
  5617. wightG = 110
  5618. break;
  5619. case 3:
  5620. wightG = 158
  5621. break;
  5622. }
  5623. return wightG
  5624. }
  5625. @State isShowDetail:boolean = false
  5626. @State longItemFilePathDetail:string =''
  5627. @Builder
  5628. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  5629. if(
  5630. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  5631. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5632. item.name === LocalMusic.STR_HISTORY_MUSIC)
  5633. ){
  5634. //如果是专辑和艺术家的首页,不能长按
  5635. //如果是我的收藏 最近播放等也不能长按
  5636. }else{
  5637. Scroll() {
  5638. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  5639. Menu() {
  5640. MenuItem({
  5641. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  5642. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  5643. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  5644. })
  5645. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5646. .onClick(() => {
  5647. if (item) {
  5648. this.doFav(item)
  5649. }
  5650. this.longItemFilePath = ''
  5651. })
  5652. MenuItem({
  5653. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  5654. content: '下一首播放'
  5655. })
  5656. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5657. .onClick(() => {
  5658. this.addToNextPlay(item);
  5659. this.longItemFilePath = ''
  5660. })
  5661. MenuItem({
  5662. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  5663. content: '添加到歌单'
  5664. })
  5665. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5666. .onClick(async () => {
  5667. this.longItemFilePath = ''
  5668. await this.openAddToPlaylistDialog(item)
  5669. })
  5670. MenuItem({
  5671. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  5672. content: '编辑标签'
  5673. })
  5674. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  5675. height: '99%',
  5676. dragBar: true,
  5677. showClose: true,
  5678. preferType: SheetType.CENTER ,
  5679. title: { title: '编辑标签' }
  5680. })
  5681. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5682. .onClick(async() => {
  5683. this.initEditFields(item)
  5684. this.tempLyricContent = await this.getLyricContent(item);
  5685. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  5686. this.lyricConStr = this.tempLyricContent
  5687. }
  5688. if(this.isGridMusic||this.twoFingerType==4){
  5689. this.longItemFilePath = item.filePath
  5690. }else{
  5691. this.isShowEdit = !this.isShowEdit;
  5692. }
  5693. })
  5694. MenuItem({
  5695. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  5696. content: $r('app.string.select_all')
  5697. })
  5698. .onClick(() => {
  5699. this.isMultiSelect = !this.isMultiSelect
  5700. this.longItemFilePath = ''
  5701. this.selectedFiles.push(item)
  5702. })
  5703. MenuItem({
  5704. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.cut')),
  5705. content: $r('app.string.edit_audio')
  5706. })
  5707. .bindContentCover($$this.isEditAudio, this.EditAudioBuilder(item), {
  5708. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5709. })
  5710. .onClick(() => {
  5711. this.isEditAudio = !this.isEditAudio
  5712. })
  5713. MenuItem({
  5714. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  5715. content: $r('app.string.extract_accompaniment')
  5716. })
  5717. .bindContentCover($$this.isExtractAcc, this.ExtractAccBuilder(item), {
  5718. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5719. })
  5720. .onClick(() => {
  5721. if (!Utility.isNoble()) {
  5722. this.showVipDialog()
  5723. return
  5724. }
  5725. this.isExtractAcc = !this.isExtractAcc
  5726. })
  5727. MenuItem({
  5728. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.repeat')),
  5729. content: $r('app.string.converter_audio')
  5730. })
  5731. .bindContentCover($$this.isConverter, this.ConverterBuilder(item), {
  5732. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5733. })
  5734. .onClick(() => {
  5735. if (!Utility.isNoble()) {
  5736. this.showVipDialog()
  5737. return
  5738. }
  5739. this.isConverter = !this.isConverter
  5740. })
  5741. MenuItem({
  5742. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.ai_edit')),
  5743. content: $r('app.string.vocal_separation')
  5744. })
  5745. .bindContentCover($$this.isAIVoiceSeparation, this.AiBuilder(item), {
  5746. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5747. })
  5748. .onClick(() => {
  5749. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  5750. })
  5751. MenuItem({
  5752. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_counterclockwise_clock')),
  5753. content: $r('app.string.change_tone')
  5754. })
  5755. .bindContentCover($$this.isChangeTone, this.ChangeToneBuilder(item), {
  5756. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5757. })
  5758. .onClick(() => {
  5759. this.isChangeTone = !this.isChangeTone
  5760. })
  5761. if(Utility.isVideoByExtension(item.filePath)){
  5762. MenuItem({
  5763. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.identify_song')),
  5764. content: $r('app.string.extract_audio')
  5765. })
  5766. .bindContentCover($$this.isExtractAudio, this.extractAudioFromVideoBuilder(item), {
  5767. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5768. })
  5769. .onClick(() => {
  5770. this.isExtractAudio = !this.isExtractAudio
  5771. })
  5772. }
  5773. MenuItem({
  5774. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.phone')),
  5775. content: $r('app.string.set_ring')
  5776. })
  5777. .onClick(async () => {
  5778. await PermissionUtil.activatePermission(item.filePath)
  5779. // if(item.filePath.includes(this.packName)){
  5780. setRingTone(this.context, item.filePath,item.name)
  5781. // }else{
  5782. // ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限设置铃声')
  5783. // }
  5784. this.longItemFilePath = ''
  5785. })
  5786. MenuItem({
  5787. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  5788. content: $r('app.string.rename')
  5789. })
  5790. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  5791. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5792. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  5793. .onClick(() => {
  5794. this.showReNameDialog(item, index + '', filePath)
  5795. this.longItemFilePath = ''
  5796. })
  5797. MenuItem({
  5798. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  5799. content: $r('app.string.delete')
  5800. })
  5801. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  5802. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5803. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  5804. .onClick(() => {
  5805. this.selectedFiles.push(item)
  5806. this.showWarnIsDelete()
  5807. this.longItemFilePath = ''
  5808. })
  5809. MenuItem({
  5810. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  5811. content: $r('app.string.detail')
  5812. })
  5813. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  5814. height:'100%',
  5815. dragBar: true,
  5816. showClose: true,
  5817. blurStyle:BlurStyle.Thin,
  5818. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  5819. backgroundColor:Color.Transparent,
  5820. title: { title: '详情信息' }
  5821. })
  5822. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5823. .onClick(() => {
  5824. if(this.isGridMusic||this.twoFingerType==4){
  5825. this.longItemFilePathDetail = item.filePath
  5826. }else{
  5827. this.isShowDetail = !this.isShowDetail
  5828. }
  5829. })
  5830. MenuItem({
  5831. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  5832. content: $r('app.string.share')
  5833. })
  5834. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5835. .onClick(() => {
  5836. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  5837. this.longItemFilePath = ''
  5838. })
  5839. }
  5840. .font({ size: 14, weight: FontWeight.Normal })
  5841. }
  5842. .width(180)
  5843. }
  5844. .height('auto')
  5845. .enableScrollInteraction(true)
  5846. .scrollBar(this.isGridMusic?BarState.On:BarState.Off)
  5847. }
  5848. }
  5849. private listMaxScrollOffsetY: number = 0
  5850. @State selectedIndex: number = -1
  5851. setlistTwoFingers() {
  5852. this.pinchValue = this.scaleValue;
  5853. Logger.info('this.pinchValue = ' + this.pinchValue);
  5854. if (this.pinchValue >= 1) {
  5855. this.twoFingerType++
  5856. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  5857. if (this.twoFingerType > 3) {
  5858. this.twoFingerType = 1
  5859. this.isGridMusic = true
  5860. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5861. }
  5862. } else {
  5863. this.twoFingerType--
  5864. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  5865. if (this.twoFingerType < 1) {
  5866. this.twoFingerType = 4
  5867. this.columns = 1
  5868. }
  5869. }
  5870. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5871. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5872. this.pinchValue = 1;
  5873. this.scaleValue = 1;
  5874. }
  5875. @Builder
  5876. getList(){
  5877. Stack() {
  5878. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  5879. this.getListView()
  5880. }
  5881. .pullDownRatio(this.ratioL)
  5882. .pullToRefresh(true)
  5883. .refreshOffset(0)
  5884. .onOffsetChange((offset: number) => {
  5885. // 越接近最大距离,下拉跟手系数越小。
  5886. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  5887. })
  5888. .onStateChange((refreshStatus: RefreshStatus) => {
  5889. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  5890. })
  5891. .onRefreshing(async () => {
  5892. if(this.modeType==0){
  5893. this.getHistoryList(false)
  5894. this.asyncCurrentPathOnlyFile()
  5895. }else if(this.modeType == 1){
  5896. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  5897. }else if(this.modeType == 2){
  5898. workerInstance.postMessage({ code: 3, data: this.context });
  5899. }else if(this.modeType == 3){
  5900. workerInstance.postMessage({ code: 4, data: this.context });
  5901. }else if(this.modeType == 4){
  5902. this.doSongListTask()
  5903. }
  5904. console.log('onRefreshing test');
  5905. })
  5906. }
  5907. }
  5908. // 扫描当前目录下的文件,不扫描子目录
  5909. asyncCurrentPathOnlyFile(){
  5910. if(this.modeType==0){
  5911. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  5912. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  5913. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  5914. if(this.modeType==0){
  5915. setTimeout(()=>{
  5916. this.isRefreshing =false
  5917. this.deleteCache(this.currentPath)
  5918. this.getSortedFiles(this.currentPath)
  5919. },500)
  5920. }
  5921. }).catch((e:object)=>{
  5922. this.isRefreshing =false
  5923. console.info("onecold task1 catch e: " + e);
  5924. })
  5925. }
  5926. }
  5927. @Builder
  5928. getListView() {
  5929. List({ scroller: this.listScroller }) {
  5930. // ListItemGroup({ header: this.coverHeader() }) {
  5931. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5932. ListItem() {
  5933. Column() {
  5934. if (item.type === CommonConstants.TYPE_IS_DIR
  5935. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  5936. this.DirItem(item, index)
  5937. } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
  5938. } else {
  5939. this.MusicItem(item, index)
  5940. }
  5941. }
  5942. .shadow(this.scaleItem === index ? {
  5943. radius: 70,
  5944. color: '#15000000',
  5945. offsetX: 0,
  5946. offsetY: 0
  5947. } :
  5948. {
  5949. radius: 0,
  5950. color: '#15000000',
  5951. offsetX: 0,
  5952. offsetY: 0
  5953. })
  5954. .animation({ curve: Curve.Sharp, duration: 300 })
  5955. }
  5956. // .transition(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }))
  5957. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.9, y: 0.9 })
  5958. .animation({ duration: 500 }),
  5959. TransitionEffect.scale({ x: 0, y: 0 })))
  5960. .clickEffect({ level: ClickEffectLevel.LIGHT })
  5961. .swipeAction((
  5962. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  5963. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  5964. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  5965. start:null,edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  5966. .onClick(() => {
  5967. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5968. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5969. this.handleFileSelection(item, !isChecked);
  5970. } else {
  5971. this.doPlay(item, index)
  5972. }
  5973. })
  5974. //拖动List关键代码开始
  5975. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  5976. .zIndex(this.dragItem === index ? 1 : 0)
  5977. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  5978. .gesture(
  5979. GestureGroup(GestureMode.Sequence,
  5980. LongPressGesture({ repeat: true })
  5981. .onAction((event?: GestureEvent) => {
  5982. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5983. this.scaleItem = index
  5984. })
  5985. })
  5986. .onActionEnd(() => {
  5987. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5988. this.scaleItem = -1
  5989. })
  5990. }),
  5991. PanGesture({ fingers: 1, direction: null, distance: 0 })
  5992. .onActionStart(() => {
  5993. this.dragItem = index // 记录当前拖动项索引
  5994. this.dragRefOffset = 0 // 重置偏移基准
  5995. })
  5996. .onActionUpdate((event: GestureEvent) => {
  5997. this.offsetY = event.offsetY - this.dragRefOffset;
  5998. this.neighborItem = -1;
  5999. let indexA = this.videoLocalList.indexOf(item);
  6000. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  6001. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  6002. let value: number = 0;
  6003. if (this.offsetY < 0) {
  6004. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  6005. this.neighborItem = indexA - 1;
  6006. this.neighborScale = 1 - value / 20;
  6007. } else if (this.offsetY > 0) {
  6008. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  6009. this.neighborItem = indexA + 1;
  6010. this.neighborScale = 1 - value / 20;
  6011. }
  6012. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  6013. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6014. this.offsetY -= this.ITEM_INTV;
  6015. this.dragRefOffset += this.ITEM_INTV;
  6016. this.itemMove(indexA, indexA + 1);
  6017. });
  6018. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  6019. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6020. this.offsetY += this.ITEM_INTV;
  6021. this.dragRefOffset -= this.ITEM_INTV;
  6022. this.itemMove(indexA, indexA - 1);
  6023. });
  6024. }
  6025. let curListOffset = this.listScroller.currentOffset()
  6026. // 获取手指信息
  6027. let fingerInfo = event.fingerList[0]
  6028. let clickPercentY =
  6029. (fingerInfo.globalY - Number(this.listArea.globalPosition.y)) / Number(this.listArea.height)
  6030. if (clickPercentY > 0.8 && !this.listScroller.isAtEnd()) {
  6031. let scrollVelocity = clickPercentY > 0.9 ? 4 : 2
  6032. if (this.listMaxScrollOffsetY - curListOffset.yOffset > scrollVelocity + 5) {
  6033. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset += scrollVelocity })
  6034. }
  6035. } else if (clickPercentY < 0.2 && curListOffset.yOffset >= 0) {
  6036. let scrollVelocity = clickPercentY < 0.1 ? 4 : 2
  6037. if (curListOffset.yOffset > scrollVelocity + 5) {
  6038. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset -= scrollVelocity })
  6039. }
  6040. }
  6041. })
  6042. .onActionEnd((event: GestureEvent) => {
  6043. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6044. this.dragItem = -1
  6045. this.neighborItem = -1
  6046. })
  6047. animateTo({
  6048. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  6049. }, () => {
  6050. this.scaleItem = -1
  6051. })
  6052. })
  6053. )
  6054. .onCancel(() => {
  6055. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6056. this.dragItem = -1
  6057. this.neighborItem = -1
  6058. })
  6059. animateTo({
  6060. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  6061. }, () => {
  6062. this.scaleItem = -1
  6063. })
  6064. })
  6065. ) //拖动List关键代码结束
  6066. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  6067. // }
  6068. }
  6069. .onScrollStart(() => {
  6070. this.isScrolling = true
  6071. this.isShowAlphaBet = true
  6072. })
  6073. .onScrollIndex((start: number,center:number,end:number) => {
  6074. this.selectedIndex = start
  6075. if(start >= 0 && start < this.videoLocalList.length){
  6076. this.selectAlphaBetIndex = this.findAlphaBetIndex(this.videoLocalList[start])
  6077. }
  6078. })
  6079. .onScrollStop(() => {
  6080. if(this.isScrolling){
  6081. this.isScrolling = false
  6082. }
  6083. this.isShowAlphaBet = false
  6084. })
  6085. .scrollBar(BarState.Off)
  6086. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  6087. .gesture(PinchGesture({ fingers: 2 })
  6088. .onActionEnd((event: GestureEvent) => {
  6089. this.setlistTwoFingers()
  6090. })
  6091. .onActionUpdate(e => {
  6092. this.scaleValue = this.pinchValue * e.scale
  6093. })
  6094. .onActionStart(e => {
  6095. }))
  6096. .contentStartOffset(this.topSafeHeight + 55)
  6097. .scrollBar(BarState.Off)
  6098. .contentEndOffset(this.bottomBarHeight+this.bottomSafeHeight)
  6099. .cachedCount(10)
  6100. // .reuseId('list_item')
  6101. .borderRadius(20)
  6102. .layoutWeight(1)
  6103. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  6104. .lanes(
  6105. new BreakpointType<number>({
  6106. sm: 1,
  6107. md: 2,
  6108. lg: 2,
  6109. xl: 3,
  6110. xxl: 4
  6111. }).getValue(this.currentBreakpoint),
  6112. new BreakpointType<number>({
  6113. sm: 0,
  6114. md: 12,
  6115. lg: 12,
  6116. xl: 16,
  6117. xxl: 20
  6118. }).getValue(this.currentBreakpoint)
  6119. )
  6120. .onAreaChange((oldValue: Area, newValue: Area) => {
  6121. this.listArea = newValue
  6122. if (this.twoFingerType == 3) {
  6123. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  6124. } else if (this.twoFingerType == 2) {
  6125. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  6126. } else if (this.twoFingerType == 1) {
  6127. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  6128. }
  6129. })
  6130. .onScrollFrameBegin((offset: number) => {
  6131. // 获取当前滚动偏移量
  6132. if(this.autoHideTitle){
  6133. const currentOffsetY = this.listScroller.currentOffset().yOffset;
  6134. // 判断滚动方向
  6135. if (currentOffsetY > this.prevOffsetY) {
  6136. // console.log("onecold 向上滚动");
  6137. this.isShowTitleBar = false
  6138. } else if (currentOffsetY < this.prevOffsetY) {
  6139. // console.log("onecold 向下滚动");
  6140. this.isShowTitleBar = true
  6141. }
  6142. // 更新前一次偏移量
  6143. this.prevOffsetY = currentOffsetY;
  6144. }
  6145. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  6146. // if (this.isPhoneLan()) {
  6147. // this.setBarHeightHide(offset)
  6148. // } else
  6149. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  6150. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  6151. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  6152. if (this.isScrollHide) {
  6153. this.setBarHeightHide2(offset)
  6154. } else {
  6155. this.setBarHeightNormal()
  6156. }
  6157. } else {
  6158. this.setBarHeightHide(offset)
  6159. }
  6160. return { offsetRemain: offset };
  6161. })
  6162. }
  6163. setBarHeightNormal() {
  6164. this.hideDone = false;
  6165. this.getUIContext().animateTo({
  6166. duration: 300
  6167. }, () => {
  6168. this.bottomBarHeight = 68 + 0;
  6169. this.topBarHeight = 50 + 0;
  6170. this.barOpacity = 1;
  6171. this.barBottomOpacity = 1
  6172. this.currentYOffset = 0;
  6173. this.isHiding = false;
  6174. });
  6175. }
  6176. setBarHeightHide(offset: number) {
  6177. if (offset > 0 && !this.hideDone) {
  6178. this.currentYOffset += offset;
  6179. if (this.currentYOffset <= 100) {
  6180. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  6181. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  6182. this.barOpacity = 1 - this.currentYOffset / 100;
  6183. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  6184. } else {
  6185. this.topBarHeight = 0;
  6186. this.bottomBarHeight = 0;
  6187. this.barBottomOpacity = 0
  6188. this.barOpacity = 0;
  6189. this.hideDone = true;
  6190. }
  6191. this.isHiding = true;
  6192. }
  6193. if (offset < 0 && this.isHiding) {
  6194. this.hideDone = false;
  6195. this.getUIContext().animateTo({
  6196. duration: 300
  6197. }, () => {
  6198. this.bottomBarHeight = 68 + 0;
  6199. this.topBarHeight = 50 + 0;
  6200. this.barOpacity = 1;
  6201. this.barBottomOpacity = 1
  6202. this.currentYOffset = 0;
  6203. this.isHiding = false;
  6204. });
  6205. }
  6206. }
  6207. //这个方法没隐藏bottomBar,只隐藏topbar
  6208. setBarHeightHide2(offset: number) {
  6209. if (offset > 0 && !this.hideDone) {
  6210. this.currentYOffset += offset;
  6211. if (this.currentYOffset <= 100) {
  6212. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  6213. this.barOpacity = 1 - this.currentYOffset / 100;
  6214. } else {
  6215. this.topBarHeight = 0;
  6216. this.barOpacity = 0;
  6217. this.hideDone = true;
  6218. }
  6219. this.isHiding = true;
  6220. }
  6221. if (offset < 0 && this.isHiding) {
  6222. this.hideDone = false;
  6223. this.getUIContext().animateTo({
  6224. duration: 300
  6225. }, () => {
  6226. this.topBarHeight = 50 + 0;
  6227. this.barOpacity = 1;
  6228. this.currentYOffset = 0;
  6229. this.isHiding = false;
  6230. });
  6231. }
  6232. }
  6233. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  6234. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  6235. switch (item.type) {
  6236. case CommonConstants.TYPE_IS_DIR:
  6237. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  6238. let offsetB = 0
  6239. if(this.twoFingerType==4){
  6240. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6241. let cur = this.waterScroller.currentOffset()
  6242. if (cur && typeof cur.yOffset === 'number') {
  6243. offsetB = cur.yOffset
  6244. }
  6245. }
  6246. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  6247. }else
  6248. if (this.isGridMusic) {
  6249. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6250. let cur = this.scroller.currentOffset()
  6251. if (cur && typeof cur.yOffset === 'number') {
  6252. offsetB = cur.yOffset
  6253. }
  6254. }
  6255. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  6256. } else {
  6257. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6258. let cur = this.listScroller.currentOffset()
  6259. if (cur && typeof cur.yOffset === 'number') {
  6260. offsetB = cur.yOffset
  6261. }
  6262. }
  6263. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  6264. }
  6265. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  6266. this.showVerifyDialog()
  6267. this.currentTitleName = '私密音频'
  6268. this.currentTitleCover = $r('app.media.alt')
  6269. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  6270. this.titleName = '最近播放'
  6271. this.currentTitleCover = $r('app.media.alt')
  6272. this.currentTitleName = '最近播放'
  6273. //加载动画效果
  6274. this.updateListData(this.historyList, true)
  6275. // this.videoLocalList = this.historyList
  6276. if (ArrayUtil.isEmpty(this.historyList)) {
  6277. ToastUtil.showToast('最近播放记录空空如也')
  6278. } else {
  6279. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  6280. }
  6281. this.isHistory = true
  6282. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  6283. this.titleName = '我的收藏'
  6284. this.currentTitleName = '我的收藏'
  6285. this.currentTitleCover = $r('app.media.alt')
  6286. //加载动画效果
  6287. this.updateListData(this.favList)
  6288. if (ArrayUtil.isEmpty(this.favList)) {
  6289. ToastUtil.showToast('无音乐收藏记录')
  6290. } else {
  6291. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  6292. }
  6293. this.isFavMusic = true
  6294. } else {
  6295. this.currentTitleName = item.name
  6296. this.currentPath = item.filePath
  6297. this.currentTitleCover = $r('app.media.alt')
  6298. this.getSortedFiles(this.currentPath)
  6299. }
  6300. //进入歌单的时候的滚动位置在顶部
  6301. if(this.twoFingerType==4){
  6302. setTimeout(() => {
  6303. this.waterScroller.scrollEdge(Edge.Top)
  6304. this.scroller.scrollEdge(Edge.Top)
  6305. }, 380)
  6306. }else{
  6307. if (this.isGridMusic) {
  6308. this.scroller.scrollEdge(Edge.Top)
  6309. }else{
  6310. this.listScroller.scrollEdge(Edge.Top)
  6311. }
  6312. }
  6313. this.rightTopImage = $r('sys.symbol.chevron_left')
  6314. break;
  6315. case CommonConstants.TYPE_IS_ARTIST:
  6316. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  6317. let offsetA = 0
  6318. if(this.twoFingerType==4){
  6319. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6320. let cur = this.waterScroller.currentOffset()
  6321. if (cur && typeof cur.yOffset === 'number') {
  6322. offsetA = cur.yOffset
  6323. }
  6324. }
  6325. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  6326. }else
  6327. if (this.isGridMusic) {
  6328. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6329. let cur = this.scroller.currentOffset()
  6330. if (cur && typeof cur.yOffset === 'number') {
  6331. offsetA = cur.yOffset
  6332. }
  6333. }
  6334. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  6335. } else {
  6336. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6337. let cur = this.listScroller.currentOffset()
  6338. if (cur && typeof cur.yOffset === 'number') {
  6339. offsetA = cur.yOffset
  6340. }
  6341. }
  6342. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  6343. }
  6344. let mList = this.artistMap.get(item.name)
  6345. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  6346. Utility.doSortListAscending(mList)
  6347. this.isCanBack = true
  6348. this.titleName = item.name
  6349. this.currentTitleName = '艺术家:' + item.name
  6350. if (item.pixelMapPath) {
  6351. this.currentTitleCover = item.pixelMapPath
  6352. }
  6353. this.updateListData(mList)
  6354. }
  6355. this.rightTopImage = $r('sys.symbol.chevron_left')
  6356. //进入歌单的时候的滚动位置在顶部
  6357. if(this.twoFingerType==4){
  6358. setTimeout(() => {
  6359. this.waterScroller.scrollEdge(Edge.Top)
  6360. this.scroller.scrollEdge(Edge.Top)
  6361. }, 380)
  6362. }else{
  6363. if (this.isGridMusic) {
  6364. this.scroller.scrollEdge(Edge.Top)
  6365. }else{
  6366. this.listScroller.scrollEdge(Edge.Top)
  6367. }
  6368. }
  6369. break;
  6370. case CommonConstants.TYPE_IS_ALBUM:
  6371. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  6372. let offset = 0
  6373. if(this.twoFingerType==4){
  6374. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6375. let cur = this.waterScroller.currentOffset()
  6376. if (cur && typeof cur.yOffset === 'number') {
  6377. offset = cur.yOffset
  6378. }
  6379. }
  6380. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  6381. }else
  6382. if (this.isGridMusic) {
  6383. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6384. let cur = this.scroller.currentOffset()
  6385. if (cur && typeof cur.yOffset === 'number') {
  6386. offset = cur.yOffset
  6387. }
  6388. }
  6389. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  6390. } else {
  6391. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6392. let cur = this.listScroller.currentOffset()
  6393. if (cur && typeof cur.yOffset === 'number') {
  6394. offset = cur.yOffset
  6395. }
  6396. }
  6397. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  6398. }
  6399. let albumList = this.albumMap.get(item.name)
  6400. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  6401. Utility.doSortListAscending(albumList)
  6402. this.isCanBack = true
  6403. this.titleName = item.name
  6404. this.currentTitleName = '专辑:' + item.name
  6405. if (item.pixelMapPath) {
  6406. this.currentTitleCover = item.pixelMapPath
  6407. }
  6408. this.updateListData(albumList)
  6409. this.mScrollMap.set(item.name, this.selectedIndex)
  6410. this.rightTopImage = $r('sys.symbol.chevron_left')
  6411. }
  6412. //进入歌单的时候的滚动位置在顶部
  6413. if(this.twoFingerType==4){
  6414. setTimeout(() => {
  6415. this.waterScroller.scrollEdge(Edge.Top)
  6416. this.scroller.scrollEdge(Edge.Top)
  6417. }, 380)
  6418. }else{
  6419. if (this.isGridMusic) {
  6420. this.scroller.scrollEdge(Edge.Top)
  6421. }else{
  6422. this.listScroller.scrollEdge(Edge.Top)
  6423. }
  6424. }
  6425. break;
  6426. case CommonConstants.TYPE_IS_CSJAD:
  6427. return
  6428. break;
  6429. case CommonConstants.TYPE_LOCAL:
  6430. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  6431. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  6432. const cueTracks:CueTrack[] = cueinfo.tracks
  6433. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  6434. if(ArrayUtil.isNotEmpty(cueTracks)){
  6435. this.showCueDialog(cueTracks,cueinfo)
  6436. }
  6437. // this.showCueSheet = !this.showCueSheet
  6438. return
  6439. }
  6440. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6441. this.stop();
  6442. }
  6443. if (isOpen) {
  6444. this.currentSong = item
  6445. if (index !== undefined) {
  6446. this.curIndex = index
  6447. }
  6448. this.songList = []
  6449. this.songList.push(item)
  6450. this.sonDataSource.pushArrayData(this.songList)
  6451. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  6452. this.currentSong = item
  6453. if (index !== undefined) {
  6454. this.curIndex = index
  6455. }
  6456. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  6457. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  6458. }else {
  6459. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  6460. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  6461. this.songList = globalVideoList
  6462. this.sonDataSource.pushArrayData(this.songList)
  6463. this.currentSong = globalVideoList[this.curIndex]
  6464. }
  6465. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  6466. this.videoUrl = this.currentSong.filePath
  6467. this.name = this.currentSong.name
  6468. this.cover = this.currentSong.pixelMapPath
  6469. this.artist = this.currentSong.artist
  6470. LogUtil.info('onecold this.currentSong.cover =' + this.currentSong.pixelMapPath)
  6471. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  6472. this.startPlayOrResumePlay()
  6473. break;
  6474. case CommonConstants.TYPE_WEBDAV:
  6475. case CommonConstants.TYPE_SMB:
  6476. case CommonConstants.TYPE_NAVIDROME:
  6477. case CommonConstants.TYPE_FTP:
  6478. case CommonConstants.TYPE_BAIDU:
  6479. // 处理网络音频播放(WebDAV/SMB)
  6480. Logger.info(`heanup 处理云端音频播放: ${item.name}, URL: ${item.filePath}`)
  6481. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6482. this.stop();
  6483. }
  6484. if (isOpen) {
  6485. this.currentSong = item
  6486. if (index !== undefined) {
  6487. this.curIndex = index
  6488. }
  6489. this.songList = []
  6490. this.songList.push(item)
  6491. this.sonDataSource.pushArrayData(this.songList)
  6492. } else if (isFromSonPlayList) {
  6493. // 点击来自右下角的播放列表
  6494. this.currentSong = item
  6495. if (index !== undefined) {
  6496. this.curIndex = index
  6497. }
  6498. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  6499. Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  6500. } else {
  6501. // 从全局网络音频列表中查找
  6502. let globalVideoList = this.videoLocalList.filter(video => isRemoteCloudType(video.type)) as VideoItem[];
  6503. this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
  6504. if (this.curIndex === -1 && index !== undefined) {
  6505. this.curIndex = index;
  6506. }
  6507. this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
  6508. this.currentSong = this.songList[this.curIndex];
  6509. this.sonDataSource.pushArrayData(this.songList)
  6510. }
  6511. await this.hydrateRemoteSongFromDb(this.currentSong);
  6512. await this.hydrateRemoteSongFromDb(this.currentSong);
  6513. AppStorage.setOrCreate('currentSong', this.currentSong);
  6514. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  6515. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  6516. context: this.context,
  6517. autoParseMusicName: this.autoParseMusicName
  6518. });
  6519. Logger.info(TAG, `WebDAV URL同步构建完成(分支2): ${this.videoUrl}`);
  6520. this.name = this.currentSong.name
  6521. this.cover = this.currentSong.pixelMapPath
  6522. this.artist = this.currentSong.artist
  6523. Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 完整URL: ${this.videoUrl}`)
  6524. this.startPlayOrResumePlay()
  6525. break;
  6526. }
  6527. }
  6528. private cueComponentId: number = 0
  6529. //显示cue分轨列表对话框
  6530. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  6531. this.getUIContext().getPromptAction().openCustomDialog({
  6532. builder: () => {
  6533. this.cueComptentBuilder(cueTracks,cueinfo)
  6534. },
  6535. isModal:true,
  6536. showInSubWindow:false,
  6537. maskColor: Color.Transparent,
  6538. dialogTransition: // 设置弹窗内容显示的过渡效果
  6539. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  6540. .animation({ duration: 600, curve: Curve.Smooth }),
  6541. maskTransition: // 设置蒙层显示的过渡效果
  6542. TransitionEffect.opacity(0.5)
  6543. .animation({ duration: 600, curve: Curve.Smooth })
  6544. }).then((dialogId: number) => {
  6545. this.cueComponentId = dialogId
  6546. })
  6547. .catch((error: BusinessError) => {
  6548. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  6549. })
  6550. }
  6551. @Builder
  6552. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  6553. CueComptent({
  6554. title:cueinfo.title,
  6555. cueTracks:cueTracks,
  6556. isLongNameRoLL:this.isLongNameRoLL,
  6557. onCancel:()=>{
  6558. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  6559. },
  6560. onDoItemClick: async (item: CueTrack, index: number)=>{
  6561. //获取cueinfo对应的filePath
  6562. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  6563. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  6564. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  6565. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  6566. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  6567. if (this.currentSong){
  6568. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6569. this.stop();//播放之前先停止之前播放。
  6570. }
  6571. this.songList = globalVideoList
  6572. this.sonDataSource.pushArrayData(this.songList)
  6573. if (this.currentSong) {
  6574. try {
  6575. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  6576. context: this.context,
  6577. autoParseMusicName: this.autoParseMusicName
  6578. });
  6579. } catch (error) {
  6580. Logger.error(TAG, `CUE 点播构建播放地址失败: ${(error as Error).message}`);
  6581. this.videoUrl = this.currentSong.filePath;
  6582. }
  6583. }
  6584. this.name = item.title||this.currentSong.name
  6585. this.cover = this.currentSong.pixelMapPath
  6586. this.artist = item.performer||this.currentSong.artist
  6587. this.currentSong.name = this.name
  6588. this.currentSong.artist = this.artist
  6589. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  6590. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  6591. }
  6592. }
  6593. })
  6594. }
  6595. @State isFrontWhite: boolean = false
  6596. setShowPlayTrue(){
  6597. this.getUIContext()?.animateTo({
  6598. duration: 500,
  6599. curve: Curve.Friction
  6600. }, () => {
  6601. this.isShowPlay = true;
  6602. });
  6603. }
  6604. setShowPlayFalse(){
  6605. this.getUIContext()?.animateTo({
  6606. duration: 500,
  6607. curve: Curve.Friction
  6608. }, () => {
  6609. this.isShowPlay = false;
  6610. });
  6611. }
  6612. //打开播放页
  6613. showPlayerView() {
  6614. console.info('onecold showPlayerView this.songList'+ JSON.stringify(this.songList))
  6615. if (ArrayUtil.isNotEmpty(this.songList)) {
  6616. // this.setShowPlayTrue()
  6617. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  6618. this.initLyric(lyricPath);
  6619. this.startAutoHide();
  6620. } else {
  6621. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  6622. }
  6623. }
  6624. //打开播放列表
  6625. openPlayList(){
  6626. if (ArrayUtil.isNotEmpty(this.songList)) {
  6627. this.isShowSheet = !this.isShowSheet;
  6628. this.isFrontWhite = false
  6629. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  6630. this.scrollIndex()
  6631. } else {
  6632. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6633. }
  6634. }
  6635. scrollIndex(){
  6636. try {
  6637. setTimeout(() => {
  6638. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  6639. if(this.curIndex>60){
  6640. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  6641. }else{
  6642. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  6643. }
  6644. })
  6645. }, 123)
  6646. }catch (error) {
  6647. console.error(`onecold scrollIndex出错: ${error}`);
  6648. }
  6649. }
  6650. //播放列表布局
  6651. @Builder
  6652. PlayListSheet() {
  6653. Column() {
  6654. this.PlayList()
  6655. }
  6656. .width('100%')
  6657. .height('100%')
  6658. }
  6659. @State titleStr: string = ''
  6660. @State ablumStr: string = ''
  6661. @State artistStr: string = ''
  6662. @State lyricConStr: string = ''
  6663. @State currentEditItem: string = ''
  6664. @State yearStr: string = ''
  6665. @State trackStr: string = ''
  6666. @State genreStr: string = ''
  6667. @State imagePathStr: string = ''
  6668. @State albumArtistStr: string = ''
  6669. @State composerStr: string = ''
  6670. @State lyricistStr: string = ''
  6671. @State commentStr: string = ''
  6672. @State discStr: string = ''
  6673. doUpdateData() {
  6674. setTimeout(() => {
  6675. if (this.modeType === 0) {
  6676. this.deleteCache(this.currentPath)
  6677. this.getSortedFiles(this.currentPath)
  6678. }else if (this.modeType === 1){
  6679. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6680. }
  6681. }, 500)
  6682. }
  6683. doAllUpdateData() {
  6684. setTimeout(() => {
  6685. if (this.modeType === 0) {
  6686. this.deleteCache(this.currentPath)
  6687. this.getSortedFiles(this.currentPath)
  6688. }
  6689. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6690. workerInstance.postMessage({ code: 3, data: this.context });
  6691. workerInstance.postMessage({ code: 4, data: this.context });
  6692. }, 999)
  6693. }
  6694. //编辑信息
  6695. async doEdit(item: VideoItem) {
  6696. if (!item) {
  6697. return
  6698. }
  6699. if (StrUtil.isEmpty(this.titleStr)) {
  6700. ToastUtil.showToast('标题不能为空')
  6701. return
  6702. }
  6703. //内嵌音乐标签不能开启监听
  6704. // this.deletionWatcher?.stop();
  6705. DialogHelper.showLoadingDialog()
  6706. await PermissionUtil.activatePermission(item.filePath)
  6707. let tempOutPath = ''
  6708. // 如果不是 packName 包下的文件,则直接路径用this.currentPath
  6709. if(!item.filePath.toLowerCase().includes(this.packName)){
  6710. tempOutPath = this.currentPath + '/' + item.fileName
  6711. }
  6712. console.info('onecold tempOutPath ='+tempOutPath)
  6713. //用户更改了封面,那就内嵌下封面
  6714. if(StrUtil.isNotEmpty(this.imagePathStr)){
  6715. const resultCover:boolean = await changeMusicCover(this.context,
  6716. item.filePath,this.imagePathStr,true,tempOutPath);
  6717. this.imagePathStr = ''
  6718. if(resultCover){
  6719. ToastUtil.showToast('内嵌封面成功')
  6720. }
  6721. }
  6722. const metadata:FFMpegTags = {
  6723. title: this.titleStr,
  6724. artist: this.artistStr,
  6725. album: this.ablumStr,
  6726. TYER:this.yearStr,
  6727. genre:this.genreStr,
  6728. track:this.trackStr,
  6729. album_artist:this.albumArtistStr,
  6730. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  6731. COMPOSER:this.composerStr,
  6732. lyricist:this.lyricistStr,
  6733. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  6734. comment:this.commentStr,
  6735. disc:this.discStr,
  6736. };
  6737. let newInput = item.filePath
  6738. //内嵌标签歌路径如果不是包含包名,输入newInput要赋值tempOutPath,然后tempOutPath为空
  6739. if(!item.filePath.toLowerCase().includes(this.packName)&&FileUtil.accessSync(tempOutPath)){
  6740. newInput = tempOutPath
  6741. tempOutPath = ''
  6742. }
  6743. const isWav:boolean = newInput.toLowerCase().endsWith('.wav');
  6744. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  6745. const result:boolean = await repairAudioMetadata(
  6746. newInput,
  6747. this.lyricConStr,
  6748. metadata,
  6749. true,
  6750. tempOutPath
  6751. );
  6752. if (result||isWav) {
  6753. if(!item.filePath.includes(this.packName)){
  6754. //内嵌成功的歌路径如果不是包含包名,则要入库
  6755. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newInput,
  6756. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  6757. this.table.insert(newItem, (id: number) => {
  6758. //加入数据库
  6759. if(this.modeType==0){
  6760. this.deleteCache(this.currentPath)
  6761. this.getSortedFiles(this.currentPath)
  6762. }
  6763. });
  6764. }
  6765. const task = new taskpool.Task(
  6766. updateInfoDb,
  6767. this.context,
  6768. item.filePath,
  6769. this.titleStr,
  6770. this.artistStr,
  6771. this.ablumStr,
  6772. this.lyricConStr,
  6773. this.yearStr,this.genreStr,
  6774. this.trackStr,this.albumArtistStr,
  6775. this.composerStr, this.lyricistStr,
  6776. this.commentStr,this.discStr
  6777. );
  6778. taskpool.execute(task, taskpool.Priority.HIGH).then((result) => {
  6779. if (result) {
  6780. console.log(" onecold 编辑信息成功,数据库已同步");
  6781. if(isWav){
  6782. ToastUtil.showToast('wav格式有可能内嵌失败,但是编辑信息成功')
  6783. }else{
  6784. ToastUtil.showToast('内嵌音乐标签成功')
  6785. }
  6786. this.isShowMoreView = false
  6787. this.name = this.titleStr
  6788. this.syncEditedFields(item)
  6789. if (item.filePath == this.currentSong?.filePath) {
  6790. this.currentSong.name = this.titleStr
  6791. this.artist = this.artistStr
  6792. this.currentSong.artist = this.artistStr
  6793. this.currentSong.album = this.ablumStr
  6794. this.currentSong.year = this.yearStr
  6795. this.currentSong.genre = this.genreStr
  6796. this.currentSong.track = this.trackStr
  6797. this.currentSong.lyricContent = this.lyricConStr
  6798. this.currentSong.ALBUMARTIST = this.albumArtistStr
  6799. this.currentSong.COMPOSER = this.composerStr
  6800. this.currentSong.LYRICIST = this.lyricistStr
  6801. this.currentSong.COMMENT = this.commentStr
  6802. }
  6803. this.syncListsAfterEdit(item.filePath)
  6804. this.doUpateEditedFields(item)
  6805. //this.doUpdateData()
  6806. } else {
  6807. // ToastUtil.showToast('保存失败' + error?.toString())
  6808. console.error(" onecold 编辑信息数据库失败 ");
  6809. }
  6810. // 关闭进度条
  6811. DialogHelper.closeLoading();
  6812. }).catch((error: Error) => {
  6813. // 关闭进度条
  6814. DialogHelper.closeLoading();
  6815. console.error('onecold Subtitle sync failed:', error);
  6816. });
  6817. console.log(' onecold 元数据标签更新成功,');
  6818. } else {
  6819. // 关闭进度条
  6820. DialogHelper.closeLoading();
  6821. ToastUtil.showToast('内嵌音乐标签失败')
  6822. console.log('onecold 内嵌音乐标签失败');
  6823. }
  6824. this.longItemFilePath = ''
  6825. this.tempLyricContent = ''
  6826. this.isShowEdit = false
  6827. }
  6828. // 内嵌标签更新当前内嵌的Item
  6829. async doUpateEditedFields(item: VideoItem) {
  6830. // 找到当前项在 videoLocalList 中的索引
  6831. const index = this.videoLocalList.findIndex(video => video.filePath === item.filePath);
  6832. if (index !== -1) {
  6833. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  6834. const updatedItem = await this.table.queryVideoByFilePath(item.filePath)
  6835. // 只有当查询结果不为 null 时才更新列表
  6836. if (updatedItem !== null) {
  6837. // 更新 videoLocalList 中的项(通过创建新数组触发响应式更新)
  6838. this.videoLocalList = [
  6839. ...this.videoLocalList.slice(0, index),
  6840. updatedItem,
  6841. ...this.videoLocalList.slice(index + 1)
  6842. ];
  6843. // 同步更新 LazyDataSource
  6844. this.dataSource.pushArrayData(this.videoLocalList)
  6845. } else {
  6846. ToastUtil.showToast('未找到更新的数据');
  6847. }
  6848. }
  6849. DialogHelper.closeLoading();
  6850. }
  6851. @Builder
  6852. editSheet(item: VideoItem) {
  6853. Scroll() {
  6854. Column() {
  6855. this.editDetail(item)
  6856. }
  6857. }
  6858. .width('100%')
  6859. .height('100%')
  6860. }
  6861. @Builder
  6862. editDetail(item: VideoItem) {
  6863. Column() {
  6864. if (item) {
  6865. Row() {
  6866. Stack() {
  6867. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  6868. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  6869. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  6870. item.pixelMapPath)
  6871. .fillColor(this.themeColor)
  6872. .height(88)
  6873. .width(88)
  6874. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  6875. .borderRadius(12)
  6876. .clip(true)
  6877. .opacity(this.opacityItem)// 绑定透明度
  6878. .margin({ left: 25 })
  6879. }
  6880. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  6881. .onClick(async () => {
  6882. const imagePath:string | undefined = await this.goSelectImage(item);
  6883. if (imagePath) {
  6884. //用户更改过图片
  6885. this.imagePathStr = imagePath
  6886. }
  6887. })
  6888. .width('28%')
  6889. Row() {
  6890. Column() {
  6891. Text(item.name)
  6892. .fontSize(17)
  6893. .maxLines(1)
  6894. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6895. .animation({
  6896. duration: 555,
  6897. curve: 'Linear',
  6898. })
  6899. .fontColor(this.themeColor)
  6900. .margin({ left: 8 })
  6901. Row() {
  6902. Text(item.artist)
  6903. .fontSize(14)
  6904. .maxLines(1)
  6905. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6906. .padding({ top: 8 })
  6907. .fontColor(this.themeColor)
  6908. .margin({ left: 8 })
  6909. }
  6910. }
  6911. .height('100%')
  6912. .width(100)
  6913. .layoutWeight(1)
  6914. .justifyContent(FlexAlign.Center)
  6915. .alignItems(HorizontalAlign.Start)
  6916. Column() {
  6917. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6918. Row(){
  6919. SymbolGlyph($r('sys.symbol.picture'))
  6920. .fontSize(18)
  6921. .fontColor([Color.White])
  6922. Text('获取封面')
  6923. .margin({ left: 4 })
  6924. .fontSize(11)
  6925. .fontColor(Color.White)
  6926. .fontWeight(480)
  6927. .textAlign(TextAlign.Center)
  6928. }
  6929. .justifyContent(FlexAlign.Center)
  6930. }
  6931. .height(38)
  6932. .width(100)
  6933. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6934. .backgroundColor(this.themeColor)
  6935. .stateEffect(true)
  6936. .margin({ right: 35 })
  6937. .onClick(async () => {
  6938. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  6939. this.showTipsDialog();
  6940. return; // Return empty string when no API is configured
  6941. }
  6942. const imagePath:string | undefined = await this.doSearchCover(item,
  6943. this.titleStr,this.artistStr);
  6944. console.info('onecold imagePath = '+imagePath)
  6945. if (StrUtil.isNotEmpty(imagePath)) {
  6946. //用户更改过图片
  6947. this.imagePathStr = imagePath
  6948. ToastUtil.showToast('获取封面成功')
  6949. }else{
  6950. ToastUtil.showToast('获取封面失败,请重试')
  6951. }
  6952. })
  6953. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6954. Row(){
  6955. SymbolGlyph($r('sys.symbol.input_mode'))
  6956. .fontSize(18)
  6957. .fontColor([Color.White])
  6958. Text('获取歌词')
  6959. .margin({ left: 4 })
  6960. .fontSize(11)
  6961. .fontColor(Color.White)
  6962. .fontWeight(480)
  6963. .textAlign(TextAlign.Center)
  6964. }
  6965. .justifyContent(FlexAlign.Center)
  6966. }
  6967. .height(38)
  6968. .width(100)
  6969. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6970. .backgroundColor(this.themeColor)
  6971. .stateEffect(true)
  6972. .margin({ top: 9, right: 35 })
  6973. .onClick(async () => {
  6974. //判断有没有设置api
  6975. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  6976. if (StrUtil.isEmpty(apiUrl)) {
  6977. this.isLyricSetting = false
  6978. this.showTipsDialog()
  6979. return
  6980. }
  6981. let res: string | undefined = await getApiLyric(apiUrl,
  6982. this.titleStr, this.artistStr, false);
  6983. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  6984. this.lyricConStr = res;
  6985. ToastUtil.showToast('获取歌词成功')
  6986. }else{
  6987. ToastUtil.showToast('获取歌词失败,请重试')
  6988. }
  6989. })
  6990. }
  6991. .justifyContent(FlexAlign.Start)
  6992. }
  6993. .height('100%')
  6994. .justifyContent(FlexAlign.Start)
  6995. .layoutWeight(1)
  6996. }
  6997. .width('100%')
  6998. .height(98)
  6999. Row() {
  7000. Text('标题:')
  7001. .fontSize(14)
  7002. .fontColor($r('app.color.text_color'))
  7003. .margin({ left: 22 })
  7004. TextInput({ text: this.titleStr||item.name })
  7005. .height(40)
  7006. .maxLines(1)
  7007. .fontSize(14)
  7008. .layoutWeight(1)
  7009. .fontColor($r('app.color.text_color'))
  7010. .margin({ right: 15, left: 10 })
  7011. .onChange((val: string) => {
  7012. this.titleStr = val
  7013. })
  7014. Button('修复乱码',{ type: ButtonType.Capsule, stateEffect: true})
  7015. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7016. .backgroundColor(this.themeColor)
  7017. .fontSize(10)
  7018. .margin({ right: 20})
  7019. .onClick(async () => {
  7020. let hwTags = await extractHwMediaMetadata(item.filePath)
  7021. let artist = hwTags?.artist|| '';
  7022. let title = hwTags?.title|| '';
  7023. let album = hwTags?.album|| '';
  7024. console.info('onecold 乱码修正 artist='+artist);
  7025. console.info('onecold 乱码修正 title='+title);
  7026. console.info('onecold 乱码修正 album='+album);
  7027. this.titleStr = title;
  7028. this.artistStr = artist;
  7029. this.ablumStr = album;
  7030. })
  7031. }
  7032. .width('100%')
  7033. .margin({ top: 10, bottom: 10 })
  7034. .justifyContent(FlexAlign.Start)
  7035. Row() {
  7036. Text('艺术家:')
  7037. .fontSize(14)
  7038. .fontColor($r('app.color.text_color'))
  7039. .margin({ left: 22 })
  7040. TextInput({ text: this.artistStr||item.artist })
  7041. .height(40)
  7042. .maxLines(1)
  7043. .fontSize(14)
  7044. .layoutWeight(1)
  7045. .fontColor($r('app.color.text_color'))
  7046. .margin({ right: 20, left: 10 })
  7047. .onChange((val: string) => {
  7048. this.artistStr = val
  7049. })
  7050. }
  7051. .width('100%')
  7052. .margin({ top: 10, bottom: 10 })
  7053. .justifyContent(FlexAlign.Start)
  7054. Row() {
  7055. Text('专辑名:')
  7056. .fontSize(14)
  7057. .fontColor($r('app.color.text_color'))
  7058. .margin({ left: 22 })
  7059. TextInput({ text: this.ablumStr||item.album })
  7060. .height(40)
  7061. .maxLines(1)
  7062. .fontSize(14)
  7063. .layoutWeight(1)
  7064. .fontColor($r('app.color.text_color'))
  7065. .margin({ right: 20, left: 10 })
  7066. .onChange((val: string) => {
  7067. this.ablumStr = val
  7068. })
  7069. }
  7070. .width('100%')
  7071. .margin({ top: 10, bottom: 10 })
  7072. .justifyContent(FlexAlign.Start)
  7073. Row() {
  7074. Column(){
  7075. Column(){
  7076. Text('歌词:')
  7077. .fontSize(14)
  7078. .fontColor($r('app.color.text_color'))
  7079. .margin({ top:9,left: 22 })
  7080. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7081. SymbolGlyph($r('sys.symbol.trash_fill'))
  7082. .fontSize(25)
  7083. .alignSelf(ItemAlign.Center)
  7084. .margin({ left: 22,top:25})
  7085. }
  7086. .backgroundColor(Color.Transparent)
  7087. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7088. Visibility.None:Visibility.Visible)
  7089. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7090. .onClick(()=>{
  7091. this.lyricConStr = ''
  7092. this.lyricContent = ''
  7093. this.tempLyricContent = ''
  7094. })
  7095. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7096. SymbolGlyph($r('sys.symbol.plus'))
  7097. .fontSize(25)
  7098. .alignSelf(ItemAlign.Center)
  7099. .margin({ left: 22,top:25})
  7100. }
  7101. .backgroundColor(Color.Transparent)
  7102. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7103. .onClick( ()=>{
  7104. this.callFilePickerSelectFileForLyric()
  7105. })
  7106. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7107. SymbolGlyph($r('sys.symbol.traditional_square'))
  7108. .fontSize(25)
  7109. .alignSelf(ItemAlign.Center)
  7110. .margin({ left: 22,top:25})
  7111. }
  7112. .backgroundColor(Color.Transparent)
  7113. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7114. Visibility.None:Visibility.Visible)
  7115. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7116. .onClick( ()=>{
  7117. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  7118. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  7119. })
  7120. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7121. Image($r('app.media.jianti'))
  7122. .height(25)
  7123. .fillColor($r('app.color.text_color'))
  7124. .alignSelf(ItemAlign.Center)
  7125. .margin({ left: 22,top:25})
  7126. }
  7127. .backgroundColor(Color.Transparent)
  7128. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7129. Visibility.None:Visibility.Visible)
  7130. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7131. .onClick( ()=>{
  7132. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  7133. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  7134. })
  7135. }
  7136. .layoutWeight(1)
  7137. }
  7138. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  7139. this.tempLyricContent })
  7140. .type(TextAreaType.NORMAL)
  7141. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  7142. .fontSize(14)
  7143. .layoutWeight(1)
  7144. .fontColor($r('app.color.text_color'))
  7145. .margin({ right: 20, left: 10 })
  7146. .onChange((val: string) => {
  7147. this.lyricConStr = val
  7148. })
  7149. }
  7150. .width('100%')
  7151. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  7152. .margin({ top: 10, bottom: 10 })
  7153. .justifyContent(FlexAlign.Start)
  7154. Row() {
  7155. Text('年份:')
  7156. .fontSize(14)
  7157. .fontColor($r('app.color.text_color'))
  7158. .margin({ left: 22 })
  7159. TextInput({ text: item.year })
  7160. .height(40)
  7161. .maxLines(1)
  7162. .fontSize(14)
  7163. .type(InputType.Number)
  7164. .layoutWeight(1)
  7165. .fontColor($r('app.color.text_color'))
  7166. .margin({ right: 20, left: 10 })
  7167. .onChange((val: string) => {
  7168. this.yearStr = val
  7169. })
  7170. }
  7171. .width('100%')
  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.track=='未知'?'': item.track })
  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.trackStr = 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.disc })
  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.discStr = 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.genre })
  7220. .height(40)
  7221. .maxLines(1)
  7222. .fontSize(14)
  7223. .layoutWeight(1)
  7224. .fontColor($r('app.color.text_color'))
  7225. .margin({ right: 20, left: 10 })
  7226. .onChange((val: string) => {
  7227. this.genreStr = val
  7228. })
  7229. }
  7230. .width('100%')
  7231. .margin({ top: 10, bottom: 10 })
  7232. .justifyContent(FlexAlign.Start)
  7233. Row() {
  7234. Text('专辑艺术家:')
  7235. .fontSize(14)
  7236. .fontColor($r('app.color.text_color'))
  7237. .margin({ left: 22 })
  7238. TextInput({ text: item.ALBUMARTIST })
  7239. .height(40)
  7240. .maxLines(1)
  7241. .fontSize(14)
  7242. .layoutWeight(1)
  7243. .fontColor($r('app.color.text_color'))
  7244. .margin({ right: 20, left: 10 })
  7245. .onChange((val: string) => {
  7246. this.albumArtistStr = val
  7247. })
  7248. }
  7249. .width('100%')
  7250. .margin({ top: 10, bottom: 10 })
  7251. .justifyContent(FlexAlign.Start)
  7252. Row() {
  7253. Text('作曲:')
  7254. .fontSize(14)
  7255. .fontColor($r('app.color.text_color'))
  7256. .margin({ left: 22 })
  7257. TextInput({ text: item.COMPOSER })
  7258. .height(40)
  7259. .maxLines(1)
  7260. .fontSize(14)
  7261. .layoutWeight(1)
  7262. .fontColor($r('app.color.text_color'))
  7263. .margin({ right: 20, left: 10 })
  7264. .onChange((val: string) => {
  7265. this.composerStr = val
  7266. })
  7267. }
  7268. .width('100%')
  7269. .margin({ top: 10, bottom: 10 })
  7270. .justifyContent(FlexAlign.Start)
  7271. Row() {
  7272. Text('作词:')
  7273. .fontSize(14)
  7274. .fontColor($r('app.color.text_color'))
  7275. .margin({ left: 22 })
  7276. TextInput({ text: item.LYRICIST })
  7277. .height(40)
  7278. .maxLines(1)
  7279. .fontSize(14)
  7280. .layoutWeight(1)
  7281. .fontColor($r('app.color.text_color'))
  7282. .margin({ right: 20, left: 10 })
  7283. .onChange((val: string) => {
  7284. this.lyricistStr = val
  7285. })
  7286. }
  7287. .width('100%')
  7288. .margin({ top: 10, bottom: 10 })
  7289. .justifyContent(FlexAlign.Start)
  7290. Row() {
  7291. Text('注释:')
  7292. .fontSize(14)
  7293. .fontColor($r('app.color.text_color'))
  7294. .margin({ left: 22 })
  7295. TextInput({ text: item.COMMENT })
  7296. .height(40)
  7297. .maxLines(1)
  7298. .fontSize(14)
  7299. .layoutWeight(1)
  7300. .fontColor($r('app.color.text_color'))
  7301. .margin({ right: 20, left: 10 })
  7302. .onChange((val: string) => {
  7303. this.commentStr = val
  7304. })
  7305. }
  7306. .width('100%')
  7307. .margin({ top: 10, bottom: 10 })
  7308. .justifyContent(FlexAlign.Start)
  7309. Row() {
  7310. Button('保存')
  7311. .fontColor(Color.White)
  7312. .layoutWeight(1)
  7313. .height(50)
  7314. .width(100)
  7315. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7316. .backgroundColor(this.themeColor)
  7317. .stateEffect(true)
  7318. .margin({ right: 20, bottom: 20 })
  7319. .onClick(async () => {
  7320. this.doEdit(item)
  7321. })
  7322. Button('取消')
  7323. .fontColor(Color.White)
  7324. .layoutWeight(1)
  7325. .height(50)
  7326. .width(100)
  7327. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7328. .backgroundColor(this.themeColor)
  7329. .stateEffect(true)
  7330. .margin({ left: 20, bottom: 20 })
  7331. .onClick(async () => {
  7332. if(this.isGridMusic){
  7333. this.longItemFilePath =''
  7334. }else{
  7335. this.isShowEdit = false
  7336. }
  7337. this.setEditStrEmpty()
  7338. if(this.isShowPlay){
  7339. this.isShowEdit = false
  7340. }
  7341. })
  7342. }
  7343. .margin({
  7344. left: 38,
  7345. right: 38,
  7346. top: 10,
  7347. bottom: 10
  7348. })
  7349. .width(250)
  7350. .height(60)
  7351. }
  7352. }
  7353. .margin({ bottom: 20 })
  7354. }
  7355. setEditStrEmpty(){
  7356. this.imagePathStr = ''
  7357. this.lyricConStr = ''
  7358. this.artistStr = ''
  7359. this.titleStr = ''
  7360. this.ablumStr = ''
  7361. this.genreStr = ''
  7362. this.yearStr = ''
  7363. this.trackStr = ''
  7364. this.albumArtistStr = ''
  7365. this.composerStr = ''
  7366. this.lyricistStr = ''
  7367. this.commentStr = ''
  7368. this.discStr = ''
  7369. }
  7370. initEditFields(item?: VideoItem) {
  7371. if (!item) {
  7372. this.setEditStrEmpty()
  7373. return
  7374. }
  7375. this.imagePathStr = ''
  7376. this.titleStr = item.name ?? ''
  7377. this.artistStr = item.artist ?? ''
  7378. this.ablumStr = item.album ?? ''
  7379. this.genreStr = item.genre ?? ''
  7380. this.yearStr = item.year ?? ''
  7381. this.trackStr = item.track ?? ''
  7382. this.albumArtistStr = item.ALBUMARTIST ?? ''
  7383. this.composerStr = item.COMPOSER ?? ''
  7384. this.lyricistStr = item.LYRICIST ?? ''
  7385. this.commentStr = item.COMMENT ?? ''
  7386. this.discStr = item.disc ?? ''
  7387. this.lyricConStr = item.lyricContent ?? ''
  7388. }
  7389. private syncEditedFields(target?: VideoItem) {
  7390. if (!target) {
  7391. return
  7392. }
  7393. target.name = this.titleStr
  7394. target.artist = this.artistStr
  7395. target.album = this.ablumStr
  7396. target.lyricContent = this.lyricConStr
  7397. target.year = this.yearStr
  7398. target.genre = this.genreStr
  7399. target.track = this.trackStr
  7400. target.ALBUMARTIST = this.albumArtistStr
  7401. target.COMPOSER = this.composerStr
  7402. target.LYRICIST = this.lyricistStr
  7403. target.COMMENT = this.commentStr
  7404. target.disc = this.discStr
  7405. }
  7406. private replaceItemInList(list: Array<VideoItem> | undefined, filePath: string,
  7407. apply?: (next: Array<VideoItem>) => void) {
  7408. if (!list || ArrayUtil.isEmpty(list)) {
  7409. return
  7410. }
  7411. const index = list.findIndex((video: VideoItem) => video.filePath === filePath)
  7412. if (index < 0) {
  7413. return
  7414. }
  7415. const nextList = [...list]
  7416. this.syncEditedFields(nextList[index])
  7417. apply?.(nextList)
  7418. }
  7419. private syncListsAfterEdit(filePath: string) {
  7420. this.replaceItemInList(this.videoLocalList, filePath, (next: Array<VideoItem>) => {
  7421. this.videoLocalList = next
  7422. this.dataSource.pushArrayData(next)
  7423. })
  7424. this.replaceItemInList(this.songList, filePath, (next: Array<VideoItem>) => {
  7425. this.songList = next
  7426. this.sonDataSource.pushArrayData(next)
  7427. })
  7428. this.replaceItemInList(this.favList, filePath, (next: Array<VideoItem>) => {
  7429. this.favList = next
  7430. })
  7431. this.replaceItemInList(this.historyList, filePath, (next: Array<VideoItem>) => {
  7432. this.historyList = next
  7433. })
  7434. this.replaceItemInList(this.currentSongList, filePath, (next: Array<VideoItem>) => {
  7435. this.currentSongList = next
  7436. })
  7437. this.replaceItemInList(this.mediaKuList, filePath, (next: Array<VideoItem>) => {
  7438. this.mediaKuList = next
  7439. })
  7440. this.replaceItemInList(this.filteredList, filePath, (next: Array<VideoItem>) => {
  7441. this.filteredList = next
  7442. })
  7443. this.replaceItemInList(this.artistList, filePath, (next: Array<VideoItem>) => {
  7444. this.artistList = next
  7445. })
  7446. this.replaceItemInList(this.albumList, filePath, (next: Array<VideoItem>) => {
  7447. this.albumList = next
  7448. })
  7449. this.listRefreshKey++
  7450. }
  7451. private refreshLazyListViews(mainListUpdated: boolean, playlistUpdated: boolean): void {
  7452. if (!mainListUpdated && !playlistUpdated) {
  7453. return;
  7454. }
  7455. this.listRefreshKey++;
  7456. if (mainListUpdated) {
  7457. this.dataSource.notifyDataReload();
  7458. }
  7459. if (playlistUpdated) {
  7460. this.sonDataSource.notifyDataReload();
  7461. }
  7462. }
  7463. @Builder
  7464. detailSheet(item:VideoItem) {
  7465. Scroll() {
  7466. Column() {
  7467. this.songDetail(item)
  7468. }
  7469. }
  7470. .width('100%')
  7471. .height('100%')
  7472. }
  7473. @Builder
  7474. songDetail(currentItem:VideoItem) {
  7475. Column() {
  7476. if (currentItem) {
  7477. Row() {
  7478. Stack() {
  7479. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.alt') :
  7480. currentItem.pixelMapPath)
  7481. .fillColor(this.themeColor)
  7482. .height(80)
  7483. .width(80)
  7484. .borderRadius(10)
  7485. .opacity(this.opacityItem)// 绑定透明度
  7486. .margin({ left: 22 })
  7487. }
  7488. Column() {
  7489. Column() {
  7490. Text(currentItem.name)
  7491. .fontSize(16)
  7492. .maxLines(1)
  7493. .animation({
  7494. duration: 555,
  7495. curve: 'Linear',
  7496. })
  7497. .fontColor($r('app.color.text_color'))
  7498. .margin({ left: 15 })
  7499. }
  7500. .height('100%')
  7501. .width('100%')
  7502. .justifyContent(FlexAlign.Center)
  7503. .alignItems(HorizontalAlign.Start)
  7504. }
  7505. .height('100%')
  7506. }
  7507. .width('100%')
  7508. .height(90)
  7509. .justifyContent(FlexAlign.SpaceBetween)
  7510. Row() {
  7511. Text('艺术家:')
  7512. .fontSize(14)
  7513. .fontColor($r('app.color.text_color'))
  7514. .margin({ left: 22 })
  7515. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  7516. .fontSize(14)
  7517. .fontColor($r('app.color.text_color'))
  7518. .margin({ left: 10 })
  7519. .layoutWeight(1)
  7520. }
  7521. .width('100%')
  7522. .margin({ top: 10, bottom: 10 })
  7523. .justifyContent(FlexAlign.Start)
  7524. Row() {
  7525. Text('专辑名:')
  7526. .fontSize(14)
  7527. .fontColor($r('app.color.text_color'))
  7528. .margin({ left: 22 })
  7529. Text(currentItem?.album ?currentItem.album : '未知专辑')
  7530. .fontSize(14)
  7531. .margin({ left: 10 })
  7532. .fontColor($r('app.color.text_color'))
  7533. .layoutWeight(1)
  7534. }
  7535. .width('100%')
  7536. .margin({ top: 10, bottom: 10 })
  7537. .justifyContent(FlexAlign.Start)
  7538. Row() {
  7539. Text('时长:')
  7540. .fontSize(14)
  7541. .fontColor($r('app.color.text_color'))
  7542. .margin({ left: 22 })
  7543. Text(StrUtil.isEmpty(currentItem.duration)?
  7544. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  7545. .fontSize(14)
  7546. .margin({ left: 10 })
  7547. .fontColor($r('app.color.text_color'))
  7548. .layoutWeight(1)
  7549. }
  7550. .width('100%')
  7551. .margin({ top: 10, bottom: 10 })
  7552. .justifyContent(FlexAlign.Start)
  7553. Row() {
  7554. Text('采样率:')
  7555. .fontSize(14)
  7556. .fontColor($r('app.color.text_color'))
  7557. .margin({ left: 22 })
  7558. Text(Utility.convertToKHz(currentItem.sampleRate))
  7559. .fontSize(14)
  7560. .margin({ left: 10 })
  7561. .fontColor($r('app.color.text_color'))
  7562. .layoutWeight(1)
  7563. }
  7564. .width('100%')
  7565. .margin({ top: 10, bottom: 10 })
  7566. .justifyContent(FlexAlign.Start)
  7567. Row() {
  7568. Text('比特率:')
  7569. .fontSize(14)
  7570. .fontColor($r('app.color.text_color'))
  7571. .margin({ left: 22 })
  7572. Text(currentItem.bit_rate)
  7573. .fontSize(14)
  7574. .margin({ left: 10 })
  7575. .fontColor($r('app.color.text_color'))
  7576. .layoutWeight(1)
  7577. }
  7578. .width('100%')
  7579. .margin({ top: 10, bottom: 10 })
  7580. .justifyContent(FlexAlign.Start)
  7581. Row() {
  7582. Text('位深:')
  7583. .fontSize(14)
  7584. .fontColor($r('app.color.text_color'))
  7585. .margin({ left: 22 })
  7586. Text(`${currentItem.bits_per_raw_sample} bits`)
  7587. .fontSize(14)
  7588. .margin({ left: 10 })
  7589. .fontColor($r('app.color.text_color'))
  7590. .layoutWeight(1)
  7591. }
  7592. .width('100%')
  7593. .margin({ top: 10, bottom: 10 })
  7594. .justifyContent(FlexAlign.Start)
  7595. Row() {
  7596. Text('声道:')
  7597. .fontSize(14)
  7598. .fontColor($r('app.color.text_color'))
  7599. .margin({ left: 22 })
  7600. Text(`${currentItem.channels}`)
  7601. .fontSize(14)
  7602. .margin({ left: 10 })
  7603. .fontColor($r('app.color.text_color'))
  7604. .layoutWeight(1)
  7605. }
  7606. .width('100%')
  7607. .margin({ top: 10, bottom: 10 })
  7608. .justifyContent(FlexAlign.Start)
  7609. Row() {
  7610. Text('声道布局:')
  7611. .fontSize(14)
  7612. .fontColor($r('app.color.text_color'))
  7613. .margin({ left: 22 })
  7614. Text(`${currentItem.channel_layout}`)
  7615. .fontSize(14)
  7616. .margin({ left: 10 })
  7617. .fontColor($r('app.color.text_color'))
  7618. .layoutWeight(1)
  7619. }
  7620. .width('100%')
  7621. .margin({ top: 10, bottom: 10 })
  7622. .justifyContent(FlexAlign.Start)
  7623. Row() {
  7624. Text('起始播放点:')
  7625. .fontSize(14)
  7626. .fontColor($r('app.color.text_color'))
  7627. .margin({ left: 22 })
  7628. Text(`${currentItem.start_time}`)
  7629. .fontSize(14)
  7630. .margin({ left: 10 })
  7631. .fontColor($r('app.color.text_color'))
  7632. .layoutWeight(1)
  7633. }
  7634. .width('100%')
  7635. .margin({ top: 10, bottom: 10 })
  7636. .justifyContent(FlexAlign.Start)
  7637. Row() {
  7638. Text('风格:')
  7639. .fontSize(14)
  7640. .fontColor($r('app.color.text_color'))
  7641. .margin({ left: 22 })
  7642. Text(currentItem.genre)
  7643. .fontSize(14)
  7644. .margin({ left: 10 })
  7645. .fontColor($r('app.color.text_color'))
  7646. .layoutWeight(1)
  7647. }
  7648. .width('100%')
  7649. .margin({ top: 10, bottom: 10 })
  7650. .justifyContent(FlexAlign.Start)
  7651. Row() {
  7652. Text('发行时间:')
  7653. .fontSize(14)
  7654. .fontColor($r('app.color.text_color'))
  7655. .margin({ left: 22 })
  7656. Text(currentItem.year)
  7657. .fontSize(14)
  7658. .margin({ left: 10 })
  7659. .fontColor($r('app.color.text_color'))
  7660. .layoutWeight(1)
  7661. }
  7662. .width('100%')
  7663. .margin({ top: 10, bottom: 10 })
  7664. .justifyContent(FlexAlign.Start)
  7665. Row() {
  7666. Text('质量评分:')
  7667. .fontSize(14)
  7668. .fontColor($r('app.color.text_color'))
  7669. .margin({ left: 22 })
  7670. Text(currentItem.probe_score+"")
  7671. .fontSize(14)
  7672. .margin({ left: 10 })
  7673. .fontColor($r('app.color.text_color'))
  7674. .layoutWeight(1)
  7675. }
  7676. .width('100%')
  7677. .margin({ top: 10, bottom: 10 })
  7678. .justifyContent(FlexAlign.Start)
  7679. Row() {
  7680. Text('音轨号:')
  7681. .fontSize(14)
  7682. .fontColor($r('app.color.text_color'))
  7683. .margin({ left: 22 })
  7684. Text(currentItem.track)
  7685. .fontSize(14)
  7686. .margin({ left: 10 })
  7687. .fontColor($r('app.color.text_color'))
  7688. .layoutWeight(1)
  7689. }
  7690. .width('100%')
  7691. .margin({ top: 10, bottom: 10 })
  7692. .justifyContent(FlexAlign.Start)
  7693. Row() {
  7694. Text('碟号:')
  7695. .fontSize(14)
  7696. .fontColor($r('app.color.text_color'))
  7697. .margin({ left: 22 })
  7698. Text(currentItem.disc)
  7699. .fontSize(14)
  7700. .margin({ left: 10 })
  7701. .fontColor($r('app.color.text_color'))
  7702. .layoutWeight(1)
  7703. }
  7704. .width('100%')
  7705. .margin({ top: 10, bottom: 10 })
  7706. .justifyContent(FlexAlign.Start)
  7707. Row() {
  7708. Text('专辑艺术家:')
  7709. .fontSize(14)
  7710. .fontColor($r('app.color.text_color'))
  7711. .margin({ left: 22 })
  7712. Text(currentItem.ALBUMARTIST)
  7713. .fontSize(14)
  7714. .margin({ left: 10 })
  7715. .fontColor($r('app.color.text_color'))
  7716. .layoutWeight(1)
  7717. }
  7718. .width('100%')
  7719. .margin({ top: 10, bottom: 10 })
  7720. .justifyContent(FlexAlign.Start)
  7721. Row() {
  7722. Text('作曲家:')
  7723. .fontSize(14)
  7724. .fontColor($r('app.color.text_color'))
  7725. .margin({ left: 22 })
  7726. Text(currentItem.COMPOSER)
  7727. .fontSize(14)
  7728. .margin({ left: 10 })
  7729. .fontColor($r('app.color.text_color'))
  7730. .layoutWeight(1)
  7731. }
  7732. .width('100%')
  7733. .margin({ top: 10, bottom: 10 })
  7734. .justifyContent(FlexAlign.Start)
  7735. Row() {
  7736. Text('作词家:')
  7737. .fontSize(14)
  7738. .fontColor($r('app.color.text_color'))
  7739. .margin({ left: 22 })
  7740. Text(currentItem.LYRICIST)
  7741. .fontSize(14)
  7742. .margin({ left: 10 })
  7743. .fontColor($r('app.color.text_color'))
  7744. .layoutWeight(1)
  7745. }
  7746. .width('100%')
  7747. .margin({ top: 10, bottom: 10 })
  7748. .justifyContent(FlexAlign.Start)
  7749. Row() {
  7750. Text('注释:')
  7751. .fontSize(14)
  7752. .fontColor($r('app.color.text_color'))
  7753. .margin({ left: 22 })
  7754. Text(currentItem.COMMENT)
  7755. .fontSize(14)
  7756. .margin({ left: 10 })
  7757. .fontColor($r('app.color.text_color'))
  7758. .layoutWeight(1)
  7759. }
  7760. .width('100%')
  7761. .margin({ top: 10, bottom: 10 })
  7762. .justifyContent(FlexAlign.Start)
  7763. Row() {
  7764. Text('格式:')
  7765. .fontSize(14)
  7766. .fontColor($r('app.color.text_color'))
  7767. .margin({ left: 22 })
  7768. Text(Utility.formatMimeType(currentItem.mimeType))
  7769. .fontSize(14)
  7770. .margin({ left: 10 })
  7771. .fontColor($r('app.color.text_color'))
  7772. .layoutWeight(1)
  7773. }
  7774. .width('100%')
  7775. .margin({ top: 10, bottom: 10 })
  7776. .justifyContent(FlexAlign.Start)
  7777. Row() {
  7778. Text('播放次数:')
  7779. .fontSize(14)
  7780. .fontColor($r('app.color.text_color'))
  7781. .margin({ left: 22 })
  7782. Text(currentItem.playCount?.toString())
  7783. .fontSize(14)
  7784. .margin({ left: 10 })
  7785. .fontColor($r('app.color.text_color'))
  7786. .layoutWeight(1)
  7787. }
  7788. .width('100%')
  7789. .margin({ top: 10, bottom: 10 })
  7790. .justifyContent(FlexAlign.Start)
  7791. Row() {
  7792. Text('流数量:')
  7793. .fontSize(14)
  7794. .fontColor($r('app.color.text_color'))
  7795. .margin({ left: 22 })
  7796. Text(currentItem.nb_streams?.toString())
  7797. .fontSize(14)
  7798. .margin({ left: 10 })
  7799. .fontColor($r('app.color.text_color'))
  7800. .layoutWeight(1)
  7801. }
  7802. .width('100%')
  7803. .margin({ top: 10, bottom: 10 })
  7804. .justifyContent(FlexAlign.Start)
  7805. Row() {
  7806. Text('文件大小:')
  7807. .fontSize(14)
  7808. .fontColor($r('app.color.text_color'))
  7809. .margin({ left: 22 })
  7810. Text(currentItem.size)
  7811. .fontSize(14)
  7812. .margin({ left: 10 })
  7813. .fontColor($r('app.color.text_color'))
  7814. .layoutWeight(1)
  7815. }
  7816. .width('100%')
  7817. .margin({ top: 10, bottom: 10 })
  7818. .justifyContent(FlexAlign.Start)
  7819. Row() {
  7820. Text('文件名:')
  7821. .fontSize(14)
  7822. .fontColor($r('app.color.text_color'))
  7823. .margin({ left: 22 })
  7824. Text(currentItem.fileName)
  7825. .fontSize(14)
  7826. .margin({ left: 10 })
  7827. .fontColor($r('app.color.text_color'))
  7828. .layoutWeight(1)
  7829. }
  7830. .width('100%')
  7831. .margin({ top: 10, bottom: 10 })
  7832. .justifyContent(FlexAlign.Start)
  7833. Row() {
  7834. Text('修改时间:')
  7835. .fontSize(14)
  7836. .fontColor($r('app.color.text_color'))
  7837. .margin({ left: 22 })
  7838. Text(currentItem.cTime)
  7839. .fontSize(14)
  7840. .margin({ left: 10 })
  7841. .fontColor($r('app.color.text_color'))
  7842. .layoutWeight(1)
  7843. }
  7844. .width('100%')
  7845. .margin({ top: 10, bottom: 10 })
  7846. .justifyContent(FlexAlign.Start)
  7847. Row() {
  7848. Text('存放目录:')
  7849. .fontSize(14)
  7850. .fontColor($r('app.color.text_color'))
  7851. .margin({ left: 22 })
  7852. Text(currentItem.filePath)
  7853. .fontSize(12)
  7854. .margin({ left: 10 })
  7855. .fontColor($r('app.color.text_color'))
  7856. .layoutWeight(1)
  7857. }
  7858. .margin({ top: 10, bottom: 10 })
  7859. .width('100%')
  7860. .justifyContent(FlexAlign.Start)
  7861. Row() {
  7862. Text('内嵌歌词:')
  7863. .fontSize(14)
  7864. .fontColor($r('app.color.text_color'))
  7865. .margin({ left: 22 })
  7866. Text(currentItem.lyricContent)
  7867. .fontSize(12)
  7868. .copyOption(CopyOptions.InApp)
  7869. .margin({ left: 10 })
  7870. .fontColor($r('app.color.text_color'))
  7871. .layoutWeight(1)
  7872. }
  7873. .margin({ top: 10, bottom: 10 })
  7874. .width('100%')
  7875. .justifyContent(FlexAlign.Start)
  7876. }
  7877. }
  7878. .margin({ bottom: 20 })
  7879. }
  7880. //定时关闭布局
  7881. @Builder
  7882. TimeCloseSheet() {
  7883. Scroll() {
  7884. Column() {
  7885. this.TimeClose()
  7886. }
  7887. }
  7888. .width('100%')
  7889. .height('100%')
  7890. }
  7891. //倒计时关闭音乐,退出App功能实现。
  7892. @State selectedMinutes: number = 0 // 0表示未开启
  7893. @State remainingSeconds: number = 0
  7894. // 预设时间选项
  7895. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  7896. private formatTime(seconds: number): string {
  7897. const mins = Math.floor(seconds / 60)
  7898. const secs = seconds % 60
  7899. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  7900. }
  7901. // 开始倒计时
  7902. private handleTimeSelect(minutes: number) {
  7903. if (minutes === this.selectedMinutes) {
  7904. this.stopCountdown();
  7905. this.selectedMinutes = 0;
  7906. return;
  7907. }
  7908. this.selectedMinutes = minutes;
  7909. this.remainingSeconds = minutes * 60;
  7910. this.startCountdown(); // 新增调用
  7911. }
  7912. @Builder
  7913. TimeClose() {
  7914. Column() {
  7915. // 倒计时显示区域
  7916. Text(this.selectedMinutes > 0 ?
  7917. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  7918. "定时关闭未开启")
  7919. .fontSize(17)
  7920. .fontColor($r('app.color.text_color'))
  7921. .margin({ top: 2, bottom: 8 });
  7922. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  7923. ForEach(this.presetTimes, (minutes: number, index: number) => {
  7924. // 单行时间选项容器
  7925. Row() {
  7926. // 文字描述区域
  7927. Text(this.getDisplayText(minutes))
  7928. .fontSize(15)
  7929. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  7930. $r('app.color.text_color'))// 选中态颜色变化
  7931. .textAlign(TextAlign.Start)
  7932. .layoutWeight(1); // 占据剩余空间
  7933. // 复选框样式的选择器
  7934. Row() {
  7935. if (minutes === this.selectedMinutes) {
  7936. // 选中状态 - 带勾号的圆形复选框
  7937. Row() {
  7938. // 使用系统内置的勾号图标
  7939. Image($r('sys.media.ohos_ic_public_ok'))
  7940. .width(14)
  7941. .height(14)
  7942. .fillColor(Color.White)
  7943. }
  7944. .width(24)
  7945. .height(24)
  7946. .borderRadius(12)
  7947. .backgroundColor(this.themeColor)
  7948. .justifyContent(FlexAlign.Center)
  7949. .alignItems(VerticalAlign.Center)
  7950. } else {
  7951. // 未选中状态的圆形边框
  7952. Row()
  7953. .width(24)
  7954. .height(24)
  7955. .borderRadius(12)
  7956. .border({
  7957. width: 2,
  7958. color: $r('app.color.text_color'),
  7959. style: BorderStyle.Solid
  7960. })
  7961. .backgroundColor(Color.Transparent)
  7962. }
  7963. }
  7964. .width(24)
  7965. .height(24)
  7966. .margin({ left: 20 })
  7967. .justifyContent(FlexAlign.Center)
  7968. .alignItems(VerticalAlign.Center)
  7969. }
  7970. .width('100%')
  7971. .padding({
  7972. top: 18,
  7973. bottom: 18,
  7974. left: 18,
  7975. right: 18
  7976. })
  7977. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  7978. $r('app.color.bottom_control_background')) // 选中背景高亮
  7979. .borderRadius(12)
  7980. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7981. .margin({ bottom: 18 })
  7982. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  7983. });
  7984. }
  7985. .width('100%')
  7986. .padding(16)
  7987. }
  7988. }
  7989. // 获取显示文本
  7990. private getDisplayText(minutes: number): string {
  7991. if (minutes === -1) {
  7992. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  7993. }
  7994. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  7995. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  7996. }
  7997. // 处理选择事件
  7998. private handleSelect(minutes: number): void {
  7999. if (minutes === -1) { // 自定义
  8000. // 弹出自定义时间对话框
  8001. DialogHelper.showTextInputDialog({
  8002. title: '自定义时间',
  8003. maskColor: Color.Transparent,
  8004. inputType: InputType.Number,
  8005. text: '',
  8006. onChange: (text) => {
  8007. console.error("onChange: " + text);
  8008. },
  8009. onAction: (action, dialogId, content) => {
  8010. if (action == DialogAction.TWO) {
  8011. const customMinutes = Number(content);
  8012. if (customMinutes > 0) {
  8013. this.handleTimeSelect(customMinutes); // 设置自定义时间
  8014. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  8015. }
  8016. }
  8017. }
  8018. });
  8019. } else {
  8020. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  8021. }
  8022. }
  8023. // 添加定时器引用
  8024. private timerId: number = -1;
  8025. // 启动/重置倒计时
  8026. private startCountdown() {
  8027. // 清除旧定时器
  8028. if (this.timerId !== -1) {
  8029. clearInterval(this.timerId);
  8030. }
  8031. // 创建新定时器
  8032. if (this.selectedMinutes > 0) {
  8033. this.timerId = setInterval(() => {
  8034. if (this.remainingSeconds === 15) {
  8035. this.showConfirmationDialog();
  8036. }
  8037. if (this.remainingSeconds > 0) {
  8038. this.remainingSeconds -= 1;
  8039. } else {
  8040. this.stopCountdown();
  8041. this.handleTimeout();
  8042. }
  8043. }, 1000);
  8044. }
  8045. }
  8046. // 15倒计时后再次提示显示确认是否关闭App对话框
  8047. private showConfirmationDialog() {
  8048. DialogHelper.showAlertDialog({
  8049. backgroundColor: $r('app.color.btn_green'),
  8050. title: '确认关闭',
  8051. maskColor: Color.Transparent,
  8052. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  8053. borderStyle: BorderStyle.Dashed,
  8054. primaryButton: '暂不关闭',
  8055. secondaryButton: '确定',
  8056. onAction: (action) => {
  8057. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  8058. this.stopCountdown();
  8059. this.selectedMinutes = 0
  8060. } else if (action == DialogAction.TWO) {
  8061. }
  8062. }
  8063. })
  8064. }
  8065. // 停止倒计时
  8066. private stopCountdown() {
  8067. if (this.timerId !== -1) {
  8068. clearInterval(this.timerId);
  8069. this.timerId = -1;
  8070. }
  8071. }
  8072. // 超时处理
  8073. private handleTimeout() {
  8074. // 执行播放器关闭逻辑
  8075. this.selectedMinutes = 0;
  8076. ToastUtil.showToast(" 定时关闭已完成");
  8077. this.stop(); // 假设存在的播放器实例
  8078. //退出APP
  8079. const mContext = getContext(this) as common.UIAbilityContext
  8080. mContext.terminateSelf();
  8081. AvSessionController.getInstance(true).unregisterSessionListener()
  8082. }
  8083. //倒计时关闭音乐,退出App功能实现结束。
  8084. //播放列表的拖动List 重新排序
  8085. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  8086. //左滑操作 移动文件 重命名 删除等操作
  8087. @Builder
  8088. sonButton(item: VideoItem, index: number, filePath: string) {
  8089. Row() {
  8090. //加入下一首播放
  8091. Button() {
  8092. Image($r('app.media.next_to_play'))
  8093. .fillColor(Color.White)
  8094. .width(20)
  8095. }
  8096. .width(40)
  8097. .height(40)
  8098. .type(ButtonType.Circle)
  8099. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8100. .backgroundColor(this.themeColor)
  8101. .margin(5)
  8102. .onClick(() => {
  8103. this.addToNextPlay(item);
  8104. })
  8105. Button() {
  8106. Image($r('app.media.close'))
  8107. .fillColor(Color.White)
  8108. .width(20)
  8109. }
  8110. .width(40)
  8111. .height(40)
  8112. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8113. .type(ButtonType.Circle)
  8114. .backgroundColor(this.themeColor)
  8115. .margin(5)
  8116. .onClick(() => {
  8117. this.songList.splice(Number(index), 1)
  8118. this.sonDataSource.pushArrayData(this.songList)
  8119. })
  8120. Button() {
  8121. Image($r('app.media.share2'))
  8122. .fillColor(Color.White)
  8123. .width(20)
  8124. }
  8125. .width(40)
  8126. .height(40)
  8127. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8128. .type(ButtonType.Circle)
  8129. .backgroundColor(this.themeColor)
  8130. .margin(5)
  8131. .onClick(() => {
  8132. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  8133. })
  8134. }
  8135. }
  8136. itemMoveSon(index: number, newIndex: number): void {
  8137. if (newIndex < 0 || newIndex >= this.songList.length) {
  8138. return;
  8139. }
  8140. let tmp = this.songList.splice(index, 1);
  8141. this.songList.splice(newIndex, 0, tmp[0]);
  8142. this.sonDataSource.pushArrayData(this.songList)
  8143. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  8144. if(this.modeType==4&&this.playlistTable){
  8145. updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
  8146. }
  8147. }
  8148. @Builder
  8149. PlayList() {
  8150. List({ scroller: this.playListScroller }) {
  8151. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  8152. ListItem() {
  8153. this.MusicItemSon(item, index)
  8154. }
  8155. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  8156. .animation({
  8157. duration: 666,
  8158. curve: 'ease-in-out' // 可选动画曲线
  8159. })
  8160. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 600 }),
  8161. TransitionEffect.scale({ x: 0, y: 0 })))
  8162. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  8163. //拖动List关键代码开始
  8164. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  8165. .zIndex(this.dragItem === index ? 1 : 0)
  8166. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  8167. .gesture(
  8168. GestureGroup(GestureMode.Sequence,
  8169. LongPressGesture({ repeat: true })
  8170. .onAction((event?: GestureEvent) => {
  8171. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  8172. this.scaleItem = index
  8173. })
  8174. })
  8175. .onActionEnd(() => {
  8176. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  8177. this.scaleItem = -1
  8178. })
  8179. }),
  8180. PanGesture({ fingers: 1, direction: null, distance: 0 })
  8181. .onActionStart(() => {
  8182. this.dragItem = index // 记录当前拖动项索引
  8183. this.dragRefOffset = 0 // 重置偏移基准
  8184. })
  8185. .onActionUpdate((event: GestureEvent) => {
  8186. this.offsetY = event.offsetY - this.dragRefOffset;
  8187. this.neighborItem = -1;
  8188. let indexA = this.songList.indexOf(item);
  8189. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  8190. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  8191. let value: number = 0;
  8192. if (this.offsetY < 0) {
  8193. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  8194. this.neighborItem = indexA - 1;
  8195. this.neighborScale = 1 - value / 20;
  8196. } else if (this.offsetY > 0) {
  8197. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  8198. this.neighborItem = indexA + 1;
  8199. this.neighborScale = 1 - value / 20;
  8200. }
  8201. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  8202. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8203. this.offsetY -= this.ITEM_INTV;
  8204. this.dragRefOffset += this.ITEM_INTV;
  8205. this.itemMoveSon(indexA, indexA + 1);
  8206. });
  8207. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  8208. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8209. this.offsetY += this.ITEM_INTV;
  8210. this.dragRefOffset -= this.ITEM_INTV;
  8211. this.itemMoveSon(indexA, indexA - 1);
  8212. });
  8213. }
  8214. })
  8215. .onActionEnd((event: GestureEvent) => {
  8216. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8217. this.dragItem = -1
  8218. this.neighborItem = -1
  8219. })
  8220. animateTo({
  8221. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  8222. }, () => {
  8223. this.scaleItem = -1
  8224. })
  8225. })
  8226. )
  8227. .onCancel(() => {
  8228. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8229. this.dragItem = -1
  8230. this.neighborItem = -1
  8231. })
  8232. animateTo({
  8233. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  8234. }, () => {
  8235. this.scaleItem = -1
  8236. })
  8237. })
  8238. ) //拖动List关键代码结束
  8239. .onClick(() => {
  8240. this.doPlay(item, index, true)
  8241. })
  8242. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  8243. }
  8244. .width('100%')
  8245. .height('100%')
  8246. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  8247. // .animation({ duration: 500, curve: Curve.Ease }))
  8248. .cachedCount(10)
  8249. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  8250. .gesture(PinchGesture({ fingers: 2 })
  8251. .onActionEnd((event: GestureEvent) => {
  8252. this.setSonListTwoFingers()
  8253. })
  8254. .onActionUpdate(e => {
  8255. this.scaleValue = this.pinchValue * e.scale
  8256. })
  8257. .onActionStart(e => {
  8258. }))
  8259. .padding({
  8260. bottom: 0
  8261. })
  8262. }
  8263. setSonListTwoFingers() {
  8264. this.pinchValue = this.scaleValue;
  8265. Logger.info('this.pinchValue = ' + this.pinchValue);
  8266. if (this.pinchValue >= 1) {
  8267. this.sonTwoFingerType++
  8268. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  8269. if (this.sonTwoFingerType > 3) {
  8270. this.sonTwoFingerType = 1
  8271. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  8272. }
  8273. } else {
  8274. this.sonTwoFingerType--
  8275. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  8276. if (this.sonTwoFingerType < 1) {
  8277. this.sonTwoFingerType = 1
  8278. }
  8279. }
  8280. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  8281. this.pinchValue = 1;
  8282. this.scaleValue = 1;
  8283. }
  8284. @State sonTwoFingerType:number = 3
  8285. @Builder
  8286. private MusicItemSon(item: VideoItem, index?: number) {
  8287. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8288. Row() {
  8289. Stack() {
  8290. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  8291. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  8292. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  8293. .alt($r('app.media.alt'))
  8294. .fillColor(this.themeColor)
  8295. .borderRadius(this.isCoverRectangle?11:'100%')
  8296. .clip(true)
  8297. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  8298. .draggable(false)// 禁止长按手势拖动
  8299. .autoResize(true) // 重采样,可减少内存占用
  8300. .margin({ left: 20 })
  8301. }
  8302. .width('15%')
  8303. Column() {
  8304. Column() {
  8305. Text(this.isShowFileName?item.fileName :item.name)
  8306. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  8307. .fontColor(this.curIndex === index ? this.themeColor :
  8308. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  8309. .maxLines(1)
  8310. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  8311. Row() {
  8312. Column(){
  8313. Text(item.md5Str?.includes('Lossless')?
  8314. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  8315. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  8316. .padding({ top: 3,right:6,left:6,bottom:3 })
  8317. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  8318. $r('app.color.text_color'))
  8319. .fontWeight(500)
  8320. .borderRadius(12)
  8321. .visibility(StrUtil.isEmpty(item.md5Str) ? Visibility.None : Visibility.Visible)
  8322. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  8323. .backgroundColor('#FFC107')
  8324. }
  8325. .padding({ top: 8 })
  8326. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  8327. item.artist + ' ' + item?.duration)
  8328. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  8329. .padding({ top: 8 })
  8330. .maxLines(1)
  8331. .fontColor(this.curIndex === index ? this.themeColor :
  8332. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  8333. .margin({ left: StrUtil.isEmpty(item.md5Str)? 12 :this.sonTwoFingerType == 3 ? 5 : 3 })
  8334. Blank()
  8335. Text(item.size)
  8336. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  8337. .padding({ top: 8 })
  8338. .maxLines(1)
  8339. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  8340. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  8341. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  8342. .margin({ left: 10 })
  8343. }
  8344. }
  8345. .height('100%')
  8346. .width('100%')
  8347. .justifyContent(FlexAlign.Center)
  8348. .alignItems(HorizontalAlign.Start)
  8349. }
  8350. .height('100%')
  8351. .width('65%')
  8352. Column() {
  8353. ImageAnimator()
  8354. .images(this.imagesF)// 动画数组
  8355. .duration(1000)// 持续
  8356. .state(this.animationState)// 动画状态
  8357. .fillMode(FillMode.Forwards)
  8358. .width(18)
  8359. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  8360. Visibility.None)
  8361. .height(18)
  8362. .iterations(-1) // 播放次数
  8363. }
  8364. .width('20%')
  8365. }
  8366. }
  8367. .backgroundColor(Color.Transparent)
  8368. .width('100%')
  8369. .reuseId('son_item')
  8370. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  8371. .shadow(this.scaleItem === index ? {
  8372. radius: 70,
  8373. color: '#15000000',
  8374. offsetX: 0,
  8375. offsetY: 0
  8376. } :
  8377. {
  8378. radius: 0,
  8379. color: '#15000000',
  8380. offsetX: 0,
  8381. offsetY: 0
  8382. })
  8383. .animation({ curve: Curve.Sharp, duration: 300 })
  8384. }
  8385. @Builder
  8386. MusicPlayBuilder() {
  8387. Column() {
  8388. this.IjkMusicPlayerView()
  8389. }
  8390. .transition(TransitionEffect.asymmetric(
  8391. TransitionEffect.opacity(1),
  8392. TransitionEffect.OPACITY
  8393. ))
  8394. .visualEffect(!this.isMusicBGCover&&deviceInfo.sdkApiVersion>=20&&this.bgController?
  8395. new hdsEffect.HdsEffectBuilder()
  8396. .shaderEffect({
  8397. effectType: hdsEffect.EffectType.UV_BACKGROUND_FLOW_LIGHT,
  8398. animation: {
  8399. duration: 10000,
  8400. iterations: -1,
  8401. autoPlay: true,
  8402. onFinish: ()=> {
  8403. console.info('Succeeded in finishing');
  8404. }
  8405. },
  8406. controller: this.bgController,
  8407. })
  8408. .buildEffect():null)
  8409. .height('100%')
  8410. .width('100%')
  8411. .onDisAppear(() => {
  8412. this.translateY = 0;
  8413. })
  8414. .translate({ y: this.translateY })
  8415. .gesture(
  8416. PanGesture(this.panOption)
  8417. .onActionUpdate((event?: GestureEvent) => {
  8418. if (event) {
  8419. // 只允许向下滑动,向上滑动时限制为0
  8420. this.translateY = Math.max(0, event.offsetY);
  8421. this.getUIContext().animateTo({
  8422. duration: 500,
  8423. curve: Curve.Sharp
  8424. }, () => {
  8425. this.scaleValueImage = Math.min(1, Math.max(0.5, 1 - event.offsetY / 600));
  8426. console.info('onecold scaleValueImage:', this.scaleValueImage)
  8427. this.scaleValueText =Math.min(1, Math.max(0.6, 1 - event.offsetY / 700));
  8428. })
  8429. }
  8430. })
  8431. .onActionEnd((event?: GestureEvent) => {
  8432. // 使用更低的阈值和滑动速度判断
  8433. const minDistance = 300; // 最小滑动距离 100vp
  8434. const minVelocity = 500; // 最小滑动速度
  8435. // 获取滑动速度(如果可用)
  8436. const velocity = event?.velocityY || 0;
  8437. // 判断是否应该关闭:距离足够 或者 速度足够快
  8438. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  8439. if (shouldClose) {
  8440. // 添加关闭动画
  8441. this.getUIContext().animateTo({
  8442. duration: 600,
  8443. curve: Curve.Friction
  8444. }, () => {
  8445. this.isShowPlay = false;
  8446. this.scaleValueImage = 1
  8447. this.scaleValueText = 1
  8448. this.translateY = 0;
  8449. })
  8450. } else {
  8451. // 回弹动画
  8452. this.getUIContext().animateTo({
  8453. duration: 600,
  8454. curve: Curve.Friction
  8455. }, () => {
  8456. this.scaleValueImage = 1
  8457. this.scaleValueText = 1
  8458. this.translateY = 0;
  8459. })
  8460. }
  8461. })
  8462. )
  8463. }
  8464. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  8465. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  8466. HeightBreakpoint.HEIGHT_LG;
  8467. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  8468. @State topBarHeight: number = 50
  8469. @State barOpacity: number = 1
  8470. @State barBottomOpacity: number = 1
  8471. private hideDone: boolean = false;
  8472. @State currentYOffset: number = 0;
  8473. @State bottomBarHeight: number = 68;
  8474. private isHiding: boolean = false;
  8475. //是否是Pura X外屏,或者小屏幕
  8476. isPuraWP() {
  8477. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  8478. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  8479. }
  8480. //是否是Pura X外屏,或者小屏幕,手机横屏
  8481. /**
  8482. * 是否是Pura X外屏,或者小屏幕,手机横屏
  8483. * @returns
  8484. */
  8485. isCoverOpacity() {
  8486. if (this.isPuraWP()) {
  8487. return true
  8488. }
  8489. if (this.isPhoneLan()) {
  8490. return true
  8491. }
  8492. if (deviceInfo.marketName.includes('Pura X')
  8493. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  8494. return true
  8495. }
  8496. return false
  8497. }
  8498. //是不是手机横屏
  8499. isPhoneLan() {
  8500. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  8501. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  8502. logHiCarWindow(`isPhoneLan width=${this.windowWidth}`);
  8503. logHiCarWindow(`isPhoneLan height=${this.windowHeight}`);
  8504. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarStatus=${this.isHiCarStatus}`);
  8505. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, curDisplayIsHiCar=${this.curDisplayIsHiCar}`);
  8506. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall=${this.isHiCarSmall()}`);
  8507. if (this.isHiCarKuanBianPing()) {
  8508. return true
  8509. }
  8510. if (this.isHiCar()) {
  8511. return false
  8512. }
  8513. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8514. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  8515. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  8516. return true
  8517. }
  8518. return false
  8519. }
  8520. //是不是1920x720的hicar的屏幕分辨率
  8521. isHiCarKuanBianPing(){
  8522. if(!this.isHiCar()){
  8523. return false
  8524. }
  8525. const hiCarAspectRatios: HiCarAspectRatio[] = [
  8526. { ratio: 1920 / 720, name: "1920x720" },
  8527. ];
  8528. const currentRatio: number = this.windowWidth / this.windowHeight;
  8529. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  8530. logHiCarWindow(`HiCarKuanBianPing currentRatio=${currentRatio}`)
  8531. for (const hiCarRatio of hiCarAspectRatios) {
  8532. logHiCarWindow(`HiCarKuanBianPing hiCarRatio=${hiCarRatio.ratio}`)
  8533. logHiCarWindow(`HiCarKuanBianPing diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  8534. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  8535. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  8536. //宽扁平的尺寸设置列表展示
  8537. this.twoFingerType ==3
  8538. this.isGridMusic = false
  8539. return true;
  8540. }
  8541. }
  8542. return false;
  8543. }
  8544. //是不是hicar的屏幕分辨率
  8545. isHiCarSmall() {
  8546. if(!this.isHiCar()){
  8547. return false
  8548. }
  8549. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  8550. {
  8551. this.columns = 6
  8552. return false
  8553. }
  8554. const hiCarAspectRatios: HiCarAspectRatio[] = [
  8555. { ratio: 800 / 480, name: "800x480" },
  8556. { ratio: 1280 / 720, name: "1280x720" },
  8557. { ratio: 1920 / 1080, name: "1920x1080" },
  8558. ];
  8559. const currentRatio: number = this.windowWidth / this.windowHeight;
  8560. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  8561. logHiCarWindow(`HiCarSmall currentRatio=${currentRatio}`)
  8562. for (const hiCarRatio of hiCarAspectRatios) {
  8563. logHiCarWindow(`HiCarSmall hiCarRatio=${hiCarRatio.ratio}`)
  8564. logHiCarWindow(`HiCarSmall diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  8565. logHiCarWindow(`HiCarSmall isHiCarStatus=${this.isHiCarStatus}`);
  8566. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  8567. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  8568. //宽扁平的尺寸设置列表展示
  8569. return true;
  8570. }
  8571. }
  8572. return false;
  8573. }
  8574. isHiCar() {
  8575. return this.curDisplayIsHiCar;
  8576. }
  8577. //是不是正常的手机竖屏
  8578. isPhonePortrait() {
  8579. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  8580. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  8581. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  8582. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8583. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  8584. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  8585. return true
  8586. }
  8587. return false
  8588. }
  8589. @State showSpeedDialog: boolean = false
  8590. @State longPressSpeed: number = 3 //长按默认倍数
  8591. @Builder
  8592. SpeedDialog() {
  8593. Stack() {
  8594. Column() {
  8595. Text('已切换至' + this.longPressSpeed + '倍速播放')
  8596. .fontColor(Color.White)
  8597. .visibility(Visibility.Hidden)
  8598. }
  8599. .backgroundColor(Color.Black)
  8600. .borderRadius(20)
  8601. .padding({
  8602. top: 10,
  8603. right: 20,
  8604. left: 15,
  8605. bottom: 20
  8606. })
  8607. .opacity(0.6)
  8608. Text('已切换至' + this.longPressSpeed + '倍速播放')
  8609. .fontColor(Color.White)
  8610. }
  8611. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  8612. .zIndex(5)
  8613. .margin({ top: 80 })
  8614. }
  8615. @Builder
  8616. IjkMusicPlayerView() {
  8617. Stack() {
  8618. if(canIUse("SystemCapability.UIDesign.HDSComponent.Core")
  8619. &&deviceInfo.sdkApiVersion>=20&&this.sceneBgController){
  8620. HdsVisualComponent()
  8621. .scene(HdsSceneType.DUAL_EDGE_FLOW_LIGHT_WITH_BACKGROUND_MASK, this.sceneBgController, () => {
  8622. console.info('Succeeded in finishing');
  8623. })
  8624. .width('100%')
  8625. .height('100%')
  8626. .visibility(this.isShowBgLiuGUANG?Visibility.Visible:Visibility.None)
  8627. }
  8628. Column() {
  8629. Column() {
  8630. //播放标题
  8631. Column() {
  8632. this.PlayTitle()
  8633. }
  8634. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  8635. .width('100%')
  8636. .margin({ top: 0 })
  8637. .height(PlayConstants.HEIGHT)
  8638. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  8639. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  8640. if (this.showSpeedDialog) {
  8641. this.SpeedDialog()
  8642. }
  8643. Stack() {
  8644. //手势拖动快进
  8645. Column()
  8646. .width(CommonConstants.FULL_PERCENT)
  8647. .height('100%')
  8648. .gesture(
  8649. GestureGroup(GestureMode.Parallel,
  8650. // 长按屏幕倍数播放
  8651. LongPressGesture({ repeat: true })
  8652. .onAction(() => {
  8653. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8654. this.showSpeedDialog = true;
  8655. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  8656. }
  8657. })
  8658. .onActionEnd(() => {
  8659. this.showSpeedDialog = false;
  8660. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  8661. }),
  8662. //双击屏幕暂停或者播放
  8663. TapGesture({ count: 2 })
  8664. .onAction((event: GestureEvent) => {
  8665. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8666. ToastUtil.showToast('已暂停')
  8667. }
  8668. console.info('onecold playOrPause 6693')
  8669. this.playOrPause()
  8670. })
  8671. )
  8672. )
  8673. }
  8674. .height('65%')
  8675. Swiper() {
  8676. this.CoverInfo()
  8677. this.PlayerLyrics()
  8678. }
  8679. .onChange((index: number) => {
  8680. this.currentSwiperIndex = index
  8681. })
  8682. .indicator(false)
  8683. .displayCount(new BreakpointType({
  8684. sm: 1,
  8685. md: 2,
  8686. lg: 2,
  8687. xl: 2,
  8688. xxl: 2
  8689. }).getValue(this.currentBreakpoint))
  8690. .clip(false)
  8691. .loop(false)
  8692. .autoPlay(false)
  8693. // .interval(8000)
  8694. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  8695. .height('100%')
  8696. .hitTestBehavior(HitTestMode.Transparent)
  8697. Image($r('app.media.icon_replay'))
  8698. .objectFit(ImageFit.Auto)
  8699. .width('120px')
  8700. .height('120px')
  8701. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  8702. .border({ width: 0 })
  8703. .visibility(Visibility.None)
  8704. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  8705. .onClick(() => {
  8706. console.info('onecold startPlayOrResumePlay 6744')
  8707. this.startPlayOrResumePlay();
  8708. })
  8709. }
  8710. .width(CommonConstants.FULL_PERCENT)
  8711. .height(CommonConstants.FULL_PERCENT)
  8712. .justifyContent(FlexAlign.End)
  8713. }
  8714. .justifyContent(FlexAlign.End)
  8715. .margin({ bottom: 8 })
  8716. }
  8717. .backgroundImage(!this.isMusicBGCover||StrUtil.isEmpty(this.cover)?null: this.cover)
  8718. .backgroundImageSize(this.isPuraWP()||!this.isMusicBGCover ? { width: '100%' } : { height: '150%', width: '100%' })
  8719. .animation({
  8720. duration: 666,
  8721. curve: 'ease-in-out' // 可选动画曲线
  8722. })
  8723. .backgroundBlurStyle((this.isPuraWP() && this.currentSwiperIndex === 0) ||!this.isMusicBGCover
  8724. ? BlurStyle.NONE :
  8725. BlurStyle.BACKGROUND_ULTRA_THICK)
  8726. .hitTestBehavior(HitTestMode.Transparent)
  8727. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  8728. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  8729. .onClick(() => {
  8730. if(this.isHiCar())
  8731. return
  8732. if(this.is_auto_hide_progress){
  8733. this.is_auto_hide_progress = false
  8734. }
  8735. this.startAutoHide()
  8736. })
  8737. }
  8738. @Consume progressValue: number ;
  8739. @State currentTime: string = "00:00";
  8740. @State totalTime: string = "00:00";
  8741. @State loadingVisible: Visibility = Visibility.None;
  8742. @State replayVisible: Visibility = Visibility.None;
  8743. @State slideEnable: boolean = false;
  8744. @State aspRatio: number = 0.5;
  8745. @State mContext: object | undefined = undefined;
  8746. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  8747. @State mFirst: boolean = true;
  8748. @State mDestroyPage: boolean = false;
  8749. @State playSpeed: number = 1;
  8750. @State oldSeconds: number = 0;
  8751. @State isSeekTo: boolean = false;
  8752. @State isCurrentTime: boolean = false;
  8753. @State videoWidth: string = '100%';
  8754. @State videoHeight: string = '100%';
  8755. @State initAspectRatio: number = 1;
  8756. @State videoAspectRatio: number = this.initAspectRatio;
  8757. @State videoUrl: string = '';
  8758. private last: number = 0;
  8759. @State videoParentAspectRatio: number = this.initAspectRatio;
  8760. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  8761. @Consume CONTROL_PlayStatus: number ;
  8762. @State PROGRESS_MAX_VALUE: number = 100;
  8763. @State updateProgressTimer: number = 0;
  8764. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  8765. @State name: string = '';
  8766. // @State loop: boolean = false;
  8767. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  8768. @State multiple: string = '1.0X';
  8769. xcomponentController: XComponentController = new XComponentController()
  8770. private panOptionBright: PanGestureOptions =
  8771. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  8772. private panOptionVolume: PanGestureOptions =
  8773. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  8774. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  8775. //手势的音量控制和亮度控制
  8776. private positionX: number = PlayConstants.POSITION_X;
  8777. private positionY: number = PlayConstants.POSITION_Y;
  8778. private windowClass: window.Window = globalThis.windowClass
  8779. @State volume: number = 0.5;
  8780. @State volumeSmall: boolean = false
  8781. @State autoParseMusicName: boolean = true
  8782. @State isShowFileName: boolean = false
  8783. @State isLongNameRoLL: boolean = true//长歌名滚动
  8784. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  8785. @State bright: number = PlayConstants.BRIGHT;
  8786. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  8787. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  8788. @State screenWidth: number = 0
  8789. @State screenHeight: number = 0
  8790. @State statusBarHeight: number = 0
  8791. @State isYesFull: boolean = false
  8792. private seekValue: number = 0
  8793. @State isVideoLock: boolean = false; // Whether the video playback is locked
  8794. eventHub = getContext().eventHub;
  8795. //投播组件
  8796. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  8797. private castController: avSession.AVCastController | undefined = undefined;
  8798. @State isCastPlaying: boolean = false;
  8799. @State currentTime2: number = 0;
  8800. @State currentStringTime: string = '00:00';
  8801. @State duration: number = 0;
  8802. @State isReady: boolean = false;
  8803. @State durationTime: number = 0;
  8804. @State durationStringTime: string = '00:00';
  8805. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  8806. // @State isPlaying: boolean = false;
  8807. private castSeek: boolean = false;
  8808. private castItem: avSession.AVQueueItem | undefined = undefined;
  8809. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  8810. @State rotateAngle2: number = -9
  8811. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  8812. @Consume cover: string | undefined ;
  8813. @State artist: string | undefined = ''
  8814. // 1.初始化controller
  8815. private lyricController: LyricController = new LyricController()
  8816. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  8817. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  8818. private parser = new LyricParser()
  8819. @State randomColor: string = 'rgb(0,0,0)'
  8820. @State randomShakenX: number = 0
  8821. @State randomShakenY: number = 0
  8822. @State lyricTextSize: number = 24
  8823. @State lyricContent: string = ''
  8824. @State isDebug: boolean = false
  8825. @State isHightLightCenter: boolean = true
  8826. /**
  8827. * 初始化歌词加载与展示逻辑
  8828. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  8829. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  8830. * @param isApi2 是否使用API2获取歌词(可选)
  8831. *
  8832. * 主要流程:
  8833. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  8834. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  8835. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  8836. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  8837. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  8838. * 6. 解析失败或读取失败时,清空歌词显示。
  8839. *
  8840. * 注意事项:
  8841. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  8842. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  8843. * - 歌词内容解析后通过lyricController驱动UI渲染。
  8844. */
  8845. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  8846. if (StrUtil.isEmpty(lyricPath)) {
  8847. return
  8848. }
  8849. this.initPipLyricSetting()
  8850. this.lyricControllerSingle
  8851. .setTextSize(15)
  8852. .setCacheSize(4)
  8853. .setTextColor("#FFFFFF")
  8854. .setHighlightColor("#FFFFFF")
  8855. .setHighlightScale(1.2)
  8856. .setEmptyHint("")
  8857. .setAlignMode('center')
  8858. .setAnimationDuration(500)
  8859. .setSingleLine(true)
  8860. this.lyricContent = ''
  8861. this.lyricController
  8862. .setTextSize(this.currentLyricSize)
  8863. .setCacheSize(4)
  8864. .setTextColor("#DDDDDD")
  8865. .setHighlightColor("#FFFFFF")
  8866. .setEmptyHint("")
  8867. .setAnimationDuration(1000)
  8868. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  8869. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  8870. this.setBlurDegree(this.blurDegree, false)
  8871. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  8872. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  8873. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  8874. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  8875. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  8876. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  8877. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  8878. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  8879. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  8880. this.lyricController.setTextWeight(this.lyricTextWeight)
  8881. this.showSingleLyric = false
  8882. this.timeOffset = 0
  8883. this.lyricController.setLyric(null)
  8884. this.lyricControllerSingle.setLyric(null)
  8885. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  8886. console.log("onecold lyricPath =" + lyricPath)
  8887. let neiqianLrc = ''
  8888. let lyContent = this.currentSong?.lyricContent
  8889. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  8890. neiqianLrc = lyContent
  8891. }
  8892. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast&&!isLocal&&!isLocal) {
  8893. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  8894. //赋值给this.lyricContent,播控中心才可以显示歌词
  8895. this.lyricContent = neiqianLrc
  8896. // 将文件内容按行分割成字符串数组
  8897. let lines = neiqianLrc.split('\n').map(line => line.trim());
  8898. // 3.解析歌词
  8899. let lyric = this.parser.parse(lines);
  8900. // 4.设置歌词
  8901. this.lyricController.setLyric(lyric);
  8902. this.lyricControllerXF.setLyric(lyric)
  8903. this.lyricControllerSingle.setLyric(lyric)
  8904. return
  8905. }
  8906. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  8907. && !Utility.isVideoByExtension(this.videoUrl))) {
  8908. if (this.currentSong !== undefined) {
  8909. // ToastUtil.showShort('正在为你搜索在线歌词!')
  8910. //判断是不是赞助会员,是会员的话才开启歌词功能
  8911. // if (!this.isDebug) {
  8912. // if (!Utility.isNoble()) {
  8913. // LogUtil.debug("onecold 不是赞助会员")
  8914. // return
  8915. // }
  8916. // if(!Utility.isPassInstallTime(33)){
  8917. // LogUtil.debug("onecold not pass time")
  8918. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  8919. // return
  8920. // }
  8921. // }
  8922. let artist = this.currentSong?.artist
  8923. if (artist === undefined) {
  8924. artist = ''
  8925. }
  8926. if (isApi2 === undefined) {
  8927. isApi2 = false
  8928. }
  8929. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  8930. // LogUtil.debug("onecold res =" + res)
  8931. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  8932. if (StrUtil.isNotEmpty(res)) {
  8933. this.lyricContent = res
  8934. let lines = res.split('\n').map(line => line.trim());
  8935. // 3.解析歌词
  8936. let lyric = this.parser.parse(lines);
  8937. // 4.设置歌词
  8938. this.lyricController.setLyric(lyric);
  8939. this.lyricControllerXF.setLyric(lyric)
  8940. this.lyricControllerSingle.setLyric(lyric)
  8941. this.showSingleLyric = true
  8942. // 4.保存歌词文件lyric到本地
  8943. //2025年8月28日歌词不再加密下载
  8944. this.saveDataToFile(res, lyricPath, false)
  8945. } else {
  8946. this.lyricController.setLyric(null)
  8947. this.lyricControllerXF.setLyric(null)
  8948. this.lyricControllerSingle.setLyric(null)
  8949. if (isOnLineAndToast) {
  8950. ToastUtil.showShort('未获取到歌词!')
  8951. }
  8952. }
  8953. } else {
  8954. this.lyricController.setLyric(null)
  8955. this.lyricControllerXF.setLyric(null)
  8956. this.lyricControllerSingle.setLyric(null)
  8957. if (isOnLineAndToast) {
  8958. ToastUtil.showShort('未获取到歌词!')
  8959. }
  8960. }
  8961. })
  8962. } else {
  8963. this.lyricController.setLyric(null)
  8964. this.lyricControllerXF.setLyric(null)
  8965. this.lyricControllerSingle.setLyric(null)
  8966. if (isOnLineAndToast) {
  8967. ToastUtil.showShort('未获取到歌词!')
  8968. }
  8969. }
  8970. return
  8971. }
  8972. try {
  8973. let isJiaMi = false;
  8974. let realLyricPath = lyricPath
  8975. if (FileUtil.accessSync(jiaMilyricPath)) {
  8976. isJiaMi = true
  8977. realLyricPath = jiaMilyricPath
  8978. console.info("onecold 找到加密本地歌词 ");
  8979. } else {
  8980. isJiaMi = false
  8981. realLyricPath = lyricPath
  8982. console.info("onecold 找到本地歌词 ");
  8983. }
  8984. // 3.读取文件内容并指定编码为 UTF-8
  8985. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  8986. const stat = await fileIo.stat(file.fd);
  8987. const arrayBuffer = new ArrayBuffer(stat.size);
  8988. fs.read(file.fd, arrayBuffer)
  8989. .then((readLen: number) => {
  8990. console.info("read file data succeed");
  8991. // let buf = buffer.from(arrayBuffer, 0, readLen);
  8992. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  8993. // 检查 buf 是否为空
  8994. if (buf.length === 0) {
  8995. throw new Error("Buffer is empty after reading the file");
  8996. }
  8997. try {
  8998. // 检测文件编码
  8999. // let detectedEncoding = chardet.detect(buf);
  9000. // console.info("onecoldT Detected encoding: " + detectedEncoding);
  9001. let detectedEncoding = this.detect(arrayBuffer)
  9002. console.info("onecoldT Detected encoding: " + detectedEncoding);
  9003. // 使用检测到的编码解码,解决中文乱码问题
  9004. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  9005. console.info("onecoldT Detected textDecoder: " + textDecoder);
  9006. let fileContent = textDecoder.decode(buf);
  9007. console.info(`onecoldT The content of file1: ${fileContent}`);
  9008. //解密
  9009. if (isJiaMi) {
  9010. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  9011. }
  9012. console.info(`onecold The content of file2: ${fileContent}`);
  9013. this.lyricContent = fileContent
  9014. if(isLocal){//编辑标签选择本地歌词需要赋值给this.lyricConStr
  9015. this.lyricConStr = fileContent
  9016. }
  9017. // 将文件内容按行分割成字符串数组
  9018. let lines = fileContent.split('\n').map(line => line.trim());
  9019. console.info(`onecold The content of file: ${fileContent}`);
  9020. // 3.解析歌词
  9021. let lyric = this.parser.parse(lines);
  9022. // 4.设置歌词
  9023. this.lyricController.setLyric(lyric);
  9024. this.lyricControllerXF.setLyric(lyric)
  9025. this.lyricControllerSingle.setLyric(lyric)
  9026. this.showSingleLyric = true
  9027. console.info(`The content of file: ${fileContent}`);
  9028. } catch (chardetError) {
  9029. console.error("chardet.detect failed with error: " + chardetError.message);
  9030. this.lyricController.setLyric(null);
  9031. this.lyricControllerXF.setLyric(null)
  9032. this.lyricControllerSingle.setLyric(null)
  9033. }
  9034. })
  9035. .catch((err: BusinessError) => {
  9036. this.lyricController.setLyric(null)
  9037. this.lyricControllerXF.setLyric(null)
  9038. this.lyricControllerSingle.setLyric(null)
  9039. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  9040. })
  9041. .catch((err: Error) => {
  9042. this.lyricController.setLyric(null)
  9043. this.lyricControllerXF.setLyric(null)
  9044. this.lyricControllerSingle.setLyric(null)
  9045. console.error("read file 2 data failed with error message: " + err.message);
  9046. })
  9047. .finally(() => {
  9048. fs.closeSync(file);
  9049. });
  9050. } catch (error) {
  9051. this.lyricController.setLyric(null)
  9052. this.lyricControllerSingle.setLyric(null)
  9053. this.lyricControllerXF.setLyric(null)
  9054. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  9055. }
  9056. }
  9057. detect(data: ArrayBuffer): string {
  9058. //创建检测对象
  9059. let detector: UniversalDetector = new UniversalDetector();
  9060. // 传入检测数据并实时判断编码格式
  9061. detector.handleData(data, 0, data.byteLength);
  9062. // 标记检测数据 读取结束
  9063. detector.dataEnd();
  9064. // 获取检测结果
  9065. let detected: string = detector.getDetectedCharset();
  9066. // 释放资源
  9067. detector.reset();
  9068. return detected;
  9069. }
  9070. //初始化悬浮歌词的自定义设置
  9071. initPipLyricSetting() {
  9072. this.lyricControllerXF
  9073. .setTextSize(this.currentLyricSize)
  9074. .setCacheSize(4)
  9075. .setTextColor("#DDDDDD")
  9076. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  9077. .setEmptyHint("")
  9078. .setAnimationDuration(1000)
  9079. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  9080. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  9081. this.setBlurDegree(this.blurDegreePip, true)
  9082. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  9083. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  9084. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  9085. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  9086. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  9087. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  9088. this.lyricControllerXF.setHightLightCenter(true)
  9089. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  9090. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  9091. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  9092. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  9093. if (this.pipBgIndex === 0) {
  9094. if (this.cover) {
  9095. this.pipBg = this.cover
  9096. } else {
  9097. this.pipBg = this.imageColor
  9098. }
  9099. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  9100. }
  9101. }
  9102. //根据item返回歌词内容
  9103. async getLyricContent(item: VideoItem): Promise<string> {
  9104. let neiqianLrc = ''
  9105. let lyContent = item?.lyricContent
  9106. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  9107. neiqianLrc = lyContent
  9108. return neiqianLrc
  9109. }
  9110. try {
  9111. //取数据库里面的歌词lyContent
  9112. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  9113. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  9114. console.log("onecold Lyrics:", lyricContent);
  9115. neiqianLrc = lyricContent
  9116. return neiqianLrc
  9117. }
  9118. } catch (error) {
  9119. console.error("Error fetching lyrics:", error);
  9120. }
  9121. try {
  9122. let filePath = item.filePath;
  9123. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  9124. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  9125. let isJiaMi = false;
  9126. let realLyricPath = lyricPath;
  9127. if (FileUtil.accessSync(jiaMilyricPath)) {
  9128. isJiaMi = true;
  9129. realLyricPath = jiaMilyricPath;
  9130. console.info("onecold 找到加密本地歌词");
  9131. } else {
  9132. console.info("onecold 找到本地歌词");
  9133. }
  9134. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  9135. const stat = await fileIo.stat(file.fd);
  9136. const arrayBuffer = new ArrayBuffer(stat.size);
  9137. const readLen = await fs.read(file.fd, arrayBuffer);
  9138. console.info("read file data succeed");
  9139. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  9140. if (buf.length === 0) {
  9141. throw new Error("Buffer is empty after reading the file");
  9142. }
  9143. // let detectedEncoding = chardet.detect(buf);
  9144. let detectedEncoding = this.detect(arrayBuffer)
  9145. console.info("Detected encoding: " + detectedEncoding);
  9146. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  9147. let fileContent = textDecoder.decode(buf);
  9148. console.info(`onecold The content of file1: ${fileContent}`);
  9149. if (isJiaMi) {
  9150. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  9151. }
  9152. console.info(`onecold The content of file2: ${fileContent}`);
  9153. fs.closeSync(file);
  9154. return fileContent;
  9155. } catch (error) {
  9156. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  9157. return '';
  9158. }
  9159. }
  9160. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  9161. if (StrUtil.isEmpty(filePath)) {
  9162. return
  9163. }
  9164. try {
  9165. //将content进行加密
  9166. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  9167. let lyricContent = ''
  9168. if (isJiaMi) {
  9169. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  9170. } else {
  9171. lyricContent = content
  9172. }
  9173. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  9174. // 清空文件内容
  9175. await fileIo.truncate(file.fd, 0);
  9176. await fileIo.write(file.fd, lyricContent);
  9177. await fileIo.close(file);
  9178. console.log('onecold lyric file Data saved successfully.');
  9179. } catch (error) {
  9180. console.error('onecold lyric file Failed to save data:', error);
  9181. }
  9182. }
  9183. // 定义开始旋转的方法
  9184. // 定时器用于一百毫秒执行一次旋转角度
  9185. @State timer: number = 0
  9186. @State rotateAngle: number = 0
  9187. //封面旋转动画
  9188. animationRoFun() {
  9189. if (this.isPlaying && !this.isCoverRectangle) {
  9190. this.timer = setInterval(() => {
  9191. this.rotateAngle += 1
  9192. }, 100)
  9193. this.startRotation()
  9194. } else {
  9195. clearInterval(this.timer)
  9196. this.stopRotation()
  9197. }
  9198. }
  9199. // 定义开始旋转的方法
  9200. startRotation() {
  9201. if (this.isPlaying) {
  9202. animateTo({
  9203. duration: 777,
  9204. iterations: 1,
  9205. curve: Curve.Linear
  9206. }, () => {
  9207. this.rotateAngle2 = -9
  9208. })
  9209. }
  9210. }
  9211. // 回调,暂停和播放按钮回调,下一首和上一首
  9212. playChange() {
  9213. // if(this.isCoverRectangle){
  9214. // return
  9215. // }
  9216. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  9217. this.setIsPlaying(true)
  9218. this.animationState = AnimationStatus.Running
  9219. } else {
  9220. this.setIsPlaying(false)
  9221. this.animationState = AnimationStatus.Paused
  9222. }
  9223. AppStorage.setOrCreate('animationState', this.animationState);
  9224. }
  9225. // 定义停止旋转的方法
  9226. stopRotation() {
  9227. if (this.isCoverRectangle) {
  9228. this.rotateAngle = 0
  9229. } else {
  9230. //唱针以左上角为点选择逆时针40度
  9231. animateTo({
  9232. duration: 1000,
  9233. curve: Curve.Linear,
  9234. iterations: 1,
  9235. }, () => {
  9236. this.rotateAngle2 = -45;
  9237. });
  9238. }
  9239. }
  9240. @Builder
  9241. private LyricsTopItem() {
  9242. Row() {
  9243. Stack() {
  9244. Image(this.cover)
  9245. .height(58)
  9246. .width(58)
  9247. .alt($r('app.media.alt'))
  9248. .borderRadius(8)
  9249. .clickEffect({ level: ClickEffectLevel.HEAVY })
  9250. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  9251. .shadow({
  9252. radius: 22,
  9253. type: ShadowType.BLUR,
  9254. color: 'on_primary'
  9255. })
  9256. }
  9257. .width('18%')
  9258. Column() {
  9259. Column() {
  9260. Text(this.name)
  9261. .fontSize(16)
  9262. .maxLines(1)
  9263. .fontWeight(FontWeight.Bolder)
  9264. .fontColor(this.currentLyricColor)
  9265. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  9266. Row() {
  9267. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  9268. .fontSize(13)
  9269. .fontWeight(FontWeight.Bold)
  9270. .padding({ top: 8 })
  9271. .fontColor(this.currentLyricColor)
  9272. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  9273. Blank()
  9274. }
  9275. }
  9276. .height('100%')
  9277. .width('100%')
  9278. .justifyContent(FlexAlign.Center)
  9279. .alignItems(HorizontalAlign.Start)
  9280. }
  9281. .height('100%')
  9282. .width('65%')
  9283. Column() {
  9284. Image($r('app.media.lyric'))
  9285. .width(28)
  9286. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9287. .margin({ right: 30 })
  9288. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9289. .onClick(() => {
  9290. this.isLyricSetting = !this.isLyricSetting;
  9291. })
  9292. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  9293. height: '99%',
  9294. dragBar: true,
  9295. preferType: SheetType.CENTER,
  9296. showClose: true,
  9297. blurStyle: BlurStyle.Thin,
  9298. backgroundColor: Color.Transparent,
  9299. title: { title: $r('app.string.lyric_setting') }
  9300. })
  9301. }
  9302. .width('18%')
  9303. }
  9304. .width('82%')
  9305. .height(58)
  9306. .justifyContent(FlexAlign.SpaceBetween)
  9307. }
  9308. //歌词显示
  9309. @Builder
  9310. PlayerLyrics() {
  9311. Column() {
  9312. Column() {
  9313. this.LyricsTopItem()
  9314. }
  9315. .height(this.isPuraWP() ? 15 : 58)
  9316. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  9317. Visibility.None : Visibility.Visible)
  9318. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  9319. .width("100%")
  9320. Column() {
  9321. LyricView2({
  9322. controller: this.lyricController,
  9323. enableSeek: true,
  9324. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  9325. seekLineColor: "#80ffffff", // 滑动定位线颜色
  9326. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  9327. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  9328. if (!this.isPlaying) {
  9329. console.info('onecold startPlayOrResumePlay 7527')
  9330. this.startPlayOrResumePlay()
  9331. }
  9332. else {
  9333. this.isSeekTo = true;
  9334. this.mDestroyPage = false;
  9335. this.showLoadIng();
  9336. this.seekTo(position + "");
  9337. this.isSeekTo = false;
  9338. }
  9339. return true
  9340. }
  9341. })
  9342. .width("100%")
  9343. .layoutWeight(1)
  9344. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  9345. if (this.isPhoneLan()) {
  9346. Column() {
  9347. this.playProgressView()
  9348. // this.playCenterView()
  9349. }
  9350. .margin({ bottom: 30, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  9351. }
  9352. }
  9353. .position({
  9354. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  9355. (this.isPuraWP() ? 58 : 99)
  9356. })
  9357. .justifyContent(FlexAlign.Center)
  9358. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  9359. }
  9360. }
  9361. @Builder
  9362. SingleLyricView() {
  9363. Column() {
  9364. Column() {
  9365. LyricView2({
  9366. controller: this.lyricControllerSingle,
  9367. enableSeek: false,
  9368. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  9369. seekLineColor: "#80ffffff", // 滑动定位线颜色
  9370. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  9371. })
  9372. }
  9373. .height(66)
  9374. .margin({ bottom: 20 })
  9375. }
  9376. }
  9377. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  9378. @Builder
  9379. BottomControl() {
  9380. Column() {
  9381. this.TopPlayProgressView()
  9382. //播放 暂停,下一首,上一首
  9383. this.playCenterView()
  9384. if(!this.curDisplayIsHiCar){
  9385. //播放进度条
  9386. this.BottomView()
  9387. }
  9388. }
  9389. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  9390. }
  9391. //播放控制上一首 下一首 暂停和播放
  9392. @Builder
  9393. playCenterView(){
  9394. Row() {
  9395. Button({type:ButtonType.Circle,stateEffect:true}){
  9396. //更多功能
  9397. Image($r('app.media.menu'))
  9398. .width(24)
  9399. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9400. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  9401. height: '99%',
  9402. preferType:SheetType.CENTER,
  9403. dragBar: true,
  9404. showClose: true,
  9405. blurStyle: BlurStyle.Thin,
  9406. title: { title: $r('app.string.more') },
  9407. backgroundColor: Color.Transparent,
  9408. })
  9409. }
  9410. .height(45)
  9411. .width(45)
  9412. .margin({ left: 5 })
  9413. .backgroundColor(Color.Transparent)
  9414. .onClick(() => {
  9415. this.isShowMoreView = !this.isShowMoreView;
  9416. })
  9417. Button({type:ButtonType.Circle,stateEffect:true}){
  9418. Image($r('app.media.ic_previous'))
  9419. .width(33)
  9420. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9421. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9422. }
  9423. .height(45)
  9424. .width(45)
  9425. .onClick(async () => {
  9426. await this.playPrevious()
  9427. })
  9428. .backgroundColor(Color.Transparent)
  9429. Button({type:ButtonType.Circle,stateEffect:true}){
  9430. Column() {
  9431. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  9432. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  9433. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  9434. .width(this.isPhoneLan()?45:55)
  9435. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9436. .fillColor(Color.White)
  9437. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9438. }
  9439. }
  9440. .onClick(async () => {
  9441. this.playOrPause()
  9442. })
  9443. .backgroundColor(Color.Transparent)
  9444. .layoutWeight(1)
  9445. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9446. Image($r('app.media.ic_next'))
  9447. .width(33)
  9448. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9449. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9450. }
  9451. .height(45)
  9452. .width(45)
  9453. .backgroundColor(Color.Transparent)
  9454. .onClick(async () => {
  9455. await this.playNext();
  9456. })
  9457. if(this.curDisplayIsHiCar){
  9458. this.playModeButton()
  9459. }else{
  9460. this.fullButton()
  9461. }
  9462. }
  9463. .width('95%')
  9464. .margin({ bottom:this.isCoverOpacity()?0:15 })
  9465. .justifyContent(FlexAlign.SpaceEvenly)
  9466. }
  9467. @Builder
  9468. TopPlayProgressView(){
  9469. Column() {
  9470. Row(){
  9471. Stack(){
  9472. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  9473. .fontColor([Color.White])
  9474. .fontSize(21)
  9475. .effectStrategy(1)
  9476. Text(this.fastForwardSeconds)
  9477. .fontColor(Color.White)
  9478. .fontSize(10)
  9479. .fontWeight(FontWeight.Bold)
  9480. }
  9481. .padding({left:12,bottom:6})
  9482. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  9483. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9484. .onClick(()=>{
  9485. this.backForward()
  9486. })
  9487. Slider({
  9488. value: this.progressValue,
  9489. min: 0,
  9490. max: this.PROGRESS_MAX_VALUE,
  9491. step: 1,
  9492. style: SliderStyle.InSet
  9493. })
  9494. .height(20)
  9495. .blockColor('rgba(255,255,255,1)')
  9496. .trackColor('rgba(255,255,255,0.3)')
  9497. .selectedColor(Color.White)
  9498. .trackThickness(4)
  9499. .showSteps(false)
  9500. .showTips(true)
  9501. .layoutWeight(1)
  9502. .enabled(this.slideEnable)
  9503. .onChange((value: number, mode: SliderChangeMode) => {
  9504. // if (mode == 2) {
  9505. this.isSeekTo = true;
  9506. this.mDestroyPage = false;
  9507. this.showLoadIng();
  9508. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  9509. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  9510. this.seekTo(seekValue + "");
  9511. // this.setProgress()
  9512. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  9513. this.isSeekTo = false;
  9514. // }
  9515. })
  9516. Stack(){
  9517. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  9518. .fontColor([Color.White])
  9519. .fontSize(21)
  9520. .effectStrategy(1)
  9521. Text(this.fastForwardSeconds)
  9522. .fontColor(Color.White)
  9523. .fontSize(10)
  9524. .fontWeight(FontWeight.Bold)
  9525. }
  9526. .padding({right:10,bottom:6})
  9527. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  9528. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9529. .onClick(()=>{
  9530. this.fastForward()
  9531. })
  9532. }
  9533. .justifyContent(FlexAlign.Center)
  9534. .padding({left:20,right:20})
  9535. .width(this.isLandscape?'88%':'95%')
  9536. Row() {
  9537. Text(this.currentTime)
  9538. .fontSize(10)
  9539. .fontColor(Color.White)
  9540. .margin({left:25})
  9541. Blank()
  9542. Text(this.totalTime)
  9543. .fontSize(10)
  9544. .fontColor(Color.White)
  9545. .margin({right:25})
  9546. }
  9547. .width(this.isLandscape?'85%':'90%')
  9548. .height(10)
  9549. }
  9550. .width('100%')
  9551. .alignItems(HorizontalAlign.Center)
  9552. }
  9553. @Builder
  9554. playModeButton(){
  9555. Button({type:ButtonType.Circle,stateEffect:true}){
  9556. Column() {
  9557. if (this.playType === 0) {
  9558. Image($r('app.media.loop'))
  9559. .width(27)
  9560. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9561. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9562. } else if (this.playType === 1) {
  9563. Image($r('app.media.single'))
  9564. .width(27)
  9565. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9566. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9567. } else if (this.playType === 2) {
  9568. Image($r('app.media.normal_play'))
  9569. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9570. .width(27)
  9571. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9572. } else if (this.playType === 3) {
  9573. Image($r('app.media.random'))
  9574. .width(27)
  9575. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9576. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9577. }
  9578. }
  9579. }
  9580. .layoutWeight(1)
  9581. .margin({ left: 5 })
  9582. .height(45)
  9583. .width(45)
  9584. .backgroundColor(Color.Transparent)
  9585. .onClick(async () => {
  9586. this.setLoopMode()
  9587. })
  9588. }
  9589. //播放进度条
  9590. @Builder
  9591. BottomView(){
  9592. Row() {
  9593. this.playModeButton()
  9594. if(this.currentSong){
  9595. Button({type:ButtonType.Circle,stateEffect:true}){
  9596. Column() {
  9597. Image($r('app.media.rename2'))
  9598. .width(21)
  9599. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9600. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9601. }
  9602. }
  9603. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  9604. height: '99%',
  9605. dragBar: true,
  9606. showClose: true,
  9607. preferType: SheetType.BOTTOM,
  9608. title: { title: '编辑标签' }
  9609. })
  9610. .height(45)
  9611. .width(45)
  9612. .layoutWeight(1)
  9613. .backgroundColor(Color.Transparent)
  9614. .onClick(async () => {
  9615. this.initEditFields(this.currentSong)
  9616. this.tempLyricContent = this.lyricContent
  9617. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  9618. this.lyricConStr = this.tempLyricContent
  9619. }
  9620. this.isShowEdit = !this.isShowEdit;
  9621. })
  9622. }
  9623. Button({type:ButtonType.Circle,stateEffect:true}){
  9624. Column() {
  9625. Image($r('app.media.lyric'))
  9626. .width(26)
  9627. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9628. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9629. }
  9630. }
  9631. .height(45)
  9632. .width(45)
  9633. .layoutWeight(1)
  9634. .backgroundColor(Color.Transparent)
  9635. .onClick(async () => {
  9636. this.isLyricSetting = !this.isLyricSetting;
  9637. })
  9638. //播放列表
  9639. Button({type:ButtonType.Circle,stateEffect:true}){
  9640. Image($r('app.media.hm_playlist'))
  9641. .width(24)
  9642. .fillColor(Color.White)
  9643. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9644. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9645. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  9646. height: '95%',
  9647. dragBar: true,
  9648. showClose: true,
  9649. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9650. blurStyle: BlurStyle.Thin,
  9651. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  9652. title: {
  9653. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  9654. + `(${this.songList.length}首)`
  9655. }
  9656. })
  9657. }
  9658. .layoutWeight(1)
  9659. .height(45)
  9660. .width(45)
  9661. .backgroundColor(Color.Transparent)
  9662. .onClick(() => {
  9663. this.isShowSheetView = !this.isShowSheetView;
  9664. if(this.isPlayListBgGrass){
  9665. this.isFrontWhite = true
  9666. }else{
  9667. this.isFrontWhite = false
  9668. }
  9669. this.scrollIndex()
  9670. })
  9671. }
  9672. .width(this.isLandscape?'88%':'95%')
  9673. .justifyContent(FlexAlign.SpaceAround)
  9674. .height(30)
  9675. .animation({
  9676. duration: 666,
  9677. curve: 'ease-in-out' // 可选动画曲线
  9678. })
  9679. }
  9680. @Builder
  9681. fullButton(){
  9682. Button({type:ButtonType.Circle,stateEffect:true}){
  9683. Column() {
  9684. Image($r('app.media.full_4'))
  9685. .width(25)
  9686. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9687. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9688. }
  9689. }
  9690. .layoutWeight(1)
  9691. .backgroundColor(Color.Transparent)
  9692. .height(45)
  9693. .width(45)
  9694. .onClick(async () => {
  9695. if (this.isLandscape) {
  9696. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  9697. } else {
  9698. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  9699. }
  9700. })
  9701. }
  9702. //旧版本播放进度条
  9703. @Builder
  9704. playProgressView() {
  9705. Row() {
  9706. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9707. Column() {
  9708. if (this.playType === 0) {
  9709. Image($r('app.media.loop'))
  9710. .width($r('app.float.control_image_width'))
  9711. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9712. } else if (this.playType === 1) {
  9713. Image($r('app.media.single'))
  9714. .width($r('app.float.control_image_width'))
  9715. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9716. } else if (this.playType === 2) {
  9717. Image($r('app.media.normal_play'))
  9718. .width($r('app.float.control_image_width'))
  9719. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9720. } else if (this.playType === 3) {
  9721. Image($r('app.media.random'))
  9722. .width($r('app.float.control_image_width'))
  9723. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9724. }
  9725. }
  9726. }
  9727. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  9728. .animation({
  9729. duration: 666,
  9730. curve: 'ease-in-out' // 可选动画曲线
  9731. })
  9732. .backgroundColor(Color.Transparent)
  9733. .margin({ right: 10 })
  9734. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9735. .onClick(async () => {
  9736. this.setLoopMode()
  9737. })
  9738. Text(this.currentTime)
  9739. .fontSize($r('app.float.slider_font_size'))
  9740. .fontColor(Color.White)
  9741. .margin(3)
  9742. Slider({
  9743. value: this.progressValue,
  9744. min: 0,
  9745. max: this.PROGRESS_MAX_VALUE,
  9746. step: 1,
  9747. style: SliderStyle.OutSet
  9748. })
  9749. .width('600px')
  9750. .blockColor('rgba(255,255,255,1)')
  9751. .trackColor('rgba(255,255,255,0.3)')
  9752. .selectedColor(Color.White)
  9753. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  9754. .layoutWeight(1)
  9755. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  9756. .showSteps(false)
  9757. .showTips(true)
  9758. .enabled(this.slideEnable)
  9759. .onChange((value: number, mode: SliderChangeMode) => {
  9760. // if (mode == 2) {
  9761. this.isSeekTo = true;
  9762. this.mDestroyPage = false;
  9763. this.showLoadIng();
  9764. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  9765. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  9766. this.seekTo(seekValue + "");
  9767. // this.setProgress()
  9768. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  9769. this.isSeekTo = false;
  9770. // }
  9771. })
  9772. Text(this.totalTime)
  9773. .fontSize($r('app.float.slider_font_size'))
  9774. .fontColor(Color.White)
  9775. .margin(3)
  9776. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  9777. //播放列表
  9778. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9779. Image($r('app.media.hm_playlist'))
  9780. .width($r('app.float.control_image_width'))
  9781. .fillColor(Color.White)
  9782. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9783. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  9784. height: '95%',
  9785. dragBar: true,
  9786. showClose: true,
  9787. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9788. blurStyle: BlurStyle.Thin,
  9789. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  9790. title: {
  9791. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  9792. + `(${this.songList.length}首)`
  9793. }
  9794. })
  9795. }
  9796. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  9797. .animation({
  9798. duration: 666,
  9799. curve: 'ease-in-out' // 可选动画曲线
  9800. })
  9801. .backgroundColor(Color.Transparent)
  9802. .margin({ right: 20, left: 10 })
  9803. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9804. .onClick(() => {
  9805. this.isShowSheetView = !this.isShowSheetView;
  9806. if (this.isPlayListBgGrass) {
  9807. this.isFrontWhite = true
  9808. } else {
  9809. this.isFrontWhite = false
  9810. }
  9811. this.scrollIndex()
  9812. })
  9813. }
  9814. //x5的竖屏模式需要99%
  9815. .width(this.isPhonePortrait() ? '93.4%'
  9816. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  9817. .height(this.isPhoneLan() ? 25 : 33)
  9818. .animation({
  9819. duration: 666,
  9820. curve: 'ease-in-out' // 可选动画曲线
  9821. })
  9822. }
  9823. isBigScreen() {
  9824. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  9825. return true
  9826. }
  9827. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  9828. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  9829. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  9830. return false
  9831. } else {
  9832. return true
  9833. }
  9834. return false
  9835. }
  9836. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  9837. @State isCoverRectangle: boolean = false
  9838. // 添加控制缩放的状态变量
  9839. @State scaleValueImage: number = 1
  9840. @State scaleValueText: number = 1
  9841. @Builder
  9842. CoverInfo() {
  9843. Column() {
  9844. Stack() {
  9845. Column() {
  9846. //方形封面布局
  9847. if (this.isCoverRectangle) {
  9848. this.RectangleCoverView()
  9849. } else {
  9850. //圆形封面布局
  9851. this.CicleCoverView()
  9852. }
  9853. this.musicNameInfo(false)
  9854. if (this.isPhoneLan()) {
  9855. Text(this.name)
  9856. .fontSize(18)
  9857. .fontWeight(FontWeight.Bold)
  9858. .margin({ top: 13 })
  9859. .textOverflow({ overflow: TextOverflow.Ellipsis })
  9860. .maxLines(1)
  9861. .width('99%')
  9862. .textAlign(TextAlign.Center)
  9863. .fontColor(Color.White)
  9864. }
  9865. }
  9866. .width('100%')
  9867. Column({ space: 8 }) {
  9868. Text(this.name)
  9869. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  9870. .fontWeight(FontWeight.Bold)
  9871. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9872. .maxLines(1)
  9873. .width('85%')
  9874. .textAlign(TextAlign.Center)
  9875. .fontColor(Color.White)
  9876. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  9877. Text(this.artist)
  9878. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  9879. .fontColor(Color.White)
  9880. .fontWeight(FontWeight.Bold)
  9881. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  9882. }
  9883. .justifyContent(FlexAlign.Start)
  9884. .zIndex(1)
  9885. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  9886. }
  9887. .margin({
  9888. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  9889. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  9890. top: this.isCoverOpacity() ? 0 : 20
  9891. })
  9892. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  9893. this.SingleLyricView()
  9894. }
  9895. if (this.isPhoneLan()) {
  9896. Column() {
  9897. this.playCenterView()
  9898. // this.playProgressView()
  9899. }
  9900. .position({ left: 28, bottom: 38 })
  9901. } else {
  9902. this.BottomControl()
  9903. }
  9904. }
  9905. .width(CommonConstants.FULL_PERCENT)
  9906. .clip(true)
  9907. }
  9908. //方形封面布局
  9909. @Builder
  9910. RectangleCoverView(){
  9911. Stack({alignContent:Alignment.Center}){
  9912. Image(this.cover)
  9913. .height(this.isHiCar()?(px2vp(this.windowHeight)*0.43):
  9914. this.isCoverOpacity()?(px2vp(this.windowHeight)*0.54):'auto')
  9915. .width(this.isHiCar()||this.isCoverOpacity()?'auto':this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '88%')
  9916. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  9917. .alt($r('app.media.alt'))
  9918. .margin({ right: 8, left: 8, top: 8 })
  9919. .aspectRatio(1)
  9920. .geometryTransition('cover') // 绑定标识符
  9921. .opacity(this.opacityValueImage)
  9922. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  9923. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  9924. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  9925. .clip(true)
  9926. .rotate({
  9927. x: 0,
  9928. y: 0,
  9929. z: 1,
  9930. angle: this.rotateAngle
  9931. })
  9932. .shadow({
  9933. radius: 22,
  9934. type: ShadowType.BLUR,
  9935. color: 'on_primary'
  9936. })
  9937. .onClick(() => {
  9938. this.isMusicBGCover = !this.isMusicBGCover
  9939. })
  9940. }
  9941. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  9942. // 设置左下角为缩放中心点
  9943. centerX: '0%',
  9944. centerY: '100%' })
  9945. }
  9946. @Builder
  9947. CicleCoverView() {
  9948. //圆形封面布局
  9949. Stack({alignContent:Alignment.Center}) {
  9950. Image($r('app.media.ic_music_disc'))
  9951. .width(245)
  9952. .height(245)
  9953. .margin({ right: 20, left: 20 ,top:this.isCoverRectangle||this.isLandscape?0:50 })
  9954. .aspectRatio(1)
  9955. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  9956. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  9957. .borderRadius('100%')
  9958. .align(Alignment.Center)
  9959. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  9960. .rotate({
  9961. angle: this.rotateAngle,
  9962. centerX: "50%",
  9963. centerY: "50%",
  9964. })
  9965. .animation({
  9966. duration: 100,
  9967. curve: Curve.Linear
  9968. })
  9969. .shadow({
  9970. radius: 22,
  9971. type: ShadowType.BLUR,
  9972. color: 'on_primary'
  9973. })
  9974. Image(this.cover)
  9975. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  9976. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 168))
  9977. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  9978. .alt($r('app.media.alt'))
  9979. // .geometryTransition('cover') // 绑定标识符
  9980. .margin({ right: 20, left: 20,
  9981. top:this.isCoverRectangle||this.isLandscape?0:50})
  9982. .aspectRatio(1)
  9983. .opacity(this.opacityValueImage)
  9984. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  9985. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  9986. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  9987. .align(Alignment.Center)//
  9988. .clip(true)
  9989. .shadow({
  9990. radius: 22,
  9991. type: ShadowType.BLUR,
  9992. color: 'on_primary'
  9993. })
  9994. .rotate({
  9995. x: 0,
  9996. y: 0,
  9997. z: 1,
  9998. angle: this.rotateAngle
  9999. })
  10000. .onClick(() => {
  10001. this.isMusicBGCover = !this.isMusicBGCover
  10002. })
  10003. // 唱针以左上角为点选择逆时针40度
  10004. Image($r('app.media.ic_music_cover_hand'))
  10005. .height(130)
  10006. .margin({ bottom: 200, top: 0 })
  10007. // .position({ x: this.windowWidth/2, y: 0 })
  10008. .align(Alignment.Top)
  10009. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  10010. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  10011. .visibility(this.isHiCar()||this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  10012. }
  10013. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  10014. // 设置左下角为缩放中心点
  10015. centerX: '0%',
  10016. centerY: '100%' })
  10017. }
  10018. @Builder
  10019. private musicNameInfo(isHidden: boolean) {
  10020. Row(){
  10021. Column({ space: 8 }) {
  10022. Text(this.name)
  10023. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 20)
  10024. .fontWeight(FontWeight.Bold)
  10025. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  10026. .maxLines(1)
  10027. .width('99%')
  10028. .textAlign(TextAlign.Start)
  10029. .fontColor(Color.White)
  10030. Text(this.artist + ' ' + this.currentSong?.album)
  10031. .fontSize(this.isCoverOpacity() ? 12 : 15)
  10032. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  10033. .fontColor(Color.White)
  10034. .textAlign(TextAlign.Start)
  10035. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  10036. .width('99%')
  10037. .maxLines(1)
  10038. }
  10039. .zIndex(1)
  10040. .layoutWeight(1)
  10041. .margin({ left: 15 })
  10042. Blank()
  10043. Row(){
  10044. Button({type:ButtonType.Circle,stateEffect:true}){
  10045. //添加或取消收藏
  10046. SymbolGlyph(Utility.getIsFav(this.favList,this.currentSong)?
  10047. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'))
  10048. .fontSize(22)
  10049. .fontColor([Color.White])
  10050. .alignSelf(ItemAlign.Center)
  10051. // .width(24)
  10052. .clickEffect({level:ClickEffectLevel.MIDDLE})
  10053. .aspectRatio(CommonConstants.ASPECT_RATIO)
  10054. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  10055. .onClick(async () => {
  10056. if(this.currentSong){
  10057. this.doFav(this.currentSong)
  10058. }
  10059. })
  10060. }
  10061. .margin({ left: 8,right:8 })
  10062. .backgroundColor(Color.Transparent)
  10063. .width(45)
  10064. .height(45)
  10065. }
  10066. }
  10067. .width(this.isLandscape?'83%':'90%')
  10068. .scale({ x: this.scaleValueText, y: this.scaleValueText }) // 添加缩放效果
  10069. .margin({ top:this.isCoverRectangle?10: 0 })
  10070. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  10071. }
  10072. @Builder
  10073. private PlayTitle() {
  10074. Row() {
  10075. Row() {
  10076. Image($r('app.media.ic_back_down'))
  10077. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  10078. .hitTestBehavior(HitTestMode.Transparent)
  10079. Text(this.name + ' ' + this.artist)
  10080. .fontColor(Color.White)
  10081. .fontSize($r('app.float.title_font_size'))
  10082. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  10083. .maxLines(1)
  10084. .visibility(Visibility.None)
  10085. .margin({ left: 2, right: 30 })
  10086. }
  10087. .layoutWeight(1)
  10088. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10089. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  10090. .onClick(() => {
  10091. this.setShowPlayFalse()
  10092. })
  10093. Column() {
  10094. AVCastPicker({
  10095. normalColor: Color.White,
  10096. onStateChange: this.onStateVastChange
  10097. })
  10098. .width(24)
  10099. .height(24)
  10100. }
  10101. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  10102. }
  10103. .width(PlayConstants.ROW_WIDTH)
  10104. }
  10105. @Builder
  10106. lyricSettingSheet(isPip: boolean) {
  10107. Scroll() {
  10108. this.lyricSetting(isPip)
  10109. }
  10110. .width('100%')
  10111. .height('100%')
  10112. }
  10113. @Builder
  10114. lyricSetting(isPip: boolean) {
  10115. Column() {
  10116. // 时间调节模块
  10117. if (!isPip) {
  10118. this.BuildTimeControls()
  10119. }
  10120. // 字号控制模块
  10121. this.BuildFontControls(isPip)
  10122. }
  10123. }
  10124. // 歌词时间偏移状态
  10125. @State timeOffset: number = 0.0
  10126. @State currentLyricColor: string = '#FFFFFF'
  10127. @State currentLyricColorPip: string = '#FFFFFF'
  10128. @State currentHighLightLyricColor: string = '#FF4081'
  10129. @State currentHighLightLyricColorPip: string = '#FF4081'
  10130. // 歌词字号状态
  10131. @State currentLyricSize: number = 20
  10132. @State currentLyricSizePip: number = 20
  10133. // 高亮歌词放大倍数
  10134. @State currentHightLyricSize: number = 1.2
  10135. @State currentHightLyricSizePip: number = 1.2
  10136. @State currentLyricLineSpace: number = 10
  10137. @State currentLyricLineSpacePip: number = 10
  10138. @State currentLyricAlignMode: number = 1
  10139. @State currentLyricAlignModePip: number = 1
  10140. @State blurDegree: number = 2
  10141. @State blurDegreePip: number = 2
  10142. @State isShowSelectColor: boolean = false
  10143. @State isShowHLSelectColor: boolean = false
  10144. @State isShowPipBgSelectColor: boolean = false
  10145. @State pipLyWidth: number = 330
  10146. @State pipLyHeight: number = 120
  10147. // 构建颜色选择器
  10148. @Builder
  10149. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  10150. Row({ space: 10 }) {
  10151. HSBColorPicker({
  10152. color: '#FFFFFF',
  10153. radius: 8,
  10154. layout: HSBColorPickerLayout.COLUMN,
  10155. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  10156. '#fa7105'],
  10157. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  10158. this.changeLyricColor(value, isPip, isBGPip)
  10159. })
  10160. .height(250)
  10161. .layoutWeight(1)
  10162. .padding(25)
  10163. }
  10164. .width('66%')
  10165. }
  10166. @State isOpenPip: boolean = false
  10167. @State pipBgIndex: number = 0
  10168. // 构建字号控制器
  10169. @Builder
  10170. BuildFontControls(isPip: boolean) {
  10171. Column() {
  10172. if (isPip) {
  10173. Column() {
  10174. Row() {
  10175. Text('悬浮歌词')
  10176. .margin({ left: 18 })
  10177. .fontSize(15)
  10178. .fontColor(Color.White)
  10179. .fontWeight(480)
  10180. .layoutWeight(1)
  10181. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  10182. .selectedColor(this.themeColor)
  10183. .switchPointColor(Color.White)
  10184. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10185. .margin({ right: 18 })
  10186. .onChange((checked: boolean) => {
  10187. this.isOpenPip = checked;
  10188. if (this.isOpenPip) {
  10189. this.startPip()
  10190. } else {
  10191. this.stopPip()
  10192. }
  10193. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  10194. })
  10195. .width(50)
  10196. .height(30);
  10197. }
  10198. .height(55)
  10199. }
  10200. .backgroundColor(Color.Transparent)
  10201. .borderRadius(15)
  10202. .margin({
  10203. left: 30,
  10204. right: 30,
  10205. top: 0,
  10206. bottom: 20
  10207. })
  10208. .padding(0)
  10209. .border({
  10210. color: Color.White,
  10211. width: 1.8
  10212. })
  10213. }else{
  10214. Column() {
  10215. Row() {
  10216. Text('单行歌词')
  10217. .margin({ left: 18 })
  10218. .fontSize(15)
  10219. .fontColor(Color.White)
  10220. .fontWeight(480)
  10221. .layoutWeight(1)
  10222. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  10223. .selectedColor(this.themeColor)
  10224. .switchPointColor(Color.White)
  10225. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10226. .margin({ right: 18 })
  10227. .onChange((checked: boolean) => {
  10228. this.isShowSingleLineLyric = checked;
  10229. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  10230. })
  10231. .width(50)
  10232. .height(30);
  10233. }
  10234. .height(55)
  10235. }
  10236. .backgroundColor(Color.Transparent)
  10237. .borderRadius(15)
  10238. .margin({
  10239. left: 30,
  10240. right: 30,
  10241. top: 10,
  10242. bottom: 10
  10243. })
  10244. .padding(0)
  10245. .border({
  10246. color: Color.White,
  10247. width: 1.8
  10248. })
  10249. }
  10250. Row() {
  10251. Text(`歌词居中:`)
  10252. .fontSize(14)
  10253. .fontColor(Color.White)
  10254. .margin({ left: 2 })
  10255. Row() {
  10256. ForEach(['居中', '居左'], (size: string, index: number) => {
  10257. Button(size)
  10258. .width(60)
  10259. .height(28)
  10260. .fontSize(12)
  10261. .fontColor('#FFFFFF')
  10262. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  10263. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  10264. .border({
  10265. color: (!isPip && this.currentLyricAlignMode === index) ||
  10266. (isPip && this.currentLyricAlignModePip === index) ?
  10267. '#007DFF' : '#DDDDDD',
  10268. width: 1.8
  10269. })
  10270. .onClick(() => {
  10271. this.setLyricAlignMode(index, isPip)
  10272. })
  10273. .margin({ left: 10, right: 8 })
  10274. })
  10275. }
  10276. .width('76%')
  10277. Blank()
  10278. }
  10279. .margin({
  10280. top: 10,
  10281. bottom: 10,
  10282. right: 20,
  10283. left: 20
  10284. })
  10285. if (isPip) {
  10286. Row() {
  10287. Text(`悬浮背景:`)
  10288. .fontSize(14)
  10289. .fontColor(Color.White)
  10290. Select([
  10291. { value: CommonConstants.PIP_LYRIC_BG[0] },
  10292. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  10293. .font({ size: 13, weight: FontWeight.Medium })
  10294. .fontColor(Color.White)
  10295. .margin({ left: 10 })
  10296. .selected(this.pipBgIndex)
  10297. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  10298. .onSelect(async (_index: number, text?: string | undefined) => {
  10299. this.pipBgIndex = _index
  10300. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  10301. if (this.pipBgIndex === 0) {
  10302. if (this.cover) {
  10303. this.pipBg = this.cover
  10304. } else {
  10305. this.pipBg = this.imageColor
  10306. }
  10307. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  10308. } else {
  10309. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  10310. }
  10311. })
  10312. Column() {
  10313. }
  10314. .backgroundColor(this.pipBg)
  10315. .margin({ left: 10, right: 10 })
  10316. .borderRadius(20)
  10317. .height(28)
  10318. .width(28)
  10319. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10320. Row() {
  10321. SymbolGlyph($r('sys.symbol.paintbrush'))
  10322. .fontColor([Color.White])
  10323. .effectStrategy(1)
  10324. Text(`选择颜色`)
  10325. .fontSize(13)
  10326. .margin({ left: 10 })
  10327. .fontColor(Color.White)
  10328. }
  10329. }
  10330. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  10331. .backgroundColor(Color.Transparent)
  10332. .border({
  10333. color: '#FFFFFF',
  10334. radius: 20,
  10335. width: 1.8
  10336. })
  10337. .height(36)
  10338. .width(110)
  10339. .onClick(() => {
  10340. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  10341. })
  10342. .bindPopup(this.isShowPipBgSelectColor, {
  10343. builder: this.SelectColor(false, isPip, true),
  10344. placement: Placement.Top,
  10345. mask: { color: '#33000000' },
  10346. enableArrow: false, //是否显示箭头
  10347. showInSubWindow: false,
  10348. onStateChange: (e) => {
  10349. if (!e.isVisible) {
  10350. this.isShowPipBgSelectColor = false
  10351. }
  10352. }
  10353. })
  10354. }
  10355. .width('76%')
  10356. .margin({ bottom: 5, right: 45, left: 20 })
  10357. }
  10358. if (!isPip) {
  10359. Row() {
  10360. Text(`高亮居中:`)
  10361. .fontSize(14)
  10362. .fontColor(Color.White)
  10363. Column() {
  10364. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  10365. .selectedColor(this.themeColor)
  10366. .switchPointColor(Color.White)
  10367. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10368. .onChange((checked: boolean) => {
  10369. this.isHightLightCenter = checked;
  10370. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  10371. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  10372. })
  10373. .width(50)
  10374. .height(30)
  10375. .alignSelf(ItemAlign.Start)
  10376. .margin({ left: 12 })
  10377. Blank()
  10378. }
  10379. .width('76%')
  10380. }
  10381. .margin({
  10382. left: 20,
  10383. right: 15,
  10384. top: 10,
  10385. bottom: 10
  10386. })
  10387. }
  10388. Row() {
  10389. Text(`歌词颜色:`)
  10390. .fontSize(14)
  10391. .fontColor(Color.White)
  10392. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  10393. .fontSize(15)
  10394. .fontColor(Color.White)
  10395. .margin({ left: 12, right: 12 })
  10396. Column() {
  10397. }
  10398. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  10399. .margin({ right: 12 })
  10400. .borderRadius(20)
  10401. .height(28)
  10402. .width(28)
  10403. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10404. Row() {
  10405. SymbolGlyph($r('sys.symbol.paintbrush'))
  10406. .fontColor([Color.White])
  10407. .effectStrategy(1)
  10408. Text(`选择颜色`)
  10409. .fontSize(13)
  10410. .margin({ left: 10 })
  10411. .fontColor(Color.White)
  10412. }
  10413. }
  10414. .backgroundColor(Color.Transparent)
  10415. .border({
  10416. color: '#FFFFFF',
  10417. radius: 20,
  10418. width: 1.8
  10419. })
  10420. .height(36)
  10421. .width(110)
  10422. .onClick(() => {
  10423. this.isShowSelectColor = !this.isShowSelectColor
  10424. })
  10425. .bindPopup(this.isShowSelectColor, {
  10426. builder: this.SelectColor(false, isPip),
  10427. placement: Placement.Top,
  10428. mask: { color: '#33000000' },
  10429. enableArrow: false, //是否显示箭头
  10430. showInSubWindow: false,
  10431. onStateChange: (e) => {
  10432. if (!e.isVisible) {
  10433. this.isShowSelectColor = false
  10434. }
  10435. }
  10436. })
  10437. }
  10438. .width('76%')
  10439. .margin({
  10440. top: 10,
  10441. bottom: 10,
  10442. right: 45,
  10443. left: 20
  10444. })
  10445. Row() {
  10446. Text(`高亮颜色:`)
  10447. .fontSize(14)
  10448. .fontColor(Color.White)
  10449. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  10450. .fontSize(15)
  10451. .fontColor(Color.White)
  10452. .margin({ left: 12, right: 12 })
  10453. Column() {
  10454. }
  10455. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  10456. .margin({ right: 12 })
  10457. .borderRadius(20)
  10458. .height(28)
  10459. .width(28)
  10460. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10461. Row() {
  10462. SymbolGlyph($r('sys.symbol.paintbrush'))
  10463. .fontColor([Color.White])
  10464. .effectStrategy(1)
  10465. Text(`选择颜色`)
  10466. .fontSize(13)
  10467. .margin({ left: 10 })
  10468. .fontColor(Color.White)
  10469. }
  10470. }
  10471. .backgroundColor(Color.Transparent)
  10472. .border({
  10473. color: '#FFFFFF',
  10474. radius: 20,
  10475. width: 1.8
  10476. })
  10477. .height(36)
  10478. .width(110)
  10479. .onClick(() => {
  10480. this.isShowHLSelectColor = !this.isShowHLSelectColor
  10481. })
  10482. .bindPopup(this.isShowHLSelectColor, {
  10483. builder: this.SelectColor(true, isPip),
  10484. placement: Placement.Top,
  10485. mask: { color: '#33000000' },
  10486. enableArrow: false, //是否显示箭头
  10487. showInSubWindow: false,
  10488. onStateChange: (e) => {
  10489. if (!e.isVisible) {
  10490. this.isShowHLSelectColor = false
  10491. }
  10492. }
  10493. })
  10494. }
  10495. .width('76%')
  10496. .margin({
  10497. top: 10,
  10498. bottom: 10,
  10499. right: 45,
  10500. left: 20
  10501. })
  10502. if (isPip) {
  10503. Row() {
  10504. Text(`显示宽度:`)
  10505. .fontSize(14)
  10506. .fontColor(Color.White)
  10507. Slider({
  10508. value: this.pipLyWidth,
  10509. min: 10,
  10510. max: 800,
  10511. step: 1,
  10512. style: SliderStyle.OutSet
  10513. })
  10514. .blockColor(this.themeColor)
  10515. .trackColor($r('app.color.speed_text_color'))
  10516. .selectedColor(Color.White)
  10517. .trackThickness(6)
  10518. .onChange((value: number) => {
  10519. this.pipLyWidth = value
  10520. if (this.pipController) {
  10521. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10522. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  10523. }
  10524. })
  10525. .width('76%')
  10526. }
  10527. .margin({
  10528. left: 20,
  10529. right: 15,
  10530. top: 5,
  10531. bottom: 5
  10532. })
  10533. Row() {
  10534. Text(`显示高度:`)
  10535. .fontSize(14)
  10536. .fontColor(Color.White)
  10537. Slider({
  10538. value: this.pipLyHeight,
  10539. min: 10,
  10540. max: 1000,
  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.pipLyHeight = value
  10550. if (this.pipController) {
  10551. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10552. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  10553. }
  10554. })
  10555. .width('76%')
  10556. }
  10557. .margin({
  10558. left: 20,
  10559. right: 15,
  10560. top: 5,
  10561. bottom: 5
  10562. })
  10563. }
  10564. Row() {
  10565. Text(`歌词字号:`)
  10566. .fontSize(14)
  10567. .fontColor(Color.White)
  10568. Slider({
  10569. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  10570. min: 12,
  10571. max: 30,
  10572. step: 0.1,
  10573. style: SliderStyle.OutSet
  10574. })
  10575. .blockColor(this.themeColor)
  10576. .trackColor($r('app.color.speed_text_color'))
  10577. .selectedColor(Color.White)
  10578. .trackThickness(6)
  10579. .onChange((value: number) => {
  10580. this.setLyricTextSize(value, isPip)
  10581. })
  10582. .width('76%')
  10583. }
  10584. .margin({
  10585. left: 20,
  10586. right: 15,
  10587. top: 5,
  10588. bottom: 5
  10589. })
  10590. Row() {
  10591. Text(`高亮倍数:`)
  10592. .fontSize(14)
  10593. .fontColor(Color.White)
  10594. Slider({
  10595. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  10596. min: 1,
  10597. max: 2,
  10598. step: 0.1,
  10599. style: SliderStyle.OutSet
  10600. })
  10601. .blockColor(this.themeColor)
  10602. .trackColor($r('app.color.speed_text_color'))
  10603. .selectedColor(Color.White)
  10604. .trackThickness(6)
  10605. .onChange((value: number) => {
  10606. this.setHighLyricTextSize(value, isPip)
  10607. })
  10608. .width('76%')
  10609. }
  10610. .margin({
  10611. left: 20,
  10612. right: 15,
  10613. top: 5,
  10614. bottom: 5
  10615. })
  10616. Row() {
  10617. Text(`歌词间隙:`)
  10618. .fontSize(14)
  10619. .fontColor(Color.White)
  10620. Slider({
  10621. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  10622. min: 0,
  10623. max: 100,
  10624. step: 1,
  10625. style: SliderStyle.OutSet
  10626. })
  10627. .blockColor(this.themeColor)
  10628. .trackColor($r('app.color.speed_text_color'))
  10629. .selectedColor(Color.White)
  10630. .trackThickness(6)
  10631. .onChange((value: number) => {
  10632. this.setLyricLineSpace(value, isPip)
  10633. })
  10634. .width('76%')
  10635. }
  10636. .margin({
  10637. left: 20,
  10638. right: 15,
  10639. top: 5,
  10640. bottom: 5
  10641. })
  10642. //取值间隔为100,默认为400,取值越大,字体越粗
  10643. Row() {
  10644. Text(`歌词字重:`)
  10645. .fontSize(14)
  10646. .fontColor(Color.White)
  10647. Slider({
  10648. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  10649. min: 100,
  10650. max: 900,
  10651. step: 100,
  10652. style: SliderStyle.OutSet
  10653. })
  10654. .blockColor(this.themeColor)
  10655. .trackColor($r('app.color.speed_text_color'))
  10656. .selectedColor(Color.White)
  10657. .trackThickness(6)
  10658. .onChange((value: number) => {
  10659. if (isPip) {
  10660. this.lyricTextWeightPip = value
  10661. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  10662. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  10663. } else {
  10664. this.lyricTextWeight = value
  10665. this.lyricController.setTextWeight(this.lyricTextWeight)
  10666. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  10667. }
  10668. })
  10669. .width('76%')
  10670. }
  10671. .margin({
  10672. left: 20,
  10673. right: 15,
  10674. top: 5,
  10675. bottom: 5
  10676. })
  10677. if (!isPip) {
  10678. Row() {
  10679. Text(`歌词模糊:`)
  10680. .fontSize(14)
  10681. .fontColor(Color.White)
  10682. Slider({
  10683. value: isPip ? this.blurDegreePip : this.blurDegree,
  10684. min: 0,
  10685. max: 5,
  10686. step: 0.1,
  10687. style: SliderStyle.OutSet
  10688. })
  10689. .blockColor(this.themeColor)
  10690. .trackColor($r('app.color.speed_text_color'))
  10691. .selectedColor(Color.White)
  10692. .trackThickness(6)
  10693. .onChange((value: number) => {
  10694. this.setBlurDegree(value, isPip)
  10695. })
  10696. .width('76%')
  10697. }
  10698. .margin({
  10699. left: 20,
  10700. right: 15,
  10701. top: 5,
  10702. bottom: 15
  10703. })
  10704. }
  10705. Row() {
  10706. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  10707. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  10708. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  10709. }
  10710. .justifyContent(FlexAlign.Center)
  10711. .margin({ top: 3, bottom: 10 })
  10712. }
  10713. }
  10714. private setBlurDegree(index: number, isPip: boolean) {
  10715. if (isPip) {
  10716. this.blurDegreePip = index
  10717. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  10718. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  10719. } else {
  10720. this.blurDegree = index
  10721. this.lyricController.setBlurDegree(this.blurDegree)
  10722. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  10723. }
  10724. }
  10725. private setLyricAlignMode(index: number, isPip: boolean) {
  10726. if (isPip) {
  10727. this.currentLyricAlignModePip = index
  10728. if (this.currentLyricAlignModePip === 1) {
  10729. this.lyricControllerXF.setAlignMode("left")
  10730. } else {
  10731. this.lyricControllerXF.setAlignMode("center")
  10732. }
  10733. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  10734. } else {
  10735. this.currentLyricAlignMode = index
  10736. if (this.currentLyricAlignMode === 1) {
  10737. this.lyricController.setAlignMode("left")
  10738. } else {
  10739. this.lyricController.setAlignMode("center")
  10740. }
  10741. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  10742. }
  10743. }
  10744. private setLyricTextSize(index: number, isPip: boolean) {
  10745. if (isPip) {
  10746. this.currentLyricSizePip = index
  10747. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  10748. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  10749. } else {
  10750. this.currentLyricSize = index
  10751. this.lyricController.setTextSize(this.currentLyricSize)
  10752. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  10753. }
  10754. }
  10755. private setHighLyricTextSize(scale: number, isPip: boolean) {
  10756. if (isPip) {
  10757. this.currentHightLyricSizePip = scale
  10758. this.lyricControllerXF
  10759. .setHighlightScale(this.currentHightLyricSizePip)
  10760. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  10761. } else {
  10762. this.currentHightLyricSize = scale
  10763. this.lyricController
  10764. .setHighlightScale(this.currentHightLyricSize)
  10765. PreferencesUtil.putSync('HighLyricTextSize', scale)
  10766. }
  10767. }
  10768. private setLyricLineSpace(index: number, isPip: boolean) {
  10769. if (isPip) {
  10770. this.currentLyricLineSpacePip = index
  10771. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  10772. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  10773. } else {
  10774. this.currentLyricLineSpace = index
  10775. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  10776. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  10777. }
  10778. }
  10779. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  10780. LogUtil.info('onecold isBG = ' + isBG)
  10781. if (isBG) { //如果是设置悬浮背景
  10782. this.pipBg = color
  10783. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  10784. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  10785. return
  10786. }
  10787. if (isPip) {
  10788. this.currentLyricColorPip = color
  10789. this.lyricControllerXF
  10790. .setTextColor(this.currentLyricColorPip)
  10791. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  10792. } else {
  10793. this.currentLyricColor = color
  10794. this.lyricController
  10795. .setTextColor(this.currentLyricColor)
  10796. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  10797. }
  10798. }
  10799. private changeLyricHightLightColor(color: string, isPip: boolean) {
  10800. if (isPip) {
  10801. this.currentHighLightLyricColorPip = color
  10802. this.lyricControllerXF
  10803. .setHighlightColor(this.currentHighLightLyricColorPip)
  10804. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  10805. } else {
  10806. this.currentHighLightLyricColor = color
  10807. this.lyricController
  10808. .setHighlightColor(this.currentHighLightLyricColor)
  10809. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  10810. }
  10811. }
  10812. // 构建时间控制器
  10813. @Builder
  10814. BuildTimeControls() {
  10815. Column() {
  10816. // 时间显示
  10817. Text(this.getTimeText())
  10818. .fontSize(18)
  10819. .fontColor(Color.White)
  10820. .margin({ bottom: 10 })
  10821. Row() {
  10822. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  10823. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  10824. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  10825. }
  10826. .justifyContent(FlexAlign.Center)
  10827. }
  10828. .margin({ top: 12, bottom: 8 })
  10829. }
  10830. // 精度按钮组件
  10831. @Builder
  10832. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  10833. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10834. Column() {
  10835. Image(icon)
  10836. .width(28)
  10837. .margin({ bottom: 5 })
  10838. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  10839. Text(label)
  10840. .fontSize(12)
  10841. .fontColor('#FFFFFF')
  10842. }
  10843. }
  10844. .backgroundColor(Color.Transparent)
  10845. .enabled(!this.isButtonDisabled(step))
  10846. .onClick(() => this.handlePrecisionAdjust(step))
  10847. .padding(5)
  10848. .width(66)
  10849. .height(66)
  10850. .margin({ left: 18, right: 18 })
  10851. .border({
  10852. color: '#FFFFFF',
  10853. width: 1.8
  10854. })
  10855. }
  10856. private handlePrecisionAdjust(step: number) {
  10857. if (step === 0) {
  10858. this.timeOffset = 0
  10859. return
  10860. }
  10861. // 精度处理:保留1位小数
  10862. const newOffset = Number((this.timeOffset + step).toFixed(5))
  10863. // 边界保护(±15.0秒)
  10864. if (newOffset < -30.0 || newOffset > 30.0) {
  10865. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  10866. return
  10867. }
  10868. // 状态更新
  10869. this.timeOffset = newOffset
  10870. }
  10871. // 按钮禁用逻辑
  10872. private isButtonDisabled(step: number): boolean {
  10873. const futureOffset = this.timeOffset + step
  10874. return (futureOffset < -30.0) || (futureOffset > 30.0)
  10875. }
  10876. // 时间显示文本升级
  10877. private getTimeText(): string {
  10878. const absValue = Math.abs(this.timeOffset)
  10879. return this.timeOffset === 0
  10880. ? '歌词时间已重置'
  10881. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  10882. }
  10883. // 导入 本地歌词 搜索歌词
  10884. @Builder
  10885. pushLyricButton(icon: Resource, step: number, label: string) {
  10886. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10887. Row() {
  10888. Image(icon)
  10889. .width(14)
  10890. .margin({ left: 13 })
  10891. Text(label)
  10892. .fontSize(12)
  10893. .margin({ left: 6 })
  10894. .fontColor('#FFFFFF')
  10895. }
  10896. }
  10897. .onClick(() => {
  10898. switch (step) {
  10899. case 0:
  10900. this.callFilePickerSelectFileForLyric()
  10901. break;
  10902. case 1:
  10903. //判断有没有设置api
  10904. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  10905. this.isLyricSetting = false
  10906. this.showTipsDialog()
  10907. return
  10908. }
  10909. if (StrUtil.isNotEmpty(this.videoUrl)) {
  10910. ToastUtil.showToast('正在获取')
  10911. this.isLyricSetting = false
  10912. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  10913. this.initLyric(lyricPath, true);
  10914. }
  10915. break;
  10916. }
  10917. })
  10918. .padding(5)
  10919. .width(110)
  10920. .backgroundColor(Color.Transparent)
  10921. .height(40)
  10922. .margin({ left: 6, right: 6 })
  10923. .border({
  10924. color: '#FFFFFF',
  10925. radius: 20,
  10926. width: 1.8
  10927. })
  10928. }
  10929. showVipDialog() {
  10930. DialogHelper.showCustomContentDialog({
  10931. dialogId: 'vip',
  10932. title: "友情提示",
  10933. autoCancel: false, //点击遮障层时,不关闭弹窗
  10934. backCancel: true, //点击返回键,不关闭弹窗
  10935. contentBuilder: () => {
  10936. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  10937. },
  10938. buttons: [],
  10939. })
  10940. }
  10941. //去赞助的自定义内容
  10942. @Builder
  10943. customVipBuilder(content: string) {
  10944. Column() {
  10945. Text(content)
  10946. .fontColor(Color.Gray)
  10947. .fontSize(16)
  10948. .alignSelf(ItemAlign.Start)
  10949. .margin({ bottom: 15 })
  10950. .fontSize(16)
  10951. Row() {
  10952. Button('取消')
  10953. .fontColor(Color.White)
  10954. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  10955. .height(50)
  10956. .layoutWeight(1)
  10957. .stateEffect(true)
  10958. .margin({ right: 6 })
  10959. .onClick(() => {
  10960. DialogHelper.closeDialog('vip'); //关闭弹框
  10961. })
  10962. Button('开通')
  10963. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  10964. .layoutWeight(1)
  10965. .height(50)
  10966. .backgroundColor(this.themeColor)
  10967. .stateEffect(true)
  10968. .margin({ left: 6 })
  10969. .onClick(() => {
  10970. DialogHelper.closeDialog('vip'); //关闭弹框
  10971. this.isShowPlay = false
  10972. this.mType = 1 //跳转到用户中心
  10973. // router.pushUrl({
  10974. // url: 'pages/VipPage'
  10975. // }, router.RouterMode.Single);
  10976. })
  10977. }
  10978. }
  10979. .width("100%")
  10980. .padding(10)
  10981. }
  10982. showTipsDialog() {
  10983. DialogHelper.showCustomContentDialog({
  10984. dialogId: 'tips',
  10985. title: "友情提示",
  10986. autoCancel: false, //点击遮障层时,不关闭弹窗
  10987. backCancel: true, //点击返回键,不关闭弹窗
  10988. contentBuilder: () => {
  10989. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  10990. },
  10991. buttons: [],
  10992. })
  10993. }
  10994. @Builder
  10995. customTipsBuilder(content: string) {
  10996. Column() {
  10997. Text(content)
  10998. .fontColor(Color.Gray)
  10999. .fontSize(16)
  11000. .alignSelf(ItemAlign.Start)
  11001. .margin({ bottom: 15 })
  11002. .fontSize(16)
  11003. Row() {
  11004. Button('取消')
  11005. .fontColor(Color.White)
  11006. .backgroundColor(this.themeColor)
  11007. .height(50)
  11008. .layoutWeight(1)
  11009. .stateEffect(true)
  11010. .margin({ right: 6 })
  11011. .onClick(() => {
  11012. DialogHelper.closeDialog('tips'); //关闭弹框
  11013. })
  11014. Button('跳转')
  11015. .fontColor(Color.White)//
  11016. .layoutWeight(1)
  11017. .height(50)
  11018. .backgroundColor(this.themeColor)
  11019. .stateEffect(true)
  11020. .margin({ left: 6 })
  11021. .onClick(() => {
  11022. DialogHelper.closeDialog('tips'); //关闭弹框
  11023. this.isShowEdit = false
  11024. this.longItemFilePath = ''
  11025. // if(this.isGridMusic&&!this.isShowPlay){
  11026. // this.longItemFilePath== ''
  11027. // }else{
  11028. // this.isShowEdit = false
  11029. // }
  11030. this.isShowMoreView = false;
  11031. this.isShowPlay = false
  11032. this.mType = 4
  11033. // router.pushUrl({
  11034. // url: 'pages/SettingPage'
  11035. // }, router.RouterMode.Single);
  11036. })
  11037. }
  11038. }
  11039. .width("100%")
  11040. .padding(10)
  11041. }
  11042. @Builder
  11043. PlayMoreSheet() {
  11044. Column() {
  11045. this.MoreList()
  11046. }
  11047. .width('100%')
  11048. .height('100%')
  11049. }
  11050. @Builder
  11051. MoreList() {
  11052. Scroll() {
  11053. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  11054. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  11055. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  11056. Row() {
  11057. if (more.id === 3&&this.currentSong) {
  11058. Image(more.image)
  11059. .width(24)
  11060. .height(24)
  11061. .margin({ left: 10, right: 10 })
  11062. Text(more.title)
  11063. .fontSize(16)
  11064. .fontColor(Color.White)
  11065. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  11066. height: '99%',
  11067. dragBar: true,
  11068. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11069. showClose: true,
  11070. blurStyle: BlurStyle.Thin,
  11071. backgroundColor: Color.Transparent,
  11072. title: { title: '歌曲信息' }
  11073. })
  11074. } else if (more.id === 15 && this.currentSong) { //编辑标签
  11075. Image(more.image)
  11076. .width(24)
  11077. .height(24)
  11078. .margin({ left: 10, right: 10 })
  11079. Text(more.title)
  11080. .fontSize(16)
  11081. .fontColor(Color.White)
  11082. } else if (more.id === 5) { //定时关闭
  11083. Image(more.image)
  11084. .width(24)
  11085. .height(24)
  11086. .margin({ left: 10, right: 10 })
  11087. Text(more.title)
  11088. .fontSize(16)
  11089. .fontColor(Color.White)
  11090. .onClick(() => {
  11091. this.doMore(more.id)
  11092. })
  11093. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  11094. height: this.isCoverOpacity() ? '95%' : '95%',
  11095. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11096. dragBar: true,
  11097. showClose: true,
  11098. title: { title: $r('app.string.time_close') }
  11099. })
  11100. } else if (more.id === 2) { //歌词设置
  11101. Image(more.image)
  11102. .width(24)
  11103. .height(24)
  11104. .margin({ left: 10, right: 10 })
  11105. Text(more.title)
  11106. .fontSize(16)
  11107. .fontColor(Color.White)
  11108. } else if (more.id === 16) { //悬浮歌词设置
  11109. Image(more.image)
  11110. .width(24)
  11111. .height(24)
  11112. .margin({ left: 10, right: 10 })
  11113. Text(more.title)
  11114. .fontSize(16)
  11115. .fontColor(Color.White)
  11116. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  11117. height: '99%',
  11118. dragBar: true,
  11119. preferType: SheetType.CENTER,
  11120. showClose: true,
  11121. blurStyle: BlurStyle.Thin,
  11122. backgroundColor: Color.Transparent,
  11123. title: { title: '悬浮歌词' }
  11124. })
  11125. } else if (more.id === 11) {
  11126. Image(more.image)
  11127. .width(24)
  11128. .height(24)
  11129. .margin({ left: 10, right: 10 })
  11130. Text(more.title)
  11131. .fontSize(16)
  11132. .fontColor(Color.White)
  11133. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  11134. height: this.isCoverOpacity() ? '95%' : '60%',
  11135. dragBar: true,
  11136. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11137. showClose: true,
  11138. blurStyle: BlurStyle.Thin,
  11139. backgroundColor: Color.Transparent,
  11140. title: { title: '跳过头尾' }
  11141. })
  11142. } else if (more.id === 12) { //投播
  11143. AVCastPicker({
  11144. customPicker: (): void => this.TPImageBuilder(more),
  11145. onStateChange: (state) => {
  11146. if (state == AVCastPickerState.STATE_APPEARING) {
  11147. console.log(' The picker starts showing.');
  11148. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  11149. console.log(' The picker finishes presenting.');
  11150. }
  11151. },
  11152. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  11153. sessionType: 'video'
  11154. })
  11155. .id('AVCastPicker')
  11156. } else {
  11157. Image(more.image)
  11158. .width(24)
  11159. .height(24)
  11160. .fillColor(Color.White)
  11161. .margin({ left: 10, right: 10 })
  11162. .onClick(() => {
  11163. this.doMore(more.id)
  11164. })
  11165. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  11166. .fontSize(16)
  11167. .fontColor(Color.White)
  11168. .onClick(() => {
  11169. this.doMore(more.id)
  11170. })
  11171. Select([//倍速
  11172. { value: '0.25x' },
  11173. { value: '0.5x' },
  11174. { value: '0.75x' },
  11175. { value: '1x' },
  11176. { value: '1.25x' },
  11177. { value: '1.5x' },
  11178. { value: '1.75x' },
  11179. { value: '2x' },
  11180. { value: '3x' }])
  11181. .font({ size: 16, weight: FontWeight.Medium })
  11182. .fontColor($r('sys.color.white'))
  11183. .margin({ left: 25 })
  11184. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  11185. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  11186. .value(Utility.optimizedFormat(this.playSpeed))
  11187. .onSelect(async (_index: number, text?: string | undefined) => {
  11188. let speed = parseFloat(text?.replace('x', '') || '1');
  11189. if (!CommonConstants.video_speed_list.includes(speed)) {
  11190. speed = 1;
  11191. }
  11192. this.playSpeed = speed
  11193. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  11194. })
  11195. Slider({
  11196. value: this.volume,
  11197. min: 0,
  11198. max: 1,
  11199. step: 0.1,
  11200. style: SliderStyle.OutSet
  11201. })
  11202. .margin({ left: 18, right: 8 })
  11203. .blockColor(this.themeColor)
  11204. .trackColor($r('app.color.speed_text_color'))
  11205. .selectedColor(Color.White)
  11206. .trackThickness(9)
  11207. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  11208. .onChange((value: number) => {
  11209. this.volume = value;
  11210. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  11211. PreferencesUtil.putSync('DefalutVolume',this.volume)
  11212. })
  11213. .layoutWeight(1)
  11214. Blank()
  11215. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  11216. .selectedColor(this.themeColor)
  11217. .switchPointColor(Color.White)
  11218. .margin({ right: 15 })
  11219. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11220. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  11221. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11222. if (more.id == 6) {
  11223. this.isMusicMemoryPlay = checked;
  11224. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  11225. if (this.isMusicMemoryPlay) {
  11226. ToastUtil.showToast('记忆播放已开启')
  11227. } else {
  11228. ToastUtil.showToast('记忆播放已关闭')
  11229. }
  11230. }
  11231. })
  11232. .width(48)
  11233. .height(24);
  11234. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  11235. .selectedColor(this.themeColor)
  11236. .switchPointColor(Color.White)
  11237. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11238. .margin({ right: 15 })
  11239. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  11240. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11241. if (more.id == 7) {
  11242. this.isMusicBGCover = checked;
  11243. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  11244. if (this.isMusicBGCover) {
  11245. ToastUtil.showToast('播放背景随音乐封面已开启')
  11246. } else {
  11247. ToastUtil.showToast('播放背景随音乐封面已关闭')
  11248. }
  11249. }
  11250. })
  11251. .width(48)
  11252. .height(24);
  11253. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  11254. .selectedColor(this.themeColor)
  11255. .switchPointColor(Color.White)
  11256. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11257. .margin({ right: 15 })
  11258. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  11259. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11260. if (more.id == 8) {
  11261. this.isSavePlayMode = checked;
  11262. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  11263. if (this.isSavePlayMode) {
  11264. ToastUtil.showToast('保存播放模式已开启')
  11265. } else {
  11266. ToastUtil.showToast('保存播放模式已关闭')
  11267. }
  11268. }
  11269. })
  11270. .width(48)
  11271. .height(24);
  11272. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  11273. .selectedColor(this.themeColor)
  11274. .switchPointColor(Color.White)
  11275. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11276. .margin({ right: 15 })
  11277. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  11278. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11279. if (more.id == 13) {
  11280. this.isCoverRectangle = checked;
  11281. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  11282. if (this.isCoverRectangle) {
  11283. ToastUtil.showToast('封面方形已开启')
  11284. this.animationRoFun()
  11285. } else {
  11286. ToastUtil.showToast('封面圆形已开启')
  11287. this.animationRoFun()
  11288. }
  11289. }
  11290. })
  11291. .width(48)
  11292. .height(24);
  11293. Toggle({ type: ToggleType.Switch, isOn: this.isShowBgLiuGUANG })
  11294. .selectedColor(this.themeColor)
  11295. .switchPointColor(Color.White)
  11296. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11297. .margin({ right: 15 })
  11298. .visibility(more.id == 21 ? Visibility.Visible : Visibility.None)
  11299. .onChange((checked: boolean) => { // 是否开启背景流光效果
  11300. if (more.id == 21) {
  11301. this.isShowBgLiuGUANG = checked;
  11302. PreferencesUtil.putSync('isShowBgLiuGUANG',this.isShowBgLiuGUANG)
  11303. }
  11304. })
  11305. .width(48)
  11306. .height(24);
  11307. }
  11308. }
  11309. .width('100%')
  11310. .height(45)
  11311. .padding(15)
  11312. .backgroundColor(Color.Transparent)
  11313. .borderRadius(12)
  11314. .margin({ bottom: 6 })
  11315. }
  11316. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  11317. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  11318. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  11319. .backgroundColor(Color.Transparent)
  11320. .onClick(() => {
  11321. this.doMore(more.id)
  11322. })
  11323. });
  11324. }
  11325. .width('100%')
  11326. .padding(16)
  11327. }.margin({ bottom: 18 })
  11328. }
  11329. @Builder
  11330. TPImageBuilder(more: MoreItem): void {
  11331. Row() {
  11332. Image($r('app.media.tuoping'))
  11333. .width(22)
  11334. .height(22)
  11335. .margin({ left: 10, right: 10 })
  11336. Text(more.title)
  11337. .fontSize(16)
  11338. .fontColor(Color.White)
  11339. }
  11340. .width('100%')
  11341. .layoutWeight(1)
  11342. .alignItems(VerticalAlign.Center)
  11343. .justifyContent(FlexAlign.Start)
  11344. }
  11345. private moreItems: MoreItem[] = [
  11346. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  11347. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  11348. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  11349. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  11350. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  11351. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  11352. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  11353. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  11354. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  11355. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  11356. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  11357. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  11358. { id: 4, image: $r('app.media.share2'), title: '分享' },
  11359. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  11360. // { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  11361. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  11362. { id : 21, image: $r('app.media.kp_music'), title: '开启背景流光' },
  11363. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  11364. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  11365. ];
  11366. @State isShowBgLiuGUANG: boolean = false;
  11367. @State isShowMoreView: boolean = false;
  11368. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  11369. @State isShowTimeCloseMore: boolean = false
  11370. @State isShowDetailMore: boolean = false
  11371. @State isMusicBGCover: boolean = true
  11372. @State isSavePlayMode: boolean = true
  11373. @State isLyricSetting: boolean = false
  11374. @State isJumpSetting: boolean = false
  11375. @State isShowEdit: boolean = false
  11376. @State showPipLyric: boolean = false
  11377. async setRingTone() {
  11378. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  11379. return
  11380. }
  11381. // 确定后的逻辑
  11382. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  11383. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  11384. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  11385. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  11386. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  11387. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  11388. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  11389. , this.videoUrl, this.name).then(res => {
  11390. LogUtil.info('onecold setFlag :' + res);
  11391. });
  11392. }
  11393. doMore(moreId: number) {
  11394. switch (moreId) {
  11395. case 2: //歌词
  11396. this.isLyricSetting = !this.isLyricSetting;
  11397. this.isShowMoreView = false
  11398. break;
  11399. case 3: //详情
  11400. this.isShowDetailMore = !this.isShowDetailMore;
  11401. break;
  11402. case 4: //分享
  11403. if (this.currentSong !== undefined) {
  11404. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  11405. }
  11406. this.isShowMoreView = false
  11407. break;
  11408. case 5: //定时关闭
  11409. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  11410. break;
  11411. case 10: //设为铃声
  11412. this.setRingTone()
  11413. this.isShowMoreView = false
  11414. break;
  11415. case 11: //跳过头尾
  11416. this.isJumpSetting = !this.isJumpSetting;
  11417. break;
  11418. case 13: //倍速
  11419. break;
  11420. case 14: //搜索封面
  11421. if (this.currentSong !== undefined) {
  11422. this.doSearchCover(this.currentSong)
  11423. }
  11424. this.isShowMoreView = false
  11425. break;
  11426. case 15: //编辑标签
  11427. this.initEditFields(this.currentSong)
  11428. this.tempLyricContent = this.lyricContent
  11429. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  11430. this.lyricConStr = this.tempLyricContent
  11431. }
  11432. this.isShowEdit = !this.isShowEdit;
  11433. break;
  11434. case 16: //悬浮歌词
  11435. this.showPipLyric = !this.showPipLyric;
  11436. break;
  11437. case 17: //横屏模式
  11438. if (this.isLandscape) {
  11439. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  11440. } else {
  11441. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  11442. }
  11443. this.isShowMoreView = false
  11444. break;
  11445. case 20://AB循环
  11446. this.isABSheet = !this.isABSheet
  11447. break;
  11448. }
  11449. }
  11450. //AB循环
  11451. @State isOpenAB:boolean = false
  11452. @State jumpATime:number = 0
  11453. @State jumpBTime:number = 0
  11454. @State isABSheet:boolean = false
  11455. @Builder
  11456. ABLoopSheet() {
  11457. ABLoopComptent({
  11458. jumpATime:this.jumpATime,
  11459. jumpBTime:this.jumpBTime,
  11460. onClickAItem: async ()=>{
  11461. if(this.mIjkMediaPlayer){
  11462. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  11463. }
  11464. },
  11465. onClickBItem: async ()=>{
  11466. if(this.mIjkMediaPlayer){
  11467. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  11468. if(this.jumpBTime<=this.jumpATime){
  11469. ToastUtil.showToast('设置B点时间不能小于A点时间')
  11470. this.jumpBTime = 0
  11471. }
  11472. }
  11473. },
  11474. onCancleButtonClick: async ()=>{
  11475. this.isOpenAB = false
  11476. this.isABSheet = false
  11477. },
  11478. onStartButtonClick: async ()=>{
  11479. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  11480. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  11481. return
  11482. }
  11483. this.isABSheet = false
  11484. this.startABLoop()
  11485. },
  11486. })
  11487. }
  11488. //开始AB循环
  11489. startABLoop(){
  11490. if(this.mIjkMediaPlayer){
  11491. this.seekTo(this.jumpATime+'')
  11492. this.isOpenAB = true
  11493. }
  11494. }
  11495. /**
  11496. * 切换横竖屏
  11497. *
  11498. */
  11499. setOrientation(orientation: number) {
  11500. this.windowClass.setPreferredOrientation(orientation).then(() => {
  11501. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  11502. }).catch((err: BusinessError) => {
  11503. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  11504. });
  11505. }
  11506. /**
  11507. * 画中画功能(悬浮歌词功能)
  11508. *
  11509. */
  11510. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  11511. pipController?: PiPWindow.PiPController;
  11512. navigationId: string = '';
  11513. @State curState: string = '';
  11514. @State curError: ResourceStr = '';
  11515. @State pipBg: string = '#E8E8E8'
  11516. @State buttonAction: string = '';
  11517. //开启画中画功能
  11518. async startPip() {
  11519. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  11520. if (!this.pipController) {
  11521. await this.createPipController();
  11522. }
  11523. if (!this.pipController) {
  11524. Logger.info(`[${TAG}] pipController create error`);
  11525. return;
  11526. }
  11527. await this.pipController.startPiP();
  11528. }
  11529. async stopPip() {
  11530. if (!this.pipController) {
  11531. Logger.info(`[${TAG}] pipController is not exist`);
  11532. return;
  11533. }
  11534. this.isOpenPip = false
  11535. await this.pipController.stopPiP();
  11536. }
  11537. async createPipController() {
  11538. this.pipController = await PiPWindow.create({
  11539. context: getContext(this),
  11540. componentController: this.xcomponentController,
  11541. navigationId: this.navigationId,
  11542. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  11543. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  11544. customUIController: this.nodeController,
  11545. });
  11546. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  11547. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  11548. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  11549. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  11550. this.onStateChange(state, reason);
  11551. });
  11552. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  11553. this.onActionEvent(event, status);
  11554. });
  11555. }
  11556. destroyPipController() {
  11557. if (!this.pipController) {
  11558. return;
  11559. }
  11560. this.pipController.off('stateChange');
  11561. this.pipController.off('controlPanelActionEvent');
  11562. this.pipController = undefined;
  11563. }
  11564. onStateChange(state: PiPWindow.PiPState, reason: string) {
  11565. switch (state) {
  11566. case PiPWindow.PiPState.ABOUT_TO_START:
  11567. this.curState = 'ABOUT_TO_START';
  11568. this.curError = $r('app.string.current_error_hint');
  11569. break;
  11570. case PiPWindow.PiPState.STARTED:
  11571. this.curState = 'STARTED';
  11572. this.curError = $r('app.string.current_error_hint');
  11573. break;
  11574. case PiPWindow.PiPState.ABOUT_TO_STOP:
  11575. this.curState = 'ABOUT_TO_STOP';
  11576. this.curError = $r('app.string.current_error_hint');
  11577. break;
  11578. case PiPWindow.PiPState.STOPPED:
  11579. this.curState = 'STOPPED';
  11580. this.curError = $r('app.string.current_error_hint');
  11581. this.stopPip()
  11582. this.destroyPipController()
  11583. break;
  11584. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  11585. this.curState = 'ABOUT_TO_RESTORE';
  11586. this.curError = $r('app.string.current_error_hint');
  11587. break;
  11588. case PiPWindow.PiPState.ERROR:
  11589. this.curState = 'ERROR';
  11590. this.curError = reason;
  11591. break;
  11592. default:
  11593. break;
  11594. }
  11595. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  11596. }
  11597. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  11598. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  11599. switch (event) {
  11600. case 'playbackStateChanged':
  11601. if (status === 0) {
  11602. this.pause();
  11603. } else {
  11604. console.info('onecold startPlayOrResumePlay 9869')
  11605. this.startPlayOrResumePlay();
  11606. }
  11607. break;
  11608. case 'nextVideo':
  11609. // 切换到下一个视频
  11610. this.playNext().catch(() => {
  11611. Logger.error('heanup onActionEvent playNext', `播放下一首失败`);
  11612. });
  11613. break;
  11614. case 'previousVideo':
  11615. // 切换到上一个视频
  11616. this.playPrevious().catch(() => {
  11617. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败`);
  11618. });
  11619. break;
  11620. case 'previousVideo':
  11621. // 切换到上一个视频
  11622. this.playPrevious().catch(() => {
  11623. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败:`);
  11624. });
  11625. break;
  11626. default:
  11627. }
  11628. this.buttonAction = event + `-status:${status}`;
  11629. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  11630. }
  11631. /**
  11632. * 画中画功能(悬浮歌词功能)结束
  11633. *
  11634. */
  11635. async doSearchCover(item: VideoItem,title?:string,artist?:string): Promise<string> {
  11636. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  11637. this.isShowMoreView = false;
  11638. this.showTipsDialog();
  11639. return ''; // Return empty string when no API is configured
  11640. }
  11641. if (!item) {
  11642. return ''; // Return empty string if item is undefined
  11643. }
  11644. const titleS = title||item?.name || '';
  11645. const artistS = artist||item?.artist || ''; // Use empty string if artist is missing
  11646. return this.searchCover(item, titleS, artistS); // Await is not needed here as we return the promise directly
  11647. }
  11648. /**
  11649. *api搜索封面
  11650. *item,根据title和artist
  11651. */
  11652. searchCover(item: VideoItem, title: string, artist: string): Promise<string> {
  11653. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  11654. LogUtil.debug("onecold res =" + res);
  11655. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  11656. if (item.filePath == this.currentSong?.filePath) {
  11657. this.cover = res;
  11658. if (this.currentSong) {
  11659. this.currentSong.pixelMapPath = res;
  11660. }
  11661. }
  11662. // Update pixel map path but always return res regardless of success
  11663. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  11664. if (success) {
  11665. this.doUpdateData();
  11666. console.log("onecold 更新音乐封面成功,数据库已同步");
  11667. } else {
  11668. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  11669. }
  11670. // Note: We don't resolve/reject here because we already returned res
  11671. });
  11672. LogUtil.debug("onecold this.cover =" + this.cover);
  11673. }
  11674. return res; // Always return res regardless of updatePixelMapPath result
  11675. });
  11676. }
  11677. @State jumpTopTime: number = 0
  11678. @State jumpEndTime: number = 0
  11679. @State isOpenJump: boolean = false
  11680. @Builder
  11681. JumpTopEndSheet() {
  11682. Scroll() {
  11683. Column() {
  11684. Column() {
  11685. Text('仅对本播放列表有效')
  11686. .fontSize(16)
  11687. .fontColor($r('app.color.text_color'))
  11688. // 跳过头尾
  11689. Column() {
  11690. Row() {
  11691. Text('跳过片头:')
  11692. .fontSize(16)
  11693. .fontColor($r('app.color.text_color'))
  11694. Text(this.jumpTopTime + 's')
  11695. .fontSize(16)
  11696. .fontColor($r('app.color.text_color'))
  11697. }
  11698. .margin({ bottom: 5 })
  11699. Row() {
  11700. Slider({
  11701. value: this.jumpTopTime,
  11702. min: 0,
  11703. max: 120,
  11704. step: 1,
  11705. style: SliderStyle.OutSet
  11706. })
  11707. .blockColor(this.themeColor)
  11708. .trackColor($r('app.color.speed_text_color'))
  11709. .selectedColor(Color.White)
  11710. .trackThickness(8)
  11711. .onChange((value: number) => {
  11712. this.jumpTopTime = value;
  11713. })
  11714. .width('85%')
  11715. }
  11716. .alignItems(VerticalAlign.Top)
  11717. }
  11718. .margin({ top: 10, bottom: 10 })
  11719. // 跳过头尾
  11720. Column() {
  11721. Row() {
  11722. Text('跳过片尾:')
  11723. .fontSize(16)
  11724. .fontColor($r('app.color.text_color'))
  11725. Text(this.jumpEndTime + 's')
  11726. .fontSize(16)
  11727. .fontColor($r('app.color.text_color'))
  11728. }
  11729. .margin({ bottom: 5 })
  11730. Row() {
  11731. Slider({
  11732. value: this.jumpEndTime,
  11733. min: 0,
  11734. max: 120,
  11735. step: 1,
  11736. style: SliderStyle.OutSet
  11737. })
  11738. .blockColor(this.themeColor)
  11739. .trackColor($r('app.color.speed_text_color'))
  11740. .selectedColor(Color.White)
  11741. .trackThickness(8)
  11742. .onChange((value: number) => {
  11743. this.jumpEndTime = value;
  11744. })
  11745. .width('85%')
  11746. }
  11747. .alignItems(VerticalAlign.Top)
  11748. }
  11749. .margin({ top: 10, bottom: 10 })
  11750. Row() {
  11751. Button('保存设置')
  11752. .fontColor(Color.White)
  11753. .layoutWeight(1)
  11754. .height(40)
  11755. .width(80)
  11756. .backgroundColor(this.themeColor)
  11757. .stateEffect(true)
  11758. .margin({ left: 0, bottom: 20 })
  11759. .onClick(async () => {
  11760. if (!Utility.isNoble()) {
  11761. this.isJumpSetting = false
  11762. this.isShowMoreView = false
  11763. this.showVipDialog()
  11764. return
  11765. }
  11766. if (this.currentSong === undefined) {
  11767. return
  11768. }
  11769. if (this.modeType === 0) {
  11770. let parentPath = FileUtil.getParentPath(this.videoUrl)
  11771. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  11772. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  11773. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  11774. } else if (this.modeType === 1) { //媒体库
  11775. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  11776. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  11777. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  11778. } else if (this.modeType === 2) { //艺术家
  11779. if (this.currentSong?.artist) {
  11780. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  11781. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  11782. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  11783. }
  11784. } else if (this.modeType === 3) { //专辑
  11785. if (this.currentSong?.album) {
  11786. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  11787. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  11788. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  11789. }
  11790. }
  11791. ToastUtil.showShort("保存成功")
  11792. this.isJumpSetting = false
  11793. })
  11794. }
  11795. .margin({
  11796. left: 38,
  11797. right: 38,
  11798. top: 10,
  11799. bottom: 10
  11800. })
  11801. .width(120)
  11802. .height(50)
  11803. }
  11804. }
  11805. }
  11806. .width('100%')
  11807. .height('100%')
  11808. }
  11809. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  11810. private onStateVastChange(state: AVCastPickerState) {
  11811. if (state == AVCastPickerState.STATE_APPEARING) {
  11812. console.log('The picker starts showing.');
  11813. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  11814. console.log('The picker finishes presenting.');
  11815. }
  11816. }
  11817. private showSelectLyric() {
  11818. DialogHelper.showActionSheetDialog({
  11819. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  11820. // sheets: ["本地歌词", "搜索歌词"],
  11821. sheets: [
  11822. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  11823. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  11824. ],
  11825. maskColor: Color.Transparent,
  11826. backgroundColor: $r('app.color.bg_card'),
  11827. transition: AnimationHelper.transitionInDown(666),
  11828. onAction: (index) => {
  11829. switch (index) {
  11830. case 0:
  11831. this.callFilePickerSelectFileForLyric()
  11832. break;
  11833. case 1:
  11834. if (StrUtil.isNotEmpty(this.videoUrl)) {
  11835. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  11836. this.initLyric(lyricPath);
  11837. }
  11838. break;
  11839. }
  11840. }
  11841. })
  11842. }
  11843. // 拉起picker选择文件管理器
  11844. async callFilePickerSelectFileForLyric(): Promise<void> {
  11845. try {
  11846. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  11847. DocumentSelectOptions.maxSelectNumber = 1
  11848. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  11849. let documentPicker = new picker.DocumentViewPicker();
  11850. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  11851. Logger.info(TAG,
  11852. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  11853. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  11854. this.saveVideoDatasLyric(DocumentSelectResult)
  11855. }
  11856. }).catch((err: BusinessError) => {
  11857. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  11858. });
  11859. } catch (err) {
  11860. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  11861. }
  11862. }
  11863. async saveVideoDatasLyric(uris: string[]) {
  11864. if (ArrayUtil.isEmpty(uris)) {
  11865. return
  11866. }
  11867. let newUris: string[] = [];
  11868. for (let i = 0; i < uris.length; i++) {
  11869. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  11870. Logger.info(TAG, 'filePath uri: ' + filePath);
  11871. newUris.push(filePath)
  11872. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  11873. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  11874. fileIo.copyFileSync(file.fd, file2.fd)
  11875. fileIo.closeSync(file);
  11876. fileIo.closeSync(file2);
  11877. this.initLyric(filePath,false,false,true)
  11878. }
  11879. }
  11880. private initDelayPlay(context: object) {
  11881. this.mContext = context;
  11882. }
  11883. startPipLyric() {
  11884. if (this.pipController) {
  11885. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  11886. PiPWindow.PiPControlStatus.PLAY);
  11887. }
  11888. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  11889. if (this.isOpenPip) {
  11890. this.startPip()
  11891. } else {
  11892. this.stopPip()
  11893. }
  11894. }
  11895. //startOffset 从cue分轨时间开始播
  11896. private startPlayOrResumePlay(startOffset?:number) {
  11897. //针对dsf文件高采样率,统一转wav播放
  11898. const sampleRate = this.currentSong?.sampleRate||0
  11899. if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  11900. console.info('onecold 采样率 ='+sampleRate)
  11901. let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  11902. console.info('onecold newDsfPath ='+newDsfPath)
  11903. if(!FileUtil.accessSync(newDsfPath)){
  11904. const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  11905. taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  11906. this.videoUrl = newDsfPath
  11907. this.startPlay(startOffset)
  11908. }).catch((e:object)=>{
  11909. console.info("task1 catch e: " + e);
  11910. })
  11911. }else{
  11912. this.videoUrl = newDsfPath
  11913. this.startPlay(startOffset)
  11914. }
  11915. }else{
  11916. this.startPlay(startOffset)
  11917. }
  11918. }
  11919. startPlay(startOffset?:number) {
  11920. this.startPipLyric()
  11921. this.mDestroyPage = false;
  11922. this.animationState = AnimationStatus.Running
  11923. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  11924. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  11925. this.stopProgressTask();
  11926. this.startProgressTask();
  11927. this.play(this.videoUrl.toString(),startOffset);
  11928. }
  11929. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  11930. this.mIjkMediaPlayer.start();
  11931. this.setProgress()
  11932. this.CONTROL_PlayStatus = PlayStatus.PLAY
  11933. }
  11934. this.setIsPlaying(true)
  11935. this.updateSessionPlayState(true)
  11936. this.watchStatus();
  11937. this.updateLastPlayTimeStr(this.videoUrl)
  11938. }
  11939. updateLastPlayTimeStr(filePath: string) {
  11940. // 检查是否为网络音频(WebDAV),如果是则不更新本地数据库
  11941. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  11942. Logger.info(`heanup 检测到网络音频播放,跳过数据库更新: ${filePath}`)
  11943. return;
  11944. }
  11945. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  11946. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  11947. if (success) {
  11948. this.getHistoryList(false)
  11949. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  11950. } else {
  11951. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  11952. }
  11953. });
  11954. }
  11955. private completionNum(num: number): string | number {
  11956. if (num < 10) {
  11957. return '0' + num;
  11958. } else {
  11959. return num;
  11960. }
  11961. }
  11962. private stringForTime(timeMs: number): string {
  11963. let totalSeconds: number | string = (timeMs / 1000);
  11964. let newSeconds: number | string = totalSeconds % 60;
  11965. let minutes: number | string = (totalSeconds / 60) % 60;
  11966. let hours: number | string = totalSeconds / 3600;
  11967. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  11968. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  11969. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  11970. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  11971. if (this.isCurrentTime) {
  11972. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  11973. this.oldSeconds = newSeconds
  11974. } else {
  11975. newSeconds = this.oldSeconds
  11976. }
  11977. }
  11978. newSeconds = this.completionNum(newSeconds);
  11979. if (hours > 0) {
  11980. return hours + ":" + minutes + ":" + newSeconds;
  11981. } else {
  11982. return minutes + ":" + newSeconds;
  11983. }
  11984. }
  11985. private setProgress() {
  11986. let position = this.mIjkMediaPlayer.getCurrentPosition();
  11987. let duration = this.mIjkMediaPlayer.getDuration();
  11988. if (duration <= 0 && this.duration > 0) {
  11989. duration = this.duration;
  11990. }
  11991. let pos = 0;
  11992. if (duration > 0) {
  11993. this.slideEnable = true;
  11994. let curPercent = position / duration;
  11995. pos = curPercent * 100;
  11996. if (pos > this.PROGRESS_MAX_VALUE) {
  11997. this.progressValue = this.PROGRESS_MAX_VALUE
  11998. } else {
  11999. this.progressValue = pos;
  12000. }
  12001. }
  12002. // LogUtils.getInstance()
  12003. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  12004. this.totalTime = this.stringForTime(duration);
  12005. if (position > duration) {
  12006. position = duration;
  12007. }
  12008. this.isCurrentTime = true;
  12009. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  12010. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  12011. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  12012. this.currentTime = this.stringForTime(position);
  12013. this.isCurrentTime = false
  12014. if (this.mIjkMediaPlayer.isPlaying()) {
  12015. this.randomColor =
  12016. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  12017. //如果是开启AB循环
  12018. if(this.isOpenAB){
  12019. if(position >=this.jumpBTime){
  12020. this.seekTo(this.jumpATime+'')
  12021. return
  12022. }
  12023. }
  12024. // 判断是否播放到结束时间
  12025. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  12026. if (position >= duration - this.jumpEndTime * 1000) {
  12027. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  12028. this.CONTROL_PlayStatus = PlayStatus.INIT
  12029. this.startPlayOrResumePlay();
  12030. }else if (this.playType == 2) { //2:正常播放,单曲播完
  12031. this.showRePlay();
  12032. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  12033. this.progressValue = this.PROGRESS_MAX_VALUE;
  12034. this.slideEnable = false;
  12035. this.stop();
  12036. // ToastUtil.showToast('开始重新播放')
  12037. }else{
  12038. this.playNext().catch(() => {
  12039. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  12040. });
  12041. }
  12042. }
  12043. }
  12044. } else {
  12045. this.randomColor = 'rbg(0,0,0)'
  12046. }
  12047. }
  12048. private startProgressTask() {
  12049. let that = this;
  12050. this.updateProgressTimer = setInterval(() => {
  12051. //LogUtils.getInstance().LOGI("startProgressTask");
  12052. if (!that.mDestroyPage) {
  12053. that.setProgress();
  12054. }
  12055. }, 300);
  12056. }
  12057. private stopProgressTask() {
  12058. LogUtils.getInstance().LOGI("stopProgressTask");
  12059. clearInterval(this.updateProgressTimer);
  12060. }
  12061. private showLoadIng() {
  12062. this.loadingVisible = Visibility.Visible;
  12063. this.replayVisible = Visibility.None;
  12064. }
  12065. private hideLoadIng() {
  12066. this.loadingVisible = Visibility.None;
  12067. this.replayVisible = Visibility.None;
  12068. }
  12069. private showRePlay() {
  12070. this.loadingVisible = Visibility.None;
  12071. this.replayVisible = Visibility.Visible;
  12072. }
  12073. private async play(url: string,startOffset?:number) {
  12074. this.isShowBgLiuGUANG = PreferencesUtil.getBooleanSync('isShowBgLiuGUANG', false)
  12075. console.info('onecold this.url 1= '+url)
  12076. if(!url.toLowerCase().startsWith('http')){
  12077. let hasPermission = await PermissionUtil.activatePermission(url)
  12078. console.info('onecold this.hasPermission 1= '+hasPermission)
  12079. if(!url.includes(this.packName)){
  12080. const file = fs.openSync(url)
  12081. this.videoUrl = file.path
  12082. url= this.videoUrl
  12083. }
  12084. console.info('onecold this.hasPermission 1= '+hasPermission)
  12085. console.info('onecold this.videoUrl 1= '+this.videoUrl)
  12086. }
  12087. let that = this;
  12088. that.showLoadIng();
  12089. this.isOpenAB = false
  12090. //设置XComponent回调的context
  12091. if (!!this.mContext) {
  12092. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  12093. }
  12094. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  12095. this.mIjkMediaPlayer.reset();
  12096. }
  12097. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  12098. //设置debug模式
  12099. this.mIjkMediaPlayer.setDebug(false);
  12100. //初始化配置
  12101. this.mIjkMediaPlayer.native_setup();
  12102. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  12103. if(this.volumeSmall){
  12104. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  12105. this.mIjkMediaPlayer.setVolume('1', '1');
  12106. }else{
  12107. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  12108. }
  12109. }else{
  12110. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  12111. }
  12112. //设置视频源
  12113. Logger.info(TAG, `IjkPlayer setDataSource url=${url}`);
  12114. this.mIjkMediaPlayer.setDataSource(url);
  12115. // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
  12116. const headers = new Map<string, string>();
  12117. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  12118. headers.set("Accept", "*/*");
  12119. if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
  12120. &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
  12121. //如果封面为空,则搜索封面
  12122. this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
  12123. }
  12124. // 如果是WebDAV网络音频,使用webdav_account_id获取认证信息(等待完成后再设置一次性头部)
  12125. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type)) {
  12126. Logger.info(`heanup WebDAV歌曲认证 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
  12127. if (this.currentSong.webdav_account_id) {
  12128. try {
  12129. const webdavManager = RemoteDriveManager.getInstance();
  12130. const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  12131. if (webDavHeaders && webDavHeaders.size > 0) {
  12132. webDavHeaders.forEach((value, key) => headers.set(key, value));
  12133. Logger.info(`heanup 成功通过webdav_account_id获取并合并WebDAV认证头`);
  12134. } else {
  12135. Logger.warn(`heanup 通过webdav_account_id获取认证头失败,播放可能无法继续`);
  12136. }
  12137. } catch (error) {
  12138. const err = error as Error;
  12139. Logger.error(`heanup 获取WebDAV认证头时出错: ${err.message}`);
  12140. }
  12141. } else {
  12142. Logger.error(`heanup WebDAV歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法进行认证`);
  12143. }
  12144. }
  12145. // 统一设置带认证的请求头
  12146. // 百度类型也需要特殊请求头
  12147. if (this.currentSong && isBaiduType(this.currentSong.type)) {
  12148. try {
  12149. const webdavManager = RemoteDriveManager.getInstance();
  12150. const baiduHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  12151. baiduHeaders.forEach((value, key) => headers.set(key, value));
  12152. const headerSnapshot: Record<string, string> = {};
  12153. headers.forEach((value, key) => headerSnapshot[key] = value);
  12154. Logger.info(TAG, `Baidu播放请求头: ${JSON.stringify(headerSnapshot)}`);
  12155. } catch (error) {
  12156. Logger.error(`heanup 构建百度请求头失败: ${(error as Error).message}`);
  12157. }
  12158. }
  12159. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  12160. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type)) {
  12161. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  12162. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  12163. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  12164. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  12165. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  12166. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  12167. // 缓冲和播放优化设置
  12168. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  12169. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  12170. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1"); // 预加载启动
  12171. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  12172. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  12173. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  12174. // 网络相关设置
  12175. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  12176. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  12177. // 重连设置
  12178. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  12179. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  12180. } else if (this.currentSong && isBaiduType(this.currentSong.type)) {
  12181. console.log(`heanup 为百度网盘播放设置IjkPlayer选项`);
  12182. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "15000000");
  12183. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "15000000");
  12184. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1");
  12185. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "1");
  12186. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "2097152");
  12187. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "25");
  12188. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", BaiduConstants.USER_AGENT);
  12189. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", "3");
  12190. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http-detect-range-support", "1");
  12191. console.log(`heanup 百度网盘 IjkPlayer 选项设置完成`);
  12192. }
  12193. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  12194. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  12195. // }
  12196. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  12197. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  12198. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  12199. let bufferSize = 50 * 1024 ; // 默认缓冲区大小为1MB
  12200. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  12201. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  12202. //停止预读的最小帧数
  12203. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  12204. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  12205. // 设置其他缓冲相关选项
  12206. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  12207. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  12208. //启动预加载
  12209. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  12210. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  12211. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  12212. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  12213. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  12214. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  12215. // 因此需要播放器丢包,才不会累积延时
  12216. // 这个和第三个参数packet-buffering无关。
  12217. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  12218. // 无限制收流
  12219. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  12220. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  12221. // 屏幕常亮
  12222. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  12223. // 开启hls起播优化 默认是关闭的
  12224. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "fetch_first", "on");
  12225. // 设置超时
  12226. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  12227. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  12228. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  12229. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  12230. // 变速播放
  12231. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  12232. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  12233. let Speed = this.mIjkMediaPlayer.getSpeed()
  12234. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  12235. //是否开启循环播放
  12236. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  12237. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  12238. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  12239. if (height === 0) {
  12240. return;
  12241. }
  12242. const va = width / height;
  12243. const vpa = that.videoParentAspectRatio;
  12244. if (vpa > va) {
  12245. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  12246. } else {
  12247. that.videoWidth = '100%';
  12248. }
  12249. if (width && height) {
  12250. that.videoAspectRatio = width / height;
  12251. }
  12252. LogUtils.getInstance()
  12253. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  12254. that.hideLoadIng();
  12255. }
  12256. }
  12257. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  12258. let mOnPreparedListener: OnPreparedListener = {
  12259. onPrepared: async () => {
  12260. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  12261. try {
  12262. //保存碰一碰分享的当前的歌曲
  12263. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  12264. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  12265. await this.initLyric(lyricPath);
  12266. const applyDuration = (durationMs: number): void => {
  12267. if (durationMs <= 0) {
  12268. return;
  12269. }
  12270. this.duration = durationMs;
  12271. this.durationTime = Math.floor(durationMs / 1000);
  12272. this.durationStringTime = secondToTime(this.durationTime);
  12273. this.totalTime = this.stringForTime(durationMs);
  12274. if (this.currentSong) {
  12275. this.currentSong.duration = this.totalTime;
  12276. try {
  12277. this.avSessionController.setAVMetadataMusic(this.currentSong, durationMs, this.lyricContent);
  12278. } catch (metaError) {
  12279. Logger.warn(TAG, `heanup 首次播放写入AVSession失败: ${(metaError as Error).message}`);
  12280. }
  12281. }
  12282. };
  12283. const fetchBaiduM3u8Duration = async (url: string): Promise<number> => {
  12284. if (!url || !isBaiduType(this.currentSong?.type ?? -1)) {
  12285. return 0;
  12286. }
  12287. const httpRequest = http.createHttp();
  12288. try {
  12289. const response = await httpRequest.request(url, {
  12290. method: http.RequestMethod.GET,
  12291. connectTimeout: 8000,
  12292. readTimeout: 8000,
  12293. expectDataType: http.HttpDataType.STRING,
  12294. header: {
  12295. 'User-Agent': BaiduConstants.STREAMING_USER_AGENT,
  12296. 'Host': 'pan.baidu.com'
  12297. }
  12298. });
  12299. if (response.responseCode !== 200 || typeof response.result !== 'string') {
  12300. return 0;
  12301. }
  12302. const text = response.result;
  12303. if (text.indexOf('#EXTM3U') < 0) {
  12304. return 0;
  12305. }
  12306. const lines = text.split('\n');
  12307. let totalSeconds = 0;
  12308. for (let i = 0; i < lines.length; i++) {
  12309. const line = lines[i].trim();
  12310. if (line.startsWith('#EXTINF:')) {
  12311. const colonIndex = line.indexOf(':');
  12312. if (colonIndex < 0) {
  12313. continue;
  12314. }
  12315. const content = line.substring(colonIndex + 1);
  12316. const commaIndex = content.indexOf(',');
  12317. const numberPart = commaIndex >= 0 ? content.substring(0, commaIndex) : content;
  12318. const seconds = Number(numberPart);
  12319. if (!Number.isNaN(seconds) && seconds > 0) {
  12320. totalSeconds += seconds;
  12321. }
  12322. }
  12323. }
  12324. if (totalSeconds > 0) {
  12325. return Math.floor(totalSeconds * 1000);
  12326. }
  12327. return 0;
  12328. } catch (fetchError) {
  12329. Logger.warn(TAG, `heanup 解析百度M3U8时长失败: ${(fetchError as Error).message}`);
  12330. return 0;
  12331. } finally {
  12332. httpRequest.destroy();
  12333. }
  12334. };
  12335. const fetchDurationFallback = async (): Promise<void> => {
  12336. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  12337. if (durationMs > 0) {
  12338. Logger.info(TAG, `heanup 通过M3U8推导出时长: ${durationMs}ms`);
  12339. applyDuration(durationMs);
  12340. return;
  12341. }
  12342. Logger.warn(TAG, 'heanup 首次播放未拿到时长,保持未知');
  12343. };
  12344. const preparedDuration = this.mIjkMediaPlayer.getDuration();
  12345. console.info("onecold preparedDuration--" + preparedDuration)
  12346. if (preparedDuration > 0) {
  12347. applyDuration(preparedDuration);
  12348. } else {
  12349. fetchDurationFallback();
  12350. }
  12351. setTimeout(() => {
  12352. this.avSessionController.initAvSession(false);
  12353. if (this.duration > 0) {
  12354. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  12355. }
  12356. this.setAvSessionListener();
  12357. this.updateSessionPlayState(true)
  12358. this.setCurrentPlayMode()
  12359. }, 500)
  12360. if(startOffset&&startOffset>0){//cue分轨播放
  12361. this.seekTo(startOffset + "");
  12362. this.saveLastPlayList()
  12363. return
  12364. }
  12365. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12366. let timeoutPlay = 0
  12367. if (StrUtil.isNotEmpty(this.videoUrl) &&
  12368. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  12369. timeoutPlay = 1000
  12370. }
  12371. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  12372. if (this.modeType === 0) { //文件夹
  12373. let parentPath = FileUtil.getParentPath(this.videoUrl)
  12374. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  12375. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  12376. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  12377. } else if (this.modeType === 1) { //媒体库
  12378. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  12379. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  12380. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  12381. } else if (this.modeType === 2) { //艺术家
  12382. if (this.currentSong?.artist) {
  12383. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  12384. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  12385. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  12386. }
  12387. } else if (this.modeType === 3) { //专辑
  12388. if (this.currentSong?.album) {
  12389. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  12390. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  12391. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  12392. }
  12393. }
  12394. this.duration = this.mIjkMediaPlayer.getDuration()
  12395. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  12396. if (this.mIjkMediaPlayer != null) {
  12397. let jumpTopTimeMs = this.jumpTopTime*1000;
  12398. if (jumpTopTimeMs <= this.duration) {
  12399. // 调用 seekTo 方法,跳到指定时间
  12400. if(PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY,true)){
  12401. console.log('onecold jumpTopTime = '+jumpTopTimeMs);
  12402. const position:number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  12403. console.log('onecold position = '+position);
  12404. if (position > jumpTopTimeMs) {
  12405. jumpTopTimeMs = position
  12406. }
  12407. }
  12408. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12409. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  12410. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  12411. }
  12412. }, timeoutPlay)
  12413. } else {
  12414. // 提示用户无法跳过
  12415. ToastUtil.showToast('跳过时间超过视频时长');
  12416. }
  12417. }
  12418. } else {
  12419. this.jumpTopTime = 0
  12420. this.jumpEndTime = 0
  12421. // console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  12422. // console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  12423. // console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  12424. // PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  12425. //记忆播放(每一首都会记忆播放)
  12426. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  12427. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12428. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  12429. this.restorePlaybackPosition() //读取播放记忆功能
  12430. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  12431. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  12432. this.restorePlaybackPosition() //读取播放记忆功能
  12433. }
  12434. this.isFirstStartPlay = false
  12435. }, timeoutPlay)
  12436. } else {
  12437. this.isFirstStartPlay = false
  12438. }
  12439. }
  12440. this.saveLastPlayList()
  12441. } catch (error) {
  12442. let err: BusinessError = error as BusinessError;
  12443. console.error('onecold failed with err: ' + JSON.stringify(err));
  12444. }
  12445. }
  12446. }
  12447. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  12448. let mOnTimedTextListener: OnTimedTextListener = {
  12449. onTimedText: () => {
  12450. }
  12451. }
  12452. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  12453. let mOnCompletionListener: OnCompletionListener = {
  12454. onCompletion: () => {
  12455. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  12456. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  12457. // 异步调用playNext
  12458. this.playNext().catch(() => {
  12459. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  12460. });
  12461. } else if (this.playType == 1) { //1:单片重复播放
  12462. this.CONTROL_PlayStatus = PlayStatus.INIT
  12463. that.startPlayOrResumePlay();
  12464. } else if (this.playType == 2) { //2:正常播放,单曲播完
  12465. that.showRePlay();
  12466. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  12467. that.progressValue = this.PROGRESS_MAX_VALUE;
  12468. that.slideEnable = false;
  12469. that.stop();
  12470. // ToastUtil.showToast('开始重新播放')
  12471. } else if (this.playType == 3) { //3:随机播放
  12472. // 异步调用randomPlay
  12473. this.randomPlay().catch(() => {
  12474. Logger.error('heanup OnCompletionListener randomPlay', `随机播放失败`);
  12475. });
  12476. }
  12477. }
  12478. }
  12479. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  12480. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  12481. onBufferingUpdate: (percent: number) => {
  12482. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  12483. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  12484. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  12485. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  12486. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  12487. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  12488. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  12489. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  12490. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  12491. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  12492. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  12493. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  12494. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  12495. let Looping = this.mIjkMediaPlayer.isLooping()
  12496. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  12497. }
  12498. }
  12499. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  12500. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  12501. onSeekComplete: () => {
  12502. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  12503. console.info('onecold startPlayOrResumePlay 10643')
  12504. that.startPlayOrResumePlay();
  12505. }
  12506. }
  12507. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  12508. let mOnInfoListener: OnInfoListener = {
  12509. onInfo: (what: number, extra: number) => {
  12510. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  12511. that.hideLoadIng();
  12512. }
  12513. }
  12514. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  12515. let mOnErrorListener: OnErrorListener = {
  12516. onError: (what: number, extra: number) => {
  12517. this.stopProgressTask();
  12518. LogUtils.getInstance().LOGI("heanup OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  12519. LogUtils.getInstance().LOGI('heanup 播放错误,歌曲详情:' + JSON.stringify(this.currentSong))
  12520. // 检查是否为WebDAV播放错误
  12521. let isWebDavError = false;
  12522. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.currentSong.filePath) {
  12523. try {
  12524. const globalContext = GlobalContext.getContext();
  12525. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  12526. if (webDavAuthInfo) {
  12527. isWebDavError = true;
  12528. }
  12529. } catch (error) {
  12530. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  12531. }
  12532. }
  12533. if (isWebDavError) {
  12534. Logger.error(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  12535. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  12536. // this.currentWebDavAuthInfo = null;
  12537. Logger.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  12538. // 根据错误代码提供更具体的错误信息
  12539. let errorMessage = "WebDAV播放失败";
  12540. if (what === -1) { // 网络错误
  12541. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  12542. } else if (what === -1004) { // HTTP 404
  12543. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  12544. } else if (what === -1001) { // 超时
  12545. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  12546. } else if (what === -1003) { // 无法解析主机
  12547. errorMessage = "无法连接到WebDAV服务器";
  12548. }
  12549. ToastUtil.showToast(errorMessage);
  12550. } else {
  12551. if (StrUtil.isNotEmpty(this.videoUrl) &&
  12552. !this.videoUrl.startsWith('http://') &&
  12553. !this.videoUrl.startsWith('https://') &&
  12554. !FileUtil.accessSync(this.videoUrl)) {
  12555. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  12556. }
  12557. }
  12558. that.hideLoadIng();
  12559. }
  12560. }
  12561. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  12562. this.mIjkMediaPlayer.setMessageListener();
  12563. this.mIjkMediaPlayer.prepareAsync();
  12564. this.mIjkMediaPlayer.start();
  12565. }
  12566. //保存最后播放的那首歌和已经对应的播放列表
  12567. saveLastPlayList() {
  12568. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  12569. PreferencesUtil.putSync('LastMusicList', this.songList)
  12570. }
  12571. // 清空播放记录
  12572. clearVideoHistory() {
  12573. this.table.clearPlayHistory((success: boolean, error?: string) => {
  12574. if (success) {
  12575. this.historyList = [];
  12576. this.updateListData(this.historyList)
  12577. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  12578. ToastUtil.showToast('清空播放记录成功')
  12579. } else {
  12580. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  12581. }
  12582. });
  12583. }
  12584. public async setAvSessionListener() {
  12585. if (!this.avSessionController) {
  12586. return;
  12587. }
  12588. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  12589. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  12590. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  12591. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  12592. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  12593. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  12594. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  12595. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  12596. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  12597. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  12598. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  12599. }
  12600. setLoopMode() {
  12601. let itype = this.playType + 1
  12602. if (itype >= 4) {
  12603. this.playType = 0
  12604. ToastUtil.showToast('连续播放')
  12605. } else if (itype === 1) {
  12606. this.playType = 1
  12607. ToastUtil.showToast('单曲循环')
  12608. } else if (itype === 2) {
  12609. this.playType = 2
  12610. ToastUtil.showToast('单曲播完')
  12611. } else if (itype === 3) {
  12612. this.playType = 3
  12613. ToastUtil.showToast('随机播放')
  12614. } else if (itype === 0) {
  12615. this.playType = 0
  12616. ToastUtil.showToast('连续播放')
  12617. }
  12618. PreferencesUtil.putSync('musicPlayType', this.playType)
  12619. this.setCurrentPlayMode()
  12620. }
  12621. private sessionSetLoopModeCallback = (mode: number) => {
  12622. if (this.mIjkMediaPlayer != null) {
  12623. ToastUtil.showToast('当前播放模式:' + mode)
  12624. Logger.info('onecold 当前播放模式= ' + mode)
  12625. let hmPlayMode = mode + 1
  12626. if (hmPlayMode >= 4) {
  12627. hmPlayMode = 0
  12628. }
  12629. if (hmPlayMode === 1) {
  12630. this.playType = 1
  12631. ToastUtil.showToast('单曲循环')
  12632. } else if (hmPlayMode === 0) {
  12633. this.playType = 2
  12634. ToastUtil.showToast('单曲播完')
  12635. } else if (hmPlayMode === 3) {
  12636. this.playType = 3
  12637. ToastUtil.showToast('随机播放')
  12638. } else if (hmPlayMode === 2) {
  12639. this.playType = 0
  12640. ToastUtil.showToast('连续播放')
  12641. }
  12642. PreferencesUtil.putSync('musicPlayType', this.playType)
  12643. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  12644. let playBackState: avSession.AVPlaybackState = {
  12645. loopMode: hmPlayMode,
  12646. };
  12647. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  12648. console.info(`set setLoopMode AVPlaybackState successfully`);
  12649. }).catch((err: BusinessError) => {
  12650. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  12651. });
  12652. }
  12653. }
  12654. setCurrentPlayMode() {
  12655. if (!this.avSessionController) {
  12656. return;
  12657. }
  12658. let mLoopMode = 0
  12659. switch (this.playType) {
  12660. case 0:
  12661. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  12662. break;
  12663. case 1:
  12664. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  12665. break;
  12666. case 2:
  12667. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  12668. break;
  12669. case 3:
  12670. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  12671. break;
  12672. }
  12673. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  12674. let playBState: avSession.AVPlaybackState = {
  12675. loopMode: mLoopMode,
  12676. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  12677. };
  12678. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  12679. console.info(`set setLoopMode AVPlaybackState successfully`);
  12680. }).catch((err: BusinessError) => {
  12681. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  12682. });
  12683. }
  12684. private sessionToggleFavoriteCallback = (assetId: string) => {
  12685. if (this.mIjkMediaPlayer != null && this.currentSong) {
  12686. console.info(`on toggleFavorite `);
  12687. // 应用收到收藏命令,进行收藏处理。
  12688. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  12689. this.doFav(this.currentSong)
  12690. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  12691. let playbackState: avSession.AVPlaybackState = {
  12692. isFavorite: !this.isFac,
  12693. };
  12694. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  12695. console.info(`SetAVPlaybackState successfully`);
  12696. }).catch((err: BusinessError) => {
  12697. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  12698. });
  12699. }
  12700. }
  12701. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  12702. device: avSession.OutputDeviceInfo) => {
  12703. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  12704. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  12705. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  12706. await this.startCasting();
  12707. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  12708. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  12709. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  12710. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  12711. if (device) {
  12712. this.endCasting();
  12713. }
  12714. }
  12715. };
  12716. private async startCasting() {
  12717. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  12718. this.setPlaybackStateChangeListener();
  12719. this.pause();
  12720. this.initQueueItem();
  12721. this.prepare();
  12722. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  12723. refToIsCasting?.set(true);
  12724. this.castSeek = true;
  12725. this.isCastPlaying = true;
  12726. }
  12727. async changeCasting() {
  12728. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  12729. this.initQueueItem();
  12730. this.prepare();
  12731. this.setPlaybackStateChangeListener();
  12732. this.isCastPlaying = true;
  12733. this.castSeek = true;
  12734. }
  12735. public endCasting() {
  12736. this.avSessionController.getAvSession()?.stopCasting();
  12737. this.stopCast();
  12738. this.isCastPlaying = false;
  12739. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  12740. refToIsCasting?.set(false);
  12741. this.pause();
  12742. this.setIsPlaying(false);
  12743. // if (this.curIndex === this.curSource.index) {
  12744. // this.play
  12745. // this.seek(this.currentTime * 1000);
  12746. // this.setIsPlaying(true);
  12747. // } else {
  12748. // this.pauseVideo();
  12749. // this.setIsPlaying(false);
  12750. // }
  12751. }
  12752. public setIsPlaying(isPlayer: boolean) {
  12753. this.isPlaying = isPlayer;
  12754. // 发送播放状态变化事件给歌单详情页面
  12755. try {
  12756. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  12757. const currentFilePath = this.currentSong?.filePath || ''
  12758. const eventData: emitter.EventData = {
  12759. data: {
  12760. isPlaying: this.isPlaying,
  12761. curIndex: this.curIndex,
  12762. currentFilePath: currentFilePath
  12763. }
  12764. };
  12765. emitter.emit(eventPlaybackStatus, eventData)
  12766. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  12767. } catch (error) {
  12768. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  12769. }
  12770. }
  12771. private setPlaybackStateChangeListener(): void {
  12772. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  12773. this.castController?.on('endOfStream', this.reloadCasting);
  12774. this.castController?.on('playNext', this.playNextCallback);
  12775. this.castController?.on('playPrevious', this.playPreviousCallback);
  12776. }
  12777. private updateSessionPlayState(isPlay: boolean): void {
  12778. // if(!this.isBgPlayOpen)
  12779. // return
  12780. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  12781. this.setAVSessionPlayState({
  12782. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  12783. position: {
  12784. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  12785. updateTime: new Date().getTime()
  12786. }
  12787. });
  12788. }
  12789. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  12790. this.avSessionController.setAvSessionPlayState(playbackState)
  12791. }
  12792. private positionChange(position: number) {
  12793. this.currentTime2 = position / 1000;
  12794. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  12795. }
  12796. private playDurationChange(duration: number) {
  12797. this.duration = duration;
  12798. this.durationTime = Math.floor(this.duration / 1000);
  12799. this.durationStringTime = secondToTime((this.durationTime));
  12800. }
  12801. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  12802. const duration = playbackState?.extras?.duration;
  12803. if (typeof duration === 'number') {
  12804. this.playDurationChange(duration as number);
  12805. }
  12806. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  12807. this.positionChange(playbackState?.position?.elapsedTime);
  12808. }
  12809. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  12810. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  12811. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  12812. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  12813. this.isCastPlaying = false;
  12814. }
  12815. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  12816. this.isCastPlaying = true;
  12817. }
  12818. };
  12819. private reloadCasting = async () => {
  12820. let item = this.songList[this.curIndex];
  12821. let uri = fileUri.getUriFromPath(item.filePath);
  12822. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  12823. // description.startPosition = 0;
  12824. this.castItem = {
  12825. itemId: this.curIndex,
  12826. description: {
  12827. assetId: item.filePath,
  12828. title: item.name,
  12829. artist: '',
  12830. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  12831. // mediaUri: item.filePath,
  12832. fdSrc: {
  12833. fd: file.fd
  12834. },
  12835. // 该字段大写,音频'AUDIO',视频'VIDEO'
  12836. mediaType: 'VIDEO',
  12837. mediaSize: item.videoSize,
  12838. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  12839. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  12840. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  12841. duration: this.duration,
  12842. // albumCoverUri: 'https://www.example.jpeg',
  12843. // albumTitle: '《ExampleAlbum》',
  12844. appName: this.appName,
  12845. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  12846. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  12847. }
  12848. };
  12849. this.prepare();
  12850. this.isCastPlaying = true;
  12851. };
  12852. public playNextCallback = (): void => {
  12853. this.playNext().catch(() => {
  12854. Logger.error('heanup playNextCallback', `播放下一首失败`);
  12855. });
  12856. };
  12857. public playPreviousCallback = (): void => {
  12858. this.playPrevious().catch(() => {
  12859. Logger.error('heanup playNextCallback', `播放上一首失败`);
  12860. });
  12861. };
  12862. async prepare() {
  12863. await this.castController?.prepare(this.castItem);
  12864. await this.castController?.start(this.castItem);
  12865. }
  12866. public initQueueItem() {
  12867. let item = this.songList[this.curIndex];
  12868. let time = this.currentTime;
  12869. let uri = fileUri.getUriFromPath(item.filePath);
  12870. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  12871. this.castItem = {
  12872. itemId: this.curIndex,
  12873. description: {
  12874. assetId: item.filePath,
  12875. title: item.name,
  12876. artist: '',
  12877. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  12878. fdSrc: {
  12879. fd: file.fd
  12880. },
  12881. // 该字段大写,音频'AUDIO',视频'VIDEO'
  12882. mediaType: 'AUDIO',
  12883. mediaSize: item.videoSize,
  12884. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  12885. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  12886. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  12887. duration: this.duration,
  12888. // albumCoverUri: 'https://www.example.jpeg',
  12889. // albumTitle: '《ExampleAlbum》',
  12890. appName: this.appName,
  12891. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  12892. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  12893. }
  12894. };
  12895. }
  12896. async stopCast() {
  12897. try {
  12898. this.castController?.off('playbackStateChange');
  12899. this.castController?.off('endOfStream');
  12900. this.castController?.off('playNext');
  12901. this.castController?.off('playPrevious');
  12902. this.castController?.off('error');
  12903. } catch (error) {
  12904. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  12905. }
  12906. }
  12907. private sessionPlayCallback = (): void => {
  12908. this.playOrPause()
  12909. };
  12910. private sessionPauseCallback = (): void => {
  12911. this.pause()
  12912. };
  12913. private playOrPause() {
  12914. if (!this.debounce()) {
  12915. return;
  12916. }
  12917. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  12918. this.pause();
  12919. } else {
  12920. console.info('onecold startPlayOrResumePlay 11064')
  12921. this.startPlayOrResumePlay();
  12922. this.playChange()
  12923. }
  12924. }
  12925. private sessionPlayNextCallback = (): void => {
  12926. this.playNext().catch(() => {
  12927. Logger.error('heanup sessionPlayPreviousCallback', `播放下 一首失败`);
  12928. });
  12929. };
  12930. private sessionPlayPreviousCallback = (): void => {
  12931. this.playPrevious().catch(() => {
  12932. Logger.error('heanup sessionPlayPreviousCallback', `播放上一首失败`);
  12933. });
  12934. };
  12935. private sessionStopCallback = (): void => {
  12936. this.stop()
  12937. };
  12938. private sessionFastForwardCallback = (time?: number) => {
  12939. if (!time) {
  12940. return;
  12941. }
  12942. if (this.mIjkMediaPlayer != null) {
  12943. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12944. let seeTime = curPosition + time * 1000;
  12945. // 限制 seekValue 在合法范围内
  12946. if (seeTime < 0) {
  12947. seeTime = 0;
  12948. } else if (seeTime > this.duration) {
  12949. seeTime = this.duration;
  12950. }
  12951. Logger.info('onecold seeTime= ' + seeTime)
  12952. this.setSeekToActionProgress(seeTime)
  12953. this.seekTo(seeTime + "")
  12954. }
  12955. };
  12956. /**
  12957. * Gesture method onActionUpdate.
  12958. *
  12959. * @param event Gesture event.手势拖动设置快进和后退
  12960. */
  12961. private setSeekToActionProgress(position: number) {
  12962. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  12963. let duration = this.mIjkMediaPlayer.getDuration();
  12964. let pos = 0;
  12965. if (duration > 0) {
  12966. this.slideEnable = true;
  12967. let curPercent = position / duration;
  12968. pos = curPercent * 100;
  12969. if (pos > this.PROGRESS_MAX_VALUE) {
  12970. this.progressValue = this.PROGRESS_MAX_VALUE
  12971. } else {
  12972. this.progressValue = pos;
  12973. }
  12974. }
  12975. // LogUtils.getInstance()
  12976. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  12977. this.totalTime = this.stringForTime(duration);
  12978. if (position > duration) {
  12979. position = duration;
  12980. }
  12981. this.isCurrentTime = true;
  12982. this.currentTime = this.stringForTime(position);
  12983. this.isCurrentTime = false
  12984. }
  12985. private sessionRewindCallback = (time?: number) => {
  12986. if (!time) {
  12987. return;
  12988. }
  12989. if (this.mIjkMediaPlayer != null) {
  12990. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12991. let seeTime = curPosition - time * 1000;
  12992. // 限制 seekValue 在合法范围内
  12993. if (seeTime < 0) {
  12994. seeTime = 0;
  12995. } else if (seeTime > this.duration) {
  12996. seeTime = this.duration;
  12997. }
  12998. Logger.info('onecold seeTime= ' + seeTime)
  12999. this.setSeekToActionProgress(seeTime)
  13000. this.seekTo(seeTime + "")
  13001. }
  13002. };
  13003. private sessionSeekCallback = (seekTime: number) => {
  13004. if (this.mIjkMediaPlayer != null) {
  13005. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  13006. this.seekTo(seekTime + "")
  13007. }
  13008. };
  13009. private async getFileSize(filePath: string): Promise<number> {
  13010. try {
  13011. const stat = await fs.stat(filePath);
  13012. return stat.size;
  13013. } catch (err) {
  13014. console.error('Failed to get file size: ' + err.message);
  13015. return 0;
  13016. }
  13017. }
  13018. private pause() {
  13019. if (this.mIjkMediaPlayer.isPlaying()) {
  13020. this.savePlaybackPosition();
  13021. this.mIjkMediaPlayer.pause();
  13022. this.setProgress();
  13023. this.mDestroyPage = true;
  13024. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  13025. this.updateSessionPlayState(false)
  13026. this.playChange()
  13027. if (this.pipController) {
  13028. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  13029. PiPWindow.PiPControlStatus.PAUSE);
  13030. }
  13031. }
  13032. }
  13033. private stop() {
  13034. this.savePlaybackPosition();
  13035. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13036. this.mIjkMediaPlayer.stop();
  13037. this.mIjkMediaPlayer.release();
  13038. this.stopProgressTask();
  13039. this.updateSessionPlayState(false)
  13040. this.playChange()
  13041. this.watchStatus();
  13042. }
  13043. //保持记忆播放功能
  13044. private savePlaybackPosition() {
  13045. if (this.mIjkMediaPlayer != null) {
  13046. const position = this.mIjkMediaPlayer.getCurrentPosition();
  13047. // ToastUtil.showToast('保存记忆播放 = ' + position)
  13048. const duration = this.mIjkMediaPlayer.getDuration();
  13049. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  13050. // 如果播放位置接近视频末尾,则保存 position 为 0
  13051. const playbackPosition = (duration - position < threshold) ? 0 : position;
  13052. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  13053. }
  13054. }
  13055. //获取记忆播放功能
  13056. private restorePlaybackPosition() {
  13057. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  13058. // ToastUtil.showToast('position = ' + position)
  13059. if (this.mIjkMediaPlayer != null && position > 0) {
  13060. // ToastUtil.showToast('seekTo = ' + position)
  13061. this.seekTo(position + "");
  13062. }
  13063. }
  13064. private seekTo(value: string) {
  13065. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  13066. ToastUtil.showToast('wma格式不支持拖动快进。')
  13067. return
  13068. }
  13069. this.isSeekTo = true
  13070. this.mIjkMediaPlayer.seekTo(value);
  13071. console.info('onecold startPlayOrResumePlay 11227')
  13072. // this.startPlayOrResumePlay()
  13073. // 在这里恢复计时器状态
  13074. this.setProgress()
  13075. this.isSeekTo = false
  13076. }
  13077. // 添加到下一首播放
  13078. private addToNextPlay(song: VideoItem) {
  13079. if (!this.debounce()) {
  13080. return;
  13081. }
  13082. if (this.currentSong) {
  13083. if (this.currentSong === song) {
  13084. ToastUtil.showToast('当前已经在播放这首歌了!')
  13085. return
  13086. }
  13087. }
  13088. // 如果未开始播放或队列为空
  13089. if (this.curIndex === -1 || this.songList.length === 0) {
  13090. this.songList = [song];
  13091. this.curIndex = 0;
  13092. this.doPlay(song)
  13093. return;
  13094. }
  13095. // 插入到当前索引+1的位置
  13096. const insertPos = this.curIndex + 1;
  13097. this.songList.splice(insertPos, 0, song);
  13098. this.songList = [...this.songList]; // 触发状态更新
  13099. this.sonDataSource.pushArrayData(this.songList)
  13100. ToastUtil.showToast('已添加至下一首播放')
  13101. }
  13102. //后退10s,可再设置设置默认几秒
  13103. backForward() {
  13104. if(this.mIjkMediaPlayer){
  13105. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  13106. let value = pos - Number(this.fastForwardSeconds) * 1000;
  13107. this.seekTo(value+"");
  13108. }
  13109. }
  13110. //快进10s,可再设置设置默认几秒
  13111. fastForward() {
  13112. if(this.mIjkMediaPlayer){
  13113. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  13114. let value = pos + Number(this.fastForwardSeconds) * 1000;
  13115. this.seekTo(value+"");
  13116. }
  13117. }
  13118. //下一个
  13119. private async playNext() {
  13120. if (!this.debounce()) {
  13121. return;
  13122. }
  13123. if (this.playType == 3) { //3:随机播放
  13124. await this.randomPlay()
  13125. return;
  13126. }
  13127. if (ArrayUtil.isNotEmpty(this.songList)) {
  13128. if (this.curIndex == this.songList.length - 1) {
  13129. this.curIndex = 0;
  13130. } else {
  13131. this.curIndex++;
  13132. }
  13133. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13134. this.stop();
  13135. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  13136. this.currentSong = this.songList[this.curIndex];
  13137. Logger.info('heanup playNext', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  13138. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13139. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13140. context: this.context,
  13141. autoParseMusicName: this.autoParseMusicName
  13142. });
  13143. this.artist = this.songList[this.curIndex].artist
  13144. this.name = this.songList[this.curIndex].name
  13145. //this.cover = this.songList[this.curIndex].pixelMapPath
  13146. this.changeImageAnimation()
  13147. }
  13148. }
  13149. changeImageAnimation() {
  13150. if(this.openSkipSongAnimate){
  13151. // 第一步:淡出动画
  13152. this.getUIContext()?.animateTo({
  13153. duration: 500,
  13154. curve: Curve.EaseOut,
  13155. }, () => {
  13156. this.opacityValueImage = 0.1;
  13157. if(this.isCoverRectangle){
  13158. this.scaleValueImage = 0.88
  13159. }
  13160. });
  13161. // 第二步:切换图片后淡入
  13162. setTimeout(() => {
  13163. this.cover = this.songList[this.curIndex].pixelMapPath
  13164. this.getUIContext()?.animateTo({
  13165. duration: 500,
  13166. curve: Curve.EaseIn,
  13167. }, () => {
  13168. this.opacityValueImage = 1;
  13169. this.scaleValueImage = 1 // 图标恢复到原始大小
  13170. this.startPlayOrResumePlay()
  13171. });
  13172. }, 500);
  13173. }else{
  13174. this.cover = this.songList[this.curIndex].pixelMapPath
  13175. this.startPlayOrResumePlay()
  13176. }
  13177. }
  13178. // 存储已播放的歌曲索引
  13179. private playedIndices: Set<number> = new Set();
  13180. //随机播放
  13181. private async randomPlay() {
  13182. // if (!this.debounce()) {
  13183. // return;
  13184. // }
  13185. if (ArrayUtil.isNotEmpty(this.songList)) {
  13186. if (this.songList.length > 3) {
  13187. // 如果所有歌曲都播放过一次,清空已播放索引集合
  13188. if (this.playedIndices.size === this.songList.length) {
  13189. this.playedIndices.clear();
  13190. }
  13191. // 随机选择一个未播放的歌曲索引
  13192. let newIndex: number;
  13193. // 添加超时机制防止无限循环
  13194. let attempt = 0;
  13195. const maxAttempts = 100; // 根据需求调整
  13196. do {
  13197. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  13198. attempt++;
  13199. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  13200. if (attempt >= maxAttempts) {
  13201. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  13202. newIndex = Math.floor(Math.random() * this.songList.length);
  13203. }
  13204. this.curIndex = newIndex;
  13205. this.playedIndices.add(newIndex);
  13206. } else {
  13207. // 当歌曲数量小于或等于3时,直接播放下一首
  13208. if (this.curIndex == this.songList.length - 1) {
  13209. this.curIndex = 0;
  13210. } else {
  13211. this.curIndex++;
  13212. }
  13213. }
  13214. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13215. this.stop();
  13216. this.currentSong = this.songList[this.curIndex];
  13217. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13218. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13219. context: this.context,
  13220. autoParseMusicName: this.autoParseMusicName
  13221. });
  13222. this.name = this.songList[this.curIndex].name;
  13223. this.artist = this.songList[this.curIndex].artist
  13224. // this.cover = this.songList[this.curIndex].pixelMapPath
  13225. this.changeImageAnimation()
  13226. }
  13227. }
  13228. private async playIndex(index: number) {
  13229. if (!this.debounce()) {
  13230. return;
  13231. }
  13232. if (ArrayUtil.isNotEmpty(this.songList)) {
  13233. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13234. this.stop();
  13235. this.curIndex = index;
  13236. this.currentSong = this.songList[index];
  13237. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13238. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13239. context: this.context,
  13240. autoParseMusicName: this.autoParseMusicName
  13241. });
  13242. this.name = this.currentSong.name
  13243. this.artist = this.currentSong.artist
  13244. this.changeImageAnimation()
  13245. }
  13246. }
  13247. //上一个
  13248. private async playPrevious() {
  13249. if (!this.debounce()) {
  13250. return;
  13251. }
  13252. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  13253. this.randomModePlayFromHistory()
  13254. return;
  13255. }
  13256. if (this.curIndex == 0) {
  13257. this.curIndex = this.songList.length - 1;
  13258. } else {
  13259. this.curIndex--;
  13260. }
  13261. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13262. this.stop();
  13263. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  13264. this.currentSong = this.songList[this.curIndex];
  13265. Logger.info('heanup playPrevious', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  13266. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13267. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13268. context: this.context,
  13269. autoParseMusicName: this.autoParseMusicName
  13270. });
  13271. this.name = this.songList[this.curIndex].name
  13272. this.artist = this.songList[this.curIndex].artist
  13273. this.changeImageAnimation()
  13274. }
  13275. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  13276. private async randomModePlayFromHistory() {
  13277. if (this.historyList.length >= 2) {
  13278. // 播放历史记录的第二首
  13279. const prevSong = this.historyList[1];
  13280. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  13281. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13282. this.stop();
  13283. // 直接使用历史记录中的歌曲信息,历史记录中的数据应该是完整的
  13284. this.currentSong = prevSong;
  13285. Logger.info('heanup randomModePlayFromHistory', `直接使用历史歌曲信息: ${prevSong.name}, type: ${prevSong.type}`);
  13286. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13287. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13288. context: this.context,
  13289. autoParseMusicName: this.autoParseMusicName
  13290. });
  13291. this.cover = prevSong.pixelMapPath
  13292. this.artist = prevSong.artist
  13293. this.name = prevSong.name;
  13294. console.info('onecold startPlayOrResumePlay 11434')
  13295. this.startPlayOrResumePlay();
  13296. } else {
  13297. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  13298. if (this.curIndex === 0) {
  13299. this.curIndex = this.songList.length - 1;
  13300. } else {
  13301. this.curIndex--;
  13302. }
  13303. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13304. this.stop();
  13305. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  13306. this.currentSong = this.songList[this.curIndex];
  13307. Logger.info('heanup randomModePlayFromHistory', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  13308. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13309. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13310. context: this.context,
  13311. autoParseMusicName: this.autoParseMusicName
  13312. });
  13313. this.artist = this.songList[this.curIndex].artist
  13314. this.name = this.songList[this.curIndex].name;
  13315. this.changeImageAnimation()
  13316. }
  13317. }
  13318. debounce() {
  13319. const delay = 600;
  13320. let cur = new Date().getTime();
  13321. if (cur - this.last > delay) {
  13322. this.last = cur;
  13323. return true;
  13324. }
  13325. return false;
  13326. }
  13327. /**
  13328. * Sets whether the screen is a constant based on the playback status.
  13329. */
  13330. watchStatus() {
  13331. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  13332. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  13333. this.windowClass.setWindowKeepScreenOn(true);
  13334. } else {
  13335. this.windowClass.setWindowKeepScreenOn(false);
  13336. }
  13337. }
  13338. /**
  13339. * Volume gesture method onActionStart.
  13340. *
  13341. * @param event Gesture event.
  13342. */
  13343. private customDialogComponentIdMM: number = 0
  13344. @Builder
  13345. customDialogComponentMM() {
  13346. Column() {
  13347. Row() {
  13348. Blank()
  13349. Text('验证密码')
  13350. .fontSize(22)
  13351. .fontColor($r('app.color.pri_bg'))
  13352. .margin({ top: 18 })
  13353. Blank()
  13354. Image($r('app.media.close'))
  13355. .fillColor(Color.White)
  13356. .margin({ top: 18, right: 18 })
  13357. .width(20)
  13358. .onClick(() => {
  13359. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  13360. })
  13361. }
  13362. .width('100%') // 使Row占据整个宽度
  13363. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  13364. Verify({
  13365. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  13366. });
  13367. }.height('60%')
  13368. .backgroundColor($r('app.color.index_background'))
  13369. .justifyContent(FlexAlign.SpaceBetween)
  13370. }
  13371. private handleVerifyCompleted(isSuccess: boolean) {
  13372. if (isSuccess) {
  13373. console.log('验证成功');
  13374. // 在这里处理验证成功后的逻辑
  13375. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  13376. this.currentPath = this.lockPath
  13377. this.getSortedFiles(this.currentPath)
  13378. } else {
  13379. // console.log('验证失败');
  13380. ToastUtil.showToast('验证失败')
  13381. }
  13382. }
  13383. private showVerifyDialog() {
  13384. promptAction.openCustomDialog({
  13385. transition: TransitionEffect.asymmetric(
  13386. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  13387. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  13388. ,
  13389. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  13390. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  13391. ),
  13392. builder: () => {
  13393. this.customDialogComponentMM()
  13394. },
  13395. isModal: true,
  13396. autoCancel: true,
  13397. maskColor: Color.Transparent,
  13398. alignment: DialogAlignment.Bottom,
  13399. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  13400. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  13401. console.log("dialog onWillDismiss")
  13402. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  13403. dismissDialogAction.dismiss()
  13404. }
  13405. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  13406. dismissDialogAction.dismiss()
  13407. }
  13408. }
  13409. }).then((dialogId: number) => {
  13410. this.customDialogComponentIdMM = dialogId
  13411. })
  13412. }
  13413. //左滑操作 移动文件 重命名 删除等操作
  13414. @Builder
  13415. DeleteButton(item: VideoItem, index: number, filePath: string) {
  13416. Row() {
  13417. //加入收藏
  13418. Button() {
  13419. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  13420. .fillColor(Color.White)
  13421. .width(20)
  13422. }
  13423. .width(40)
  13424. .height(40)
  13425. .type(ButtonType.Circle)
  13426. .backgroundColor(this.themeColor)
  13427. .margin(5)
  13428. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13429. .onClick(() => {
  13430. if (item) {
  13431. this.doFav(item)
  13432. }
  13433. })
  13434. //加入下一首播放
  13435. Button() {
  13436. Image($r('app.media.next_to_play'))
  13437. .fillColor(Color.White)
  13438. .width(20)
  13439. }
  13440. .width(40)
  13441. .height(40)
  13442. .type(ButtonType.Circle)
  13443. .backgroundColor(this.themeColor)
  13444. .margin(5)
  13445. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13446. .onClick(() => {
  13447. this.addToNextPlay(item);
  13448. })
  13449. //复制文件
  13450. Button() {
  13451. Image($r('app.media.copy'))
  13452. .fillColor(Color.White)
  13453. .width(20)
  13454. }
  13455. .width(40)
  13456. .height(40)
  13457. .type(ButtonType.Circle)
  13458. .backgroundColor(this.themeColor)
  13459. .margin(5)
  13460. .id(filePath + 'copy')
  13461. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13462. .onClick(() => {
  13463. this.showCopyDialog(false, item, index, filePath + 'copy');
  13464. })
  13465. //移动文件
  13466. Button() {
  13467. Image($r('app.media.cut'))
  13468. .fillColor(Color.White)
  13469. .width(20)
  13470. }
  13471. .width(40)
  13472. .height(40)
  13473. .type(ButtonType.Circle)
  13474. .backgroundColor(this.themeColor)
  13475. .margin(5)
  13476. .id(filePath)
  13477. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13478. .onClick(() => {
  13479. this.showCutDialog(false, item, index, filePath);
  13480. })
  13481. Button() {
  13482. Image($r('app.media.cut_current'))
  13483. .fillColor(Color.White)
  13484. .width(20)
  13485. }
  13486. .width(40)
  13487. .height(40)
  13488. .type(ButtonType.Circle)
  13489. .backgroundColor(this.themeColor)
  13490. .margin(5)
  13491. .id(filePath + 'current')
  13492. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  13493. (this.isHasDir ? Visibility.Visible : Visibility.None))
  13494. .onClick(() => {
  13495. this.showCutDialog(true, item, index, filePath + 'current');
  13496. })
  13497. //重命名
  13498. Button() {
  13499. Image($r('app.media.rename2'))
  13500. .fillColor(Color.White)
  13501. .width(20)
  13502. }
  13503. .width(40)
  13504. .height(40)
  13505. .type(ButtonType.Circle)
  13506. .backgroundColor(this.themeColor)
  13507. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  13508. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  13509. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  13510. .margin(5)
  13511. .onClick(() => {
  13512. this.showReNameDialog(item, index + '', filePath)
  13513. })
  13514. Button() {
  13515. Image($r('app.media.delete2'))
  13516. .fillColor(Color.White)
  13517. .width(20)
  13518. }
  13519. .width(40)
  13520. .height(40)
  13521. .type(ButtonType.Circle)
  13522. .backgroundColor(this.themeColor)
  13523. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  13524. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  13525. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  13526. .margin(5)
  13527. .onClick(() => {
  13528. this.selectedFiles.push(item)
  13529. this.showWarnIsDelete()
  13530. // this.showWarnIsDeleteFile(item, index + '', filePath)
  13531. })
  13532. Button() {
  13533. Image($r('app.media.share2'))
  13534. .fillColor(Color.White)
  13535. .width(20)
  13536. }
  13537. .width(40)
  13538. .height(40)
  13539. .type(ButtonType.Circle)
  13540. .backgroundColor(this.themeColor)
  13541. .margin(5)
  13542. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13543. .onClick(() => {
  13544. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  13545. })
  13546. }
  13547. }
  13548. /**
  13549. * 穿山甲banner广告
  13550. */
  13551. // private declare bannerAd: CSJNativeExpressAd;
  13552. // @State private status: string = "未加载"
  13553. // @State private isShowAd: boolean = false
  13554. // private declare mAdSlot: AdSlot;
  13555. // private mBiddingAdm = '' //服务端bidding才需要设置
  13556. // private expressLoadAdListener: NativeExpressAdListener = {
  13557. // /**
  13558. // * 加载失败的回调
  13559. // *
  13560. // * @param code
  13561. // * @param message
  13562. // */
  13563. // onError: (code: number, message: string) => {
  13564. // console.error("加载广告失败,code=" + code + ",message=" + message);
  13565. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  13566. // },
  13567. //
  13568. // /**
  13569. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  13570. // *
  13571. // * @param ads 返回的广告列表
  13572. // */
  13573. //
  13574. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  13575. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  13576. // if (ads && ads.length > 0) {
  13577. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  13578. // ad.setExpressInteractionListener({
  13579. // /**
  13580. // *广告的点击回调
  13581. // * @param type 广告的交互类型
  13582. // */
  13583. // onAdClicked: (type: number) => {
  13584. // console.log("BannerExpressAdPage==onAdClicked......");
  13585. // },
  13586. //
  13587. // /**
  13588. // * 广告的展示回调 每个广告仅回调一次
  13589. // * @param type 广告的交互类型
  13590. // */
  13591. // onAdShow: (type: number) => {
  13592. // console.log("BannerExpressAdPage==onAdShow......");
  13593. // },
  13594. //
  13595. // /**
  13596. // * 模板渲染失败
  13597. // */
  13598. // onRenderFail: (code: number, msg: string) => {
  13599. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  13600. // },
  13601. //
  13602. // /**
  13603. // * 模板渲染成功
  13604. // * @param width 返回view的宽 单位 vp
  13605. // * @param height 返回view的高 单位 vp
  13606. // */
  13607. // onRenderSuccess: (width: number, height: number) => {
  13608. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  13609. // this.bannerAd = ad;
  13610. // this.status = "广告加载完成待展示";
  13611. //
  13612. // this.showBannerAd()
  13613. // }
  13614. // })
  13615. // //渲染广告
  13616. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  13617. // this.setDislikeCallback(ad); //设置dislike
  13618. // ad.render(this.getUIContext())
  13619. // this.status = "广告加载中...";
  13620. // });
  13621. // }
  13622. // }
  13623. // }
  13624. //
  13625. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  13626. // ad.setDislikeCallback({
  13627. // /**
  13628. // * dislike show
  13629. // */
  13630. // onShow: () => {
  13631. // console.log("BannerExpressAdPage==dislike......show");
  13632. // },
  13633. //
  13634. // /**
  13635. // * @param position 选择的位置
  13636. // * @param value 选择的内容
  13637. // * @param enforceRemove 是否强制关闭广告
  13638. // */
  13639. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  13640. // this.isShowAd = false;
  13641. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  13642. // ",enforce=" + enforceRemove);
  13643. // },
  13644. //
  13645. // /**
  13646. // * 点击取消
  13647. // */
  13648. // onCancel: () => {
  13649. // console.log("BannerExpressAdPage==dislike......onCancel");
  13650. // }
  13651. //
  13652. // })
  13653. // }
  13654. /**
  13655. * 加载Banner广告
  13656. */
  13657. loadBannerAd(rit: string) {
  13658. // if (Utility.isNoble()) {
  13659. // return
  13660. // }
  13661. // if (!Utility.isPassInstallTime(2)) {
  13662. // return
  13663. // }
  13664. // this.isShowAd = false;
  13665. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  13666. // this.mAdSlot = new AdSlotBuilder()
  13667. // .setCodeId(rit)
  13668. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  13669. // .setAdCount(1)
  13670. // .setBidAdm(this.mBiddingAdm)
  13671. // .build()
  13672. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  13673. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  13674. // this.status = "广告加载中..."
  13675. }
  13676. /**
  13677. * 展示Banner广告
  13678. */
  13679. // showBannerAd() {
  13680. // if (!this.bannerAd) {
  13681. // return
  13682. // }
  13683. // this.isShowAd = true
  13684. // this.status = "已展示"
  13685. // }
  13686. /**
  13687. * 穿山甲广告代码结束
  13688. */
  13689. /**
  13690. * 处理歌单播放请求
  13691. */
  13692. private async handlePlaylistPlayRequest(playlistId: string, playlistName:
  13693. string, songFilePaths: string[], startIndex: number,isJump: boolean) {
  13694. try {
  13695. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 歌曲数量: ${songFilePaths.length}, 开始索引: ${startIndex}`)
  13696. // 检查是否为WebDAV播放请求
  13697. if (playlistId === 'webdav-playlist') {
  13698. Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
  13699. // 从全局内存读取videoItems数据
  13700. const videoItems = getWebdavVideoItems();
  13701. const currentPlayIndex = getWebdavCurrentPlayIndex();
  13702. Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
  13703. if (videoItems && videoItems.length > 0) {
  13704. // 验证webdav_account_id设置情况
  13705. const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
  13706. Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
  13707. if(isJump){
  13708. this.setShowPlayTrue()//显示播放页
  13709. }
  13710. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName)
  13711. return
  13712. } else {
  13713. return
  13714. }
  13715. }
  13716. if (playlistId === 'navidrome-playlist') {
  13717. Logger.info(`heanup 检测到Navidrome播放请求,从内存读取videoItems`);
  13718. const videoItems = getNavidromeVideoItems();
  13719. const currentPlayIndex = getNavidromeCurrentPlayIndex();
  13720. Logger.info(`heanup Navidrome歌曲列表长度: ${videoItems.length}`);
  13721. if (videoItems && videoItems.length > 0) {
  13722. if(isJump){
  13723. this.setShowPlayTrue()//显示播放页
  13724. }
  13725. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName);
  13726. return;
  13727. } else {
  13728. Logger.warn('heanup Navidrome播放请求缺少歌曲数据');
  13729. return;
  13730. }
  13731. }
  13732. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  13733. const songMap: Map<number, VideoItem> = new Map()
  13734. let completedQueries = 0
  13735. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  13736. // 遍历所有文件路径,使用索引记录位置
  13737. for (let i = 0; i < songFilePaths.length; i++) {
  13738. const filePath = songFilePaths[i]
  13739. const index = i
  13740. // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  13741. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  13742. const queryPromise = this.table.queryVideoByFilePath(filePath)
  13743. // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  13744. queryPromise.then((videoItem) => {
  13745. completedQueries++
  13746. // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  13747. if (videoItem) {
  13748. // 使用索引作为key保存到Map中,保持原始顺序
  13749. songMap.set(index, videoItem)
  13750. // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  13751. } else {
  13752. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  13753. }
  13754. // 检查是否所有歌曲都已加载完成
  13755. if (completedQueries === songFilePaths.length) {
  13756. // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  13757. // 按照索引顺序重建歌曲数组
  13758. const songs: VideoItem[] = []
  13759. for (let j = 0; j < songFilePaths.length; j++) {
  13760. const song = songMap.get(j)
  13761. if (song) {
  13762. songs.push(song)
  13763. // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  13764. }
  13765. }
  13766. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  13767. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  13768. }
  13769. }).catch((error: Error) => {
  13770. completedQueries++
  13771. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  13772. // 即使出错也要检查是否完成所有查询
  13773. if (completedQueries === songFilePaths.length) {
  13774. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  13775. // 按照索引顺序重建歌曲数组
  13776. const songs: VideoItem[] = []
  13777. for (let j = 0; j < songFilePaths.length; j++) {
  13778. const song = songMap.get(j)
  13779. if (song) {
  13780. songs.push(song)
  13781. }
  13782. }
  13783. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  13784. }
  13785. })
  13786. }
  13787. } catch (error) {
  13788. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  13789. ToastUtil.showToast('播放失败')
  13790. }
  13791. }
  13792. /**
  13793. * 完成歌单加载并开始播放
  13794. */
  13795. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string) {
  13796. if (songs.length === 0) {
  13797. Logger.error('heanup 没有找到任何可播放的歌曲')
  13798. ToastUtil.showToast('没有找到可播放的歌曲')
  13799. return
  13800. }
  13801. this.songList = songs
  13802. this.sonDataSource.pushArrayData(songs)
  13803. this.sonDataSource.notifyDataReload()
  13804. this.curIndex = startIndex
  13805. if (songs[startIndex]) {
  13806. // 确保当前播放的歌曲也更新到存储
  13807. AppStorage.setOrCreate('currentSong', songs[startIndex])
  13808. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  13809. this.doPlay(songs[startIndex], startIndex, true)
  13810. }
  13811. PreferencesUtil.putSync('LastMusicList', this.songList)
  13812. // ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  13813. }
  13814. }
  13815. //视频气泡窗口的布局
  13816. @Builder
  13817. function customPopupBuilder(dataBu: BubbleBean) {
  13818. List() {
  13819. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  13820. ListItem() {
  13821. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13822. Row() {
  13823. Column() {
  13824. Image(dataBu.imageRes[index])
  13825. .height(28)
  13826. .fillColor(dataBu.color)
  13827. .alignSelf(ItemAlign.Center)
  13828. }
  13829. .width(32)
  13830. Text(item)
  13831. .padding({
  13832. top: 10,
  13833. bottom: 10,
  13834. right: 10,
  13835. left: 10
  13836. })
  13837. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  13838. .textAlign(TextAlign.Start)
  13839. .width("100%")
  13840. }
  13841. }
  13842. .backgroundColor($r('app.color.settings_background_main'))
  13843. .margin({ top: 6, bottom: 6 })
  13844. }
  13845. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  13846. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  13847. TransitionEffect.scale({ x: 0, y: 0 })))
  13848. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  13849. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  13850. .onClick(() => {
  13851. dataBu.onItemClick?.(index)
  13852. })
  13853. })
  13854. }
  13855. .scrollBar(BarState.Off)
  13856. .width(120)
  13857. .divider({
  13858. strokeWidth: 1,
  13859. color: "#22FFFFFF"
  13860. })
  13861. }
  13862. // Function to calculate a hash for the file list
  13863. function simpleHash(fileList: string[]): string {
  13864. let hash = 0;
  13865. const str = fileList.join(',');
  13866. for (let i = 0; i < str.length; i++) {
  13867. const char = str.charCodeAt(i);
  13868. hash = (hash << 5) - hash + char;
  13869. hash |= 0; // Convert to 32bit integer
  13870. }
  13871. return hash.toString();
  13872. }
  13873. interface MoreItem {
  13874. id: number;
  13875. image: Resource;
  13876. title: string;
  13877. }
  13878. //视频气泡窗口的布局
  13879. @Builder
  13880. function cutPopupBuilder(dataBu: BubbleBean) {
  13881. Column() {
  13882. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  13883. .padding({
  13884. top: 10,
  13885. bottom: 10,
  13886. right: 10,
  13887. left: 10
  13888. })
  13889. .textAlign(TextAlign.Start)
  13890. .width(160)
  13891. .fontWeight(666)
  13892. .fontSize(16)
  13893. List() {
  13894. ForEach(dataBu.data, (item: string, index: number) => {
  13895. ListItem() {
  13896. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13897. Row() {
  13898. Column() {
  13899. Image($r('app.media.music_group'))
  13900. .height(28)
  13901. .fillColor(dataBu.color)
  13902. .alignSelf(ItemAlign.Center)
  13903. }
  13904. .width(32)
  13905. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  13906. .padding({
  13907. top: 10,
  13908. bottom: 10,
  13909. right: 10,
  13910. left: 10
  13911. })
  13912. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  13913. .fontSize(15)
  13914. }
  13915. }
  13916. .backgroundColor(Color.Transparent)
  13917. .margin({ top: 7, bottom: 7 })
  13918. }
  13919. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  13920. .animation({ duration: 500 }),
  13921. TransitionEffect.scale({ x: 0, y: 0 })))
  13922. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  13923. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  13924. .onClick(() => {
  13925. dataBu.onItemClick?.(index)
  13926. })
  13927. })
  13928. }
  13929. .scrollBar(BarState.Off)
  13930. .width(150)
  13931. .divider({
  13932. strokeWidth: 1,
  13933. color: "#22FFFFFF"
  13934. })
  13935. }
  13936. .height(300)
  13937. .padding({
  13938. bottom: 30
  13939. })
  13940. }
  13941. function getFileDirName(filePath: string,rootPath:string): string{
  13942. if(filePath===rootPath){
  13943. return '首页'
  13944. }
  13945. let result = FileUtil.getFileName(filePath)
  13946. if(StrUtil.isEmpty(result))
  13947. return ''
  13948. if(result.startsWith('.'))
  13949. result = result.replace(/\./g, '')
  13950. return result
  13951. }
  13952. //只扫描当前目录下文件(不扫描子文件夹)的方法
  13953. @Concurrent
  13954. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  13955. const table: MediaTable = new MediaTable(context);
  13956. try {
  13957. // 直接获取当前目录下的文件列表
  13958. const files = FileUtil.listFileSync(dirPath);
  13959. await Promise.all(files.map(async (file) => {
  13960. const fPath = `${dirPath}/${file}`;
  13961. // 跳过目录,只处理文件
  13962. if (FileUtil.isDirectory(fPath)) {
  13963. return;
  13964. }
  13965. // 跳过特定格式文件
  13966. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  13967. return;
  13968. }
  13969. // 检查是否为媒体文件
  13970. if (Utility.isMeidaByExtension(fPath)) {
  13971. let mType = CommonConstants.TYPE_LOCAL;
  13972. if (fPath.includes(lockPath)) {
  13973. mType = CommonConstants.TYPE_LOCK;
  13974. }
  13975. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  13976. context, fPath, mType, true
  13977. );
  13978. table.insert(mediaItem, (id: number) => {
  13979. // 插入回调函数
  13980. }, cover_api);
  13981. }
  13982. }));
  13983. } catch (error) {
  13984. console.error(' 扫描当前目录失败:', error);
  13985. }
  13986. }
  13987. //内嵌标签后更新库
  13988. @Concurrent
  13989. async function updateInfoDb(
  13990. context: Context,
  13991. filePath: string,
  13992. titleStr: string,
  13993. artistStr: string,
  13994. albumStr: string,
  13995. lyricConStr: string,
  13996. yearStr: string,
  13997. genreStr: string,
  13998. trackStr: string,
  13999. albumArtistStr: string,
  14000. composerStr: string,
  14001. lyricistStr: string,
  14002. commentStr: string,
  14003. discStr: string,
  14004. ): Promise<boolean> {
  14005. const table: MediaTable = new MediaTable(context);
  14006. await new Promise<void>((resolve, reject) => {
  14007. table.getRdbStore(context, (err:Error) => {
  14008. err ? reject(err) : resolve();
  14009. });
  14010. });
  14011. return await new Promise<boolean>((resolve) => {
  14012. table.updateMediaInfo(filePath, titleStr, artistStr, albumStr, lyricConStr,
  14013. yearStr, genreStr, trackStr, albumArtistStr, composerStr, lyricistStr, commentStr, discStr,
  14014. (success: boolean, error?: string) => {
  14015. if (success) {
  14016. console.log("onecold 编辑信息成功,数据库已同步");
  14017. } else {
  14018. console.error("onecold 编辑信息数据库失败原因: " + error);
  14019. }
  14020. resolve(success);
  14021. });
  14022. });
  14023. }