LocalMusic.ets 542 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577
  1. import TitleBar from './TitleBar'
  2. import { curves, display, MenuModifier,PiPWindow, promptAction, router, SymbolGlyphModifier, window } from '@kit.ArkUI';
  3. import { VideoItem } from '../viewmodel/VideoItem';
  4. import { LengthMetrics, SegmentButton,SegmentButtonOptions } from '@kit.ArkUI';
  5. import { getWebdavVideoItems, getWebdavCurrentPlayIndex } from '../pages/WebDavMainPage';
  6. import { getNavidromeVideoItems, getNavidromeCurrentPlayIndex } from '../common/util/NavidromePlaylistStore';
  7. import {
  8. ButtonFancyModifier,
  9. ImageFancyModifier,
  10. ShadowModifier,
  11. SymbolGlyphFancyModifier } from '../common/util/AttributeModifierUtil'
  12. import {
  13. AppUtil,
  14. ArrayUtil,
  15. Base64Util,
  16. DateUtil,
  17. DeviceUtil,
  18. FileUtil,
  19. GlobalContext,
  20. LogUtil,
  21. MD5,
  22. PreferencesUtil,
  23. RandomUtil,
  24. StrUtil,
  25. ToastUtil
  26. } from '@pura/harmony-utils';
  27. import { imagePathToPixelMap } from '../common/util/CommUtils';
  28. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  29. import { CommonConstants } from '../common/constants/CommonConstants';
  30. import { BaiduConstants } from '../common/constants/BaiduConstants';
  31. import { EventConstants } from '../common/constants/EventConstants';
  32. import Logger from '../common/util/Logger';
  33. import { http } from '@kit.NetworkKit';
  34. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  35. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  36. import { BubbleBean } from '../viewmodel/BubbleBean';
  37. import { PopupPosition, XPopup } from '@chinalike/popup';
  38. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  39. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  40. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  41. import { MessageEvents, util, worker, ErrorEvent, JSON } from '@kit.ArkTS';
  42. import { Verify } from './Verify';
  43. import { taskpool } from '@kit.ArkTS';
  44. import { RotatingCover } from './RotatingCover';
  45. import { PointLightButton } from './PointLight/PointLightButton';
  46. import { PlayConstants } from '../common/constants/PlayConstants';
  47. import { effectKit } from '@kit.ArkGraphics2D';
  48. import { ColorConversion } from '../common/util/ColorConversion';
  49. import { LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  50. import { AvSessionController } from '../controller/AvSessionController';
  51. import { repairAudioMetadata, convertDsfToWav, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  52. import { extractHwMediaMetadata, FFMpegTags,Utility } from '../common/util/Utility';
  53. import { TagsContentCover } from '../view/TagsContentCover';
  54. import {
  55. DeviceChangeReason,
  56. IjkMediaPlayer,
  57. InterruptEvent,
  58. InterruptHintType,
  59. LogUtils,
  60. OnBufferingUpdateListener,
  61. OnCompletionListener,
  62. OnErrorListener,
  63. OnInfoListener,
  64. OnPreparedListener,
  65. OnSeekCompleteListener,
  66. OnTimedTextListener,
  67. OnVideoSizeChangedListener
  68. } from '@ohos/ijkplayer';
  69. import { PlayStatus } from '../common/PlayStatus';
  70. import fs from '@ohos.file.fs';
  71. import { image } from '@kit.ImageKit';
  72. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  73. import { UniversalDetector } from '@ohos/juniversalchardet';
  74. import { SettingPage } from '../pages/SettingPage';
  75. import { secondToTime,getTransverterText } from '../common/util/CommUtils';
  76. import { CommonConstants2 } from '../common/util/CommonConstants2';
  77. import { hilog } from '@kit.PerformanceAnalysisKit';
  78. import { LazyDataSource } from '../common/util/LazyDataSource';
  79. import MediaTable from '../common/util/MediaTable';
  80. import FileDeletionWatcher from '../common/util/FileDeletionWatcher';
  81. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  82. import ImageUtils from '../common/util/ImageUtils';
  83. import { ringtone } from '@kit.RingtoneKit';
  84. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  85. import { resourceManager } from '@kit.LocalizationKit';
  86. import { deviceInfo } from '@kit.BasicServicesKit';
  87. import { RemoteCacheManager } from '../common/network/RemoteCacheManager';
  88. import '../common/network/RemoteCacheRegistry';
  89. import { RemoteCacheType, resolveCacheFilePath } from '../common/network/RemoteSongCache';
  90. import { findWebDavCacheIfExists, triggerWebDavCacheDownload } from '../common/network/WebDavFileCache';
  91. import { navidromeApi } from '../common/network/NavidromeApi';
  92. import { jellyfinApi } from '../common/network/JellyfinApi';
  93. import { embyApi } from '../common/network/EmbyApi';
  94. import { ServerLogUtil } from '../common/util/ServerLogUtil';
  95. import { ensureSmbFileStreaming, SmbStreamingMeta } from '../common/network/SmbFileCache';
  96. import { ensureBaiduFileCached } from '../common/network/BaiduFileCache';
  97. import FileManager from '../common/util/FileManager';
  98. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  99. import app from '@system.app';
  100. import { TextNodeController } from './PipLyricTextBuilder';
  101. import { IndexerView } from './IndexerView';
  102. import { KeyCode } from '@kit.InputKit';
  103. import { KnockController } from '../controller/KnockController';
  104. import { DeleteComptent } from '../view/DeleteComptent';
  105. import { ABLoopComptent } from '../view/ABLoopComptent';
  106. import { FixMessyView } from '../view/FixMessyView';
  107. import { parseCueFile,CueTrack,CueInfo } from '../common/util/CueUtils';
  108. import { CueComptent } from '../view/CueComptent';
  109. import PlaylistTable from '../common/util/PlaylistTable';
  110. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  111. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  112. import { convertPlaylistSongsToVideoItems, emptyView,updateAllSongsSortOrder } from '../pages/PlaylistDetailPage';
  113. import { Playlist, PlaylistSong } from '../viewmodel/Playlist';
  114. import { Song } from '../viewmodel/Song';
  115. import { SongType } from '../common/enums/SongType';
  116. import { RemoteDriveManager, WebDavAuthInfo as WebDavManagerAuthInfo,
  117. buildHttpHeadersWithWebDav,
  118. WebDavAuthItem} from '../common/util/RemoteDriveManager';
  119. import PermissionUtil from '../common/util/PermissionUtil'
  120. import { EditAudio, setRingTone } from './EditAudio';
  121. import { ExtractAccompaniment } from './ExtractAccompaniment';
  122. import { ExtractAudioFromVideo } from './ExtractAudioFromVideo';
  123. import { AudioFormatConverter } from './AudioFormatConverter';
  124. import { MergeAudio } from './MergeAudio';
  125. import { AIVoiceSeparation } from './AIVoiceSeparation';
  126. import { WebDavUrlUtil } from '../common/util/WebDavUrlUtil';
  127. import { ChangeTone } from './ChangeTone';
  128. import {
  129. hdsEffect,
  130. HdsVisualComponent,
  131. HdsSceneController,
  132. HdsSceneType,
  133. HdsVisualComponentAttribute,
  134. } from '@kit.UIDesignKit';
  135. import { GlobalAlphabetIndexerModifier } from '../Styels/GlobalStyles'
  136. import { getFirstLetter } from '../Constants';
  137. import { audio } from '@kit.AudioKit';
  138. const TAG = 'LocalMusic';
  139. const HICAR_LOG_TAG = 'HiCarWindow';
  140. function logHiCarWindow(message: string): void {
  141. void ServerLogUtil.info(HICAR_LOG_TAG, message);
  142. }
  143. /**
  144. * 歌单播放事件数据
  145. */
  146. interface PlaylistEventData {
  147. playlistId: string;
  148. playlistName: string;
  149. songCount: number;
  150. startIndex: number;
  151. songFilePaths: string[];
  152. isJump: boolean;
  153. webDavAuthInfo?: WebDavAuthItem; // 新增WebDAV认证信息
  154. }
  155. const DEFAULT_INDEX =
  156. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  157. 'X', 'Y', 'Z']
  158. //排序类型
  159. function getTypeOrder(type: number) {
  160. switch (type) {
  161. case CommonConstants.TYPE_IS_DIR:
  162. return 1; // First
  163. case CommonConstants.TYPE_IS_CSJAD:
  164. return 2; // Middle
  165. case CommonConstants.TYPE_LOCAL:
  166. return 3; // Last
  167. case CommonConstants.TYPE_WEBDAV:
  168. case CommonConstants.TYPE_SMB:
  169. case CommonConstants.TYPE_NAVIDROME:
  170. case CommonConstants.TYPE_FTP:
  171. case CommonConstants.TYPE_BAIDU:
  172. case CommonConstants.TYPE_JELLYFIN:
  173. case CommonConstants.TYPE_EMBY:
  174. return 3;
  175. default:
  176. return 4; // Unknown types, if any, go last
  177. }
  178. }
  179. function isWebDavType(type: number): boolean {
  180. return type === CommonConstants.TYPE_WEBDAV;
  181. }
  182. function isSmbType(type: number): boolean {
  183. return type === CommonConstants.TYPE_SMB;
  184. }
  185. function isNavidromeType(type: number): boolean {
  186. return type === CommonConstants.TYPE_NAVIDROME;
  187. }
  188. function isFtpType(type: number): boolean {
  189. return type === CommonConstants.TYPE_FTP;
  190. }
  191. function isBaiduType(type: number): boolean {
  192. return type === CommonConstants.TYPE_BAIDU;
  193. }
  194. function isJellyfinType(type: number): boolean {
  195. return type === CommonConstants.TYPE_JELLYFIN;
  196. }
  197. function isEmbyType(type: number): boolean {
  198. return type === CommonConstants.TYPE_EMBY;
  199. }
  200. function isRemoteCloudType(type: number): boolean {
  201. return isWebDavType(type) || isSmbType(type) || isNavidromeType(type) || isFtpType(type) || isBaiduType(type) || isJellyfinType(type) || isEmbyType(type);
  202. }
  203. function getShareNameFromFilePath(filePath?: string): string | undefined {
  204. if (!filePath) {
  205. return undefined;
  206. }
  207. const match = filePath.match(/^smb:\/\/[^/]+\/([^/]+)/i);
  208. return match && match[1] ? match[1] : undefined;
  209. }
  210. function removeSharePrefixFromPath(path: string, primaryShare?: string, secondaryShare?: string): string {
  211. const uniqueShares: string[] = [];
  212. [primaryShare, secondaryShare].forEach((name?: string) => {
  213. const cleaned = name ? name.replace(/^\/+|\/+$/g, '') : '';
  214. if (cleaned.length > 0 && !uniqueShares.some(item => item.toLowerCase() === cleaned.toLowerCase())) {
  215. uniqueShares.push(cleaned);
  216. }
  217. });
  218. if (uniqueShares.length === 0) {
  219. return path;
  220. }
  221. let result = path;
  222. for (let i = 0; i < uniqueShares.length; i++) {
  223. const share = uniqueShares[i];
  224. const lowerPath = result.toLowerCase();
  225. const lowerShare = share.toLowerCase();
  226. if (lowerPath === lowerShare) {
  227. result = '';
  228. break;
  229. }
  230. const prefix = `${lowerShare}/`;
  231. if (lowerPath.startsWith(prefix)) {
  232. result = result.substring(share.length + 1);
  233. break;
  234. }
  235. }
  236. return result;
  237. }
  238. function extractSmbRelativePath(song: VideoItem, shareNameOverride?: string): string {
  239. const shareFromFilePath = getShareNameFromFilePath(song.filePath);
  240. const shareName = shareNameOverride ?? shareFromFilePath;
  241. if (song.remote_rel_path && song.remote_rel_path.length > 0) {
  242. const cleaned = song.remote_rel_path.replace(/^\/+/, '');
  243. return removeSharePrefixFromPath(cleaned, shareName, shareFromFilePath);
  244. }
  245. if (!song.filePath) {
  246. return '';
  247. }
  248. const match = song.filePath.match(/^smb:\/\/[^/]+\/([^/]+)(\/.*)?$/i);
  249. if (!match) {
  250. return song.filePath.replace(/^\/+/, '');
  251. }
  252. const remainder = match[2] ? match[2].replace(/^\/+/, '') : '';
  253. if (remainder.length === 0) {
  254. return '';
  255. }
  256. return remainder;
  257. }
  258. function extractFtpRelativePath(song: VideoItem): string {
  259. if (song.remote_rel_path && song.remote_rel_path.length > 0) {
  260. return song.remote_rel_path.replace(/^\/+/, '');
  261. }
  262. if (!song.filePath) {
  263. return '';
  264. }
  265. const match = song.filePath.match(/^ftp:\/\/[^/]+(?::\d+)?(\/.*)$/i);
  266. if (match && match[1]) {
  267. return match[1].replace(/^\/+/, '');
  268. }
  269. return song.filePath.replace(/^\/+/, '');
  270. }
  271. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  272. interface MetadataExtractionOptions {
  273. context?: common.Context;
  274. autoParseMusicName?: boolean;
  275. }
  276. interface WorkerEditMusicResult {
  277. success: boolean;
  278. error?: string;
  279. coverResult?: boolean;
  280. needRefreshList?: boolean;
  281. metadataResult?: boolean;
  282. }
  283. interface LocalEditMusicPayload {
  284. context: Context;
  285. item: VideoItem;
  286. titleStr: string;
  287. artistStr: string;
  288. ablumStr: string;
  289. yearStr: string;
  290. genreStr: string;
  291. trackStr: string;
  292. albumArtistStr: string;
  293. composerStr: string;
  294. lyricistStr: string;
  295. commentStr: string;
  296. discStr: string;
  297. lyricConStr: string;
  298. imagePathStr: string;
  299. currentPath: string;
  300. packName: string;
  301. modeType: number;
  302. autoParseMusicName: boolean;
  303. }
  304. interface WorkerMetadataPayload {
  305. originFilePath: string;
  306. originId?: string;
  307. bit_rate?: string;
  308. duration?: string;
  309. sampleRate?: string;
  310. mimeType?: string;
  311. md5Str?: string;
  312. videoSize?: number;
  313. size?: string;
  314. pixelMapPath?: string;
  315. artist?: string;
  316. album?: string;
  317. name?: string;
  318. lyricContent?: string;
  319. bits_per_raw_sample?: string;
  320. channels?: string;
  321. channel_layout?: string;
  322. start_time?: string;
  323. genre?: string;
  324. year?: string;
  325. probe_score?: number;
  326. track?: string;
  327. disc?: string;
  328. ALBUMARTIST?: string;
  329. COMPOSER?: string;
  330. COMMENT?: string;
  331. LYRICIST?: string;
  332. nb_streams?: number;
  333. nb_programs?: number;
  334. error?: string;
  335. }
  336. interface WebDavMetadataUpdatePayload {
  337. filePath: string;
  338. pixelMapPath?: string;
  339. name?: string;
  340. artist?: string;
  341. }
  342. const metadataExtractionInFlight: Set<string> = new Set();
  343. const METADATA_RETRY_DELAY_MS = 1500;
  344. const METADATA_MAX_RETRY = 120;
  345. async function scheduleMetadataExtractionFromCache(
  346. song: VideoItem,
  347. cachePath: string,
  348. options?: MetadataExtractionOptions,
  349. expectedSize?: number,
  350. retryCount: number = 0
  351. ): Promise<void> {
  352. if (!song || !cachePath || !song.filePath || !options || !options.context) {
  353. return;
  354. }
  355. if (!isRemoteCloudType(song.type ?? -1)) {
  356. return;
  357. }
  358. if (metadataExtractionInFlight.has(song.filePath)) {
  359. return;
  360. }
  361. if (song.bit_rate && song.sampleRate && song.duration) {
  362. return;
  363. }
  364. const requiredSize = expectedSize && expectedSize > 0 ? expectedSize : undefined;
  365. try {
  366. const stat = await fileIo.stat(cachePath);
  367. const ready = requiredSize !== undefined ? stat.size >= requiredSize : stat.size > 0;
  368. if (!ready) {
  369. if (retryCount >= METADATA_MAX_RETRY) {
  370. Logger.warn(TAG, `缓存尚未完成,放弃解析: ${cachePath}`);
  371. return;
  372. }
  373. setTimeout(() => {
  374. void scheduleMetadataExtractionFromCache(song, cachePath, options, expectedSize, retryCount + 1);
  375. }, METADATA_RETRY_DELAY_MS);
  376. return;
  377. }
  378. } catch (error) {
  379. if (retryCount >= METADATA_MAX_RETRY) {
  380. Logger.warn(TAG, `无法读取缓存文件,放弃解析: ${(error as Error).message}`);
  381. return;
  382. }
  383. setTimeout(() => {
  384. void scheduleMetadataExtractionFromCache(song, cachePath, options, expectedSize, retryCount + 1);
  385. }, METADATA_RETRY_DELAY_MS);
  386. return;
  387. }
  388. metadataExtractionInFlight.add(song.filePath);
  389. workerInstance.postMessage({
  390. code: 5,
  391. data: options.context,
  392. data2: cachePath,
  393. data3: song.type,
  394. data4: {
  395. name: song.name,
  396. originFilePath: song.filePath,
  397. originId: song.id,
  398. autoParseMusicName: options.autoParseMusicName ?? false
  399. }
  400. });
  401. }
  402. function sanitizePlaybackUrl(rawUrl: string | null | undefined): string {
  403. if (!rawUrl) {
  404. return '';
  405. }
  406. try {
  407. const decoded = decodeURI(rawUrl);
  408. const encoded = encodeURI(decoded);
  409. // encodeURI 不会处理 #,手动转义避免播放器把剩余内容当作片段
  410. return encoded.replace(/#/g, '%23');
  411. } catch (error) {
  412. const err = error as Error;
  413. Logger.warn(TAG, `URL 编码失败,使用降级方案: ${err?.message}`);
  414. return rawUrl.replace(/ /g, '%20').replace(/#/g, '%23');
  415. }
  416. }
  417. function cloneVideoItem(item: VideoItem): VideoItem {
  418. const copy = new VideoItem(
  419. item.name,
  420. item.id,
  421. item.filePath,
  422. item.type,
  423. item.videoSize,
  424. item.cTime,
  425. item.size,
  426. item.pixelMapPath,
  427. item.artist,
  428. item.album,
  429. item.fileName,
  430. item.lastPlayed
  431. );
  432. copy.parentPath = item.parentPath;
  433. copy.isFav = item.isFav;
  434. copy.size = item.size;
  435. copy.pixelMapPath = item.pixelMapPath;
  436. copy.artist = item.artist;
  437. copy.album = item.album;
  438. copy.duration = item.duration;
  439. copy.mimeType = item.mimeType;
  440. copy.sampleRate = item.sampleRate;
  441. copy.trackCount = item.trackCount;
  442. copy.lastPlayedStr = item.lastPlayedStr;
  443. copy.playCount = item.playCount;
  444. copy.lyricContent = item.lyricContent;
  445. copy.md5Str = item.md5Str;
  446. copy.extra_json = item.extra_json;
  447. copy.pyStr = item.pyStr;
  448. copy.bit_rate = item.bit_rate;
  449. copy.probe_score = item.probe_score;
  450. copy.year = item.year;
  451. copy.nb_streams = item.nb_streams;
  452. copy.nb_programs = item.nb_programs;
  453. copy.genre = item.genre;
  454. copy.track = item.track;
  455. copy.bits_per_raw_sample = item.bits_per_raw_sample;
  456. copy.channels = item.channels;
  457. copy.channel_layout = item.channel_layout;
  458. copy.start_time = item.start_time;
  459. copy.ALBUMARTIST = item.ALBUMARTIST;
  460. copy.COMPOSER = item.COMPOSER;
  461. copy.LYRICIST = item.LYRICIST;
  462. copy.COMMENT = item.COMMENT;
  463. copy.disc = item.disc;
  464. copy.webdav_account_id = item.webdav_account_id;
  465. copy.remote_rel_path = item.remote_rel_path;
  466. return copy;
  467. }
  468. /**
  469. * 异步设置videoUrl的辅助方法,处理WebDAV URL的构建
  470. * @param song 歌曲对象
  471. * @returns Promise<string> 完整的URL
  472. */
  473. /**
  474. * 设置videoUrl,通过webdav_account_id设置完整的 URL
  475. * @param song 歌曲对象
  476. * @returns Promise<string> 完整的URL
  477. */
  478. async function setVideoUrlForSong(song: VideoItem, options?: MetadataExtractionOptions): Promise<string> {
  479. const metadataOptions = options ?? {};
  480. Logger.info(TAG, `setVideoUrlForSong start -> name=${song.name}, type=${song.type}, path=${song.filePath}, fsId=${song.baiduFsId || song.id}`);
  481. if (isWebDavType(song.type) && song.webdav_account_id) {
  482. try {
  483. Logger.info(TAG, `WebDAV 路径信息 remote_rel_path: ${song.remote_rel_path}`);
  484. Logger.info(TAG, `WebDAV 路径信息 filePath: ${song.filePath}`);
  485. const relativePath = song.remote_rel_path || song.filePath;
  486. const manager = RemoteDriveManager.getInstance();
  487. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  488. if (account) {
  489. const cachePath = await findWebDavCacheIfExists(account, relativePath);
  490. if (cachePath) {
  491. Logger.info(TAG, `WebDAV 缓存命中,直接播放: ${cachePath}`);
  492. void scheduleMetadataExtractionFromCache(song, cachePath, metadataOptions, song.videoSize);
  493. return cachePath;
  494. }
  495. const fullUrlFromAccount = WebDavUrlUtil.buildFullUrl(account, relativePath);
  496. if (fullUrlFromAccount) {
  497. const sanitizedUrl = sanitizePlaybackUrl(fullUrlFromAccount);
  498. const downloadPromise = triggerWebDavCacheDownload(account, relativePath, sanitizedUrl);
  499. if (downloadPromise) {
  500. downloadPromise.then((completedPath?: string | null) => {
  501. if (completedPath) {
  502. void scheduleMetadataExtractionFromCache(song, completedPath, metadataOptions, song.videoSize);
  503. }
  504. }).catch((error: Error) => {
  505. Logger.error(TAG, `WebDAV 缓存后台下载失败: ${error.message}`);
  506. });
  507. }
  508. Logger.info(TAG, `WebDAV 启动异步缓存: ${relativePath}`);
  509. return sanitizedUrl;
  510. }
  511. }
  512. const fallbackUrl = await WebDavUrlUtil.buildFullUrlByAccountId(song.webdav_account_id, relativePath);
  513. if (fallbackUrl) {
  514. Logger.warn(TAG, `WebDAV 使用全局查询到的URL: ${fallbackUrl}`);
  515. return sanitizePlaybackUrl(fallbackUrl);
  516. }
  517. Logger.error(TAG, `WebDAV URL构建失败,使用原始路径: ${relativePath}`);
  518. return sanitizePlaybackUrl(relativePath);
  519. } catch (error) {
  520. Logger.error(TAG, `WebDAV URL构建出错: ${(error as Error).message}`);
  521. const fallbackPath = song.remote_rel_path || song.filePath;
  522. return sanitizePlaybackUrl(fallbackPath);
  523. }
  524. }
  525. if (isNavidromeType(song.type) && song.webdav_account_id) {
  526. try {
  527. const manager = RemoteDriveManager.getInstance();
  528. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  529. if (!account) {
  530. throw new Error('Navidrome账号不可用');
  531. }
  532. const navSongId = song.remote_rel_path || song.id || song.filePath;
  533. const streamUrl = await navidromeApi.buildStreamUrl(account, navSongId);
  534. void ServerLogUtil.info(TAG, `流地址构建成功: ${streamUrl}`);
  535. void ServerLogUtil.debug(TAG, `播放songId=${navSongId}, account=${ServerLogUtil.sanitizeAccount(account)}`);
  536. return sanitizePlaybackUrl(streamUrl);
  537. } catch (error) {
  538. const err = error as Error;
  539. void ServerLogUtil.error(TAG, `URL构建失败: ${err.message}`);
  540. throw new Error(err.message);
  541. }
  542. }
  543. if (isJellyfinType(song.type) && song.webdav_account_id) {
  544. try {
  545. const manager = RemoteDriveManager.getInstance();
  546. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  547. if (!account) {
  548. throw new Error('Jellyfin账号不可用');
  549. }
  550. const jellyfinSongId = song.remote_rel_path || song.id || song.filePath;
  551. const streamUrl = await jellyfinApi.buildStreamUrl(account, jellyfinSongId);
  552. void ServerLogUtil.info(TAG, `Jellyfin 流地址构建成功: ${streamUrl}`);
  553. void ServerLogUtil.debug(TAG, `播放songId=${jellyfinSongId}, account=${ServerLogUtil.sanitizeAccount(account)}`);
  554. return sanitizePlaybackUrl(streamUrl);
  555. } catch (error) {
  556. const err = error as Error;
  557. void ServerLogUtil.error(TAG, `Jellyfin URL构建失败: ${err.message}`);
  558. throw new Error(err.message);
  559. }
  560. }
  561. if (isEmbyType(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('Emby账号不可用');
  567. }
  568. const embySongId = song.remote_rel_path || song.id || song.filePath;
  569. const streamUrl = await embyApi.buildStreamUrl(account, embySongId);
  570. void ServerLogUtil.info(TAG, `Emby 流地址构建成功: ${streamUrl}`);
  571. void ServerLogUtil.debug(TAG, `播放songId=${embySongId}, account=${ServerLogUtil.sanitizeAccount(account)}`);
  572. return sanitizePlaybackUrl(streamUrl);
  573. } catch (error) {
  574. const err = error as Error;
  575. void ServerLogUtil.error(TAG, `Emby URL构建失败: ${err.message}`);
  576. throw new Error(err.message);
  577. }
  578. }
  579. if (isSmbType(song.type) && song.webdav_account_id) {
  580. try {
  581. const manager = RemoteDriveManager.getInstance();
  582. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  583. if (!account) {
  584. throw new Error('SMB账号不可用');
  585. }
  586. const relativePath = extractSmbRelativePath(song, account.smbShare);
  587. const pathInfo = await resolveCacheFilePath(
  588. RemoteCacheType.SMB,
  589. account.id?.toString(),
  590. relativePath
  591. );
  592. const streamMeta: SmbStreamingMeta = {
  593. fileSize: song.videoSize,
  594. mimeType: song.mimeType,
  595. fileName: song.fileName || song.name
  596. };
  597. const streamingUrl = await ensureSmbFileStreaming(account, pathInfo.normalizedRelative, streamMeta);
  598. Logger.info(TAG, `SMB 流地址: ${streamingUrl}`);
  599. void scheduleMetadataExtractionFromCache(song, pathInfo.cachePath, metadataOptions, song.videoSize);
  600. const shouldBypassSanitize = streamingUrl.startsWith('http://127.0.0.1:');
  601. return shouldBypassSanitize ? streamingUrl : sanitizePlaybackUrl(streamingUrl);
  602. } catch (error) {
  603. const err = error as Error;
  604. Logger.error(TAG, `SMB 流式播放失败: ${err.message}`);
  605. throw new Error(err.message);
  606. }
  607. }
  608. if (isFtpType(song.type) && song.webdav_account_id) {
  609. try {
  610. const manager = RemoteDriveManager.getInstance();
  611. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  612. if (!account) {
  613. throw new Error('FTP账号不可用');
  614. }
  615. const relativePath = extractFtpRelativePath(song);
  616. const cachedPath = await RemoteCacheManager.ensureCached(RemoteCacheType.FTP, {
  617. account,
  618. remotePath: relativePath
  619. });
  620. Logger.info(TAG, `FTP 缓存路径: ${cachedPath}`);
  621. void scheduleMetadataExtractionFromCache(song, cachedPath, metadataOptions, song.videoSize);
  622. return cachedPath;
  623. } catch (error) {
  624. const err = error as Error;
  625. Logger.error(TAG, `FTP 缓存失败: ${err.message}`);
  626. throw new Error(err.message);
  627. }
  628. }
  629. if (isBaiduType(song.type) && song.webdav_account_id) {
  630. try {
  631. const manager = RemoteDriveManager.getInstance();
  632. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  633. if (!account) {
  634. throw new Error('百度网盘账户不可用');
  635. }
  636. Logger.info(TAG, `百度网盘播放准备 - accountId: ${account.id}, fsId: ${song.baiduFsId || song.id}`);
  637. const sanitizedAccount = ServerLogUtil.sanitizeAccount(account);
  638. void ServerLogUtil.info('BaiduStream', `准备播放百度歌曲: account=${sanitizedAccount}, fsId=${song.baiduFsId || song.id}`);
  639. const fsId = song.baiduFsId || song.id;
  640. if (!fsId) {
  641. throw new Error('缺少百度网盘文件fs_id');
  642. }
  643. // 优先使用remote_rel_path,回退到文件名
  644. const relativePath = song.remote_rel_path || song.name || song.fileName || song.filePath;
  645. const streamPath = song.remote_rel_path;
  646. const cachedPath = await resolveCacheFilePath(
  647. RemoteCacheType.BAIDU,
  648. account.id?.toString(),
  649. relativePath
  650. );
  651. const fileExists = await FileManager.isExist(cachedPath.cachePath);
  652. if (fileExists) {
  653. const fileSize = await FileManager.getFileSize(cachedPath.cachePath);
  654. if (fileSize > 0) {
  655. Logger.info(TAG, `百度网盘文件已缓存: ${cachedPath.cachePath}`);
  656. void scheduleMetadataExtractionFromCache(song, cachedPath.cachePath, metadataOptions, song.videoSize);
  657. return cachedPath.cachePath;
  658. }
  659. }
  660. // 缓存不存在或无效,获取文件信息(包含大小和下载链接)
  661. Logger.info(TAG, `百度网盘文件未缓存,准备获取文件信息: ${relativePath}`);
  662. const fileInfo = await manager.getBaiduFileInfo(account, fsId, streamPath);
  663. Logger.info(TAG, `百度网盘文件信息获取成功: 大小=${fileInfo.size}字节,流地址已获取`);
  664. void ServerLogUtil.info('BaiduStream', `音频流URL获取成功: ${fileInfo.streamUrl}`);
  665. // 立即返回媒体流地址,开始播放
  666. Logger.info(TAG, `返回音频流链接进行播放,同时后台缓存: ${fileInfo.streamUrl}`);
  667. // 异步进行缓存,不阻塞播放
  668. void (async () => {
  669. try {
  670. Logger.info(TAG, `后台开始缓存百度网盘文件: ${relativePath},大小: ${fileInfo.size}字节`);
  671. void ServerLogUtil.info('BaiduStream', `开始缓存百度文件: account=${sanitizedAccount}, path=${relativePath}`);
  672. const cachedFilePath = await ensureBaiduFileCached(
  673. account,
  674. fsId,
  675. relativePath,
  676. fileInfo.dlink,
  677. fileInfo.size
  678. );
  679. Logger.info(TAG, `后台缓存完成: ${cachedFilePath}`);
  680. void ServerLogUtil.info('BaiduStream', `缓存完成: ${cachedFilePath}`);
  681. void scheduleMetadataExtractionFromCache(song, cachedFilePath, metadataOptions, song.videoSize);
  682. } catch (cacheError) {
  683. const cacheErr = cacheError as Error;
  684. Logger.warn(TAG, `后台缓存失败: ${cacheErr.message}`);
  685. void ServerLogUtil.error('BaiduStream', `缓存失败: ${cacheErr.message}`);
  686. }
  687. })();
  688. return fileInfo.streamUrl;
  689. } catch (error) {
  690. const err = error as Error;
  691. Logger.error(TAG, `百度网盘播放链接获取失败: ${err.message}`);
  692. throw err;
  693. }
  694. }
  695. if (isWebDavType(song.type)) {
  696. Logger.warn(TAG, `WebDAV歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
  697. return sanitizePlaybackUrl(song.filePath);
  698. }
  699. if (isSmbType(song.type)) {
  700. Logger.warn(TAG, `SMB歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
  701. return song.filePath;
  702. }
  703. if (isFtpType(song.type)) {
  704. Logger.warn(TAG, `FTP歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
  705. return song.filePath;
  706. }
  707. if (isBaiduType(song.type)) {
  708. throw new Error('百度网盘歌曲缺少webdav_account_id,无法构建播放链接');
  709. }
  710. if (isNavidromeType(song.type)) {
  711. throw new Error('Navidrome歌曲缺少webdav_account_id,无法构建播放链接');
  712. }
  713. if (isJellyfinType(song.type)) {
  714. throw new Error('Jellyfin歌曲缺少webdav_account_id,无法构建播放链接');
  715. }
  716. if (isEmbyType(song.type)) {
  717. throw new Error('Emby歌曲缺少webdav_account_id,无法构建播放链接');
  718. }
  719. Logger.info(TAG, `setVideoUrlForSong fallback直接返回原始路径: ${song.filePath}`);
  720. return song.filePath;
  721. }
  722. // 定义接口
  723. interface HiCarAspectRatio {
  724. ratio: number;
  725. name: string;
  726. }
  727. interface GeneratedObjectLiteralInterface_1 {
  728. assetId: string;
  729. title: string;
  730. artist: string;
  731. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  732. mediaUri: string;
  733. // 该字段大写,音频'AUDIO',视频'VIDEO'
  734. mediaType: string;
  735. mediaSize: number;
  736. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  737. startPosition: number;
  738. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  739. duration: number;
  740. albumCoverUri: string;
  741. albumTitle: string;
  742. appName: string;
  743. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  744. drmScheme: string;
  745. }
  746. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  747. const ITEM_HEIGHT: number = 65; // 列表项中高度
  748. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  749. //功能强大的音乐播放器
  750. @Preview
  751. @Component
  752. export struct LocalMusic {
  753. @State showZMIndex: boolean = false //是否右侧显示字母索引
  754. private prevOffsetY: number = 0; // 记录上一次的Y轴偏移量
  755. @State autoHideTitle: boolean = true //滚动自动隐藏标题栏
  756. // 字母表
  757. @State alphaBet: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
  758. 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  759. @State alphaBetStyle: GlobalAlphabetIndexerModifier = new GlobalAlphabetIndexerModifier()
  760. @State selectAlphaBetIndex: number = 0
  761. @State isShowAlphaBet: boolean = false
  762. @State isScrolling: boolean = false
  763. @State isTouchingAlphaBet: boolean = false
  764. @State alphabetHeight: number = 0
  765. public enableShowAlphabet: boolean = true // 是否显示字母表
  766. @State isShowPrecious: boolean = false //播控条显示上一首按钮
  767. //背景两侧流光控制器
  768. @State sceneBgController: HdsSceneController|undefined = deviceInfo.sdkApiVersion>=20
  769. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  770. new HdsSceneController()
  771. .setSceneParams({
  772. backgroundMaskColors: [Color.Green, Color.Red],
  773. firstEdgeFlowLight: {
  774. startPos: 0,
  775. endPos: 0.5,
  776. color: Color.Red
  777. },
  778. secondEdgeFlowLight: {
  779. startPos: 0,
  780. endPos: -0.5,
  781. color: Color.Green
  782. }
  783. }) : undefined;
  784. //背景流光控制器
  785. @State bgController: hdsEffect.ShaderEffectController|undefined = deviceInfo.sdkApiVersion>=20
  786. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  787. new hdsEffect.ShaderEffectController():undefined;
  788. @State showAddSheet:boolean = false
  789. private loadingDialogId: string = ''
  790. private loadingProgressDialogId: string = ''
  791. searchController: SearchController = new SearchController()
  792. @State rightTopImage:Resource = $r('sys.symbol.sort')
  793. @State isEditAudio:boolean = false
  794. @State isExtractAcc:boolean = false
  795. @State isConverter:boolean = false
  796. @State isAIVoiceSeparation:boolean = false
  797. @State isExtractAudio:boolean = false
  798. @State isMergeAudio:boolean = false
  799. @State isCopyFileToDownLoad: boolean = false
  800. @State isChangeTone:boolean = false
  801. @State offHeight: number = 75
  802. @State currentSongList: Array<VideoItem> = []//当前歌单
  803. @Consume currentSongListName:string //当前歌单名称
  804. @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
  805. @State isRefreshing: boolean = false;
  806. @State maxRefreshingHeight: number = 100.0;
  807. private contentNode?: ComponentContent<Object> = undefined;
  808. // WebDAV相关实例变量(现在改为从内存读取,不再需要存储)
  809. @State ratioL: number = 1;
  810. @State mediaKuCount: number = 0;
  811. @State albumCount: number = 0;
  812. @State artistCount: number = 0;
  813. @State fastForwardSeconds: string = '10'
  814. @State isShowBackFast: boolean = true//快进快退按钮
  815. @State isCanAuto:boolean = true
  816. @State opacityValueImage: number = 1;
  817. @State tipPopup:boolean = false
  818. @Consume mType: number;
  819. @StorageProp('themeColor') themeColor: string =
  820. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  821. themeMode: number = 0;
  822. @State titleName: string = '首页'
  823. @State textStr: string = ''
  824. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  825. // private download_path: string = '';
  826. @Consume rootPath: string //音频根目录
  827. @Consume currentPath: string
  828. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  829. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  830. @State lockPath: string = ''
  831. @State favPath: string = ''
  832. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  833. @State historyPath: string = ''
  834. @State historyList: Array<VideoItem> = []
  835. @Consume isHistory: boolean
  836. static readonly HISTORY_MUSIC: string = 'music_historyList';
  837. private table: MediaTable = new MediaTable(getContext(this))
  838. private playlistTable: PlaylistTable | null = null
  839. private deletionWatcher: FileDeletionWatcher | null = null
  840. @State allPlaylists: Playlist[] = []
  841. @State isZero: boolean = false
  842. @State fileList: Array<string> = []
  843. @State dirList: Array<VideoItem> = []
  844. @Consume videoLocalList:VideoItem[]
  845. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  846. @State listRefreshKey: number = 0
  847. // @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  848. @StorageProp('mediaKuList') mediaKuList: Array<VideoItem> = []; //媒体库文件
  849. @State artistList: Array<VideoItem> = []; //艺术家文件
  850. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  851. @State albumList: Array<VideoItem> = []; //专辑文件
  852. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  853. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  854. @State imageOpacities: number[] = [];
  855. @Consume isCanBack: boolean
  856. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  857. @State showSingleLyric: boolean = false
  858. @State sortType: number = 4 //默认排序方式
  859. @State isShowSimi: boolean = false //是否显示私密音频
  860. @State isShowFAV: boolean = true //是否显示我的收藏
  861. @State isShowTitleBar: boolean = true //是否显示分类导航条
  862. @State isShowAllBar: boolean = true //是否显示播放全部条
  863. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  864. @State isShowHistory: boolean = true //是否显示最近播放
  865. @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
  866. @State isGridMusic: boolean = false //是否网格布局
  867. @State isCircleBtn: boolean = false //是否圆形播放按钮
  868. @State twoFingerType: number = 3 //双支放大缩小的类型
  869. @State isScrollHide: boolean = false //是否滚动隐藏
  870. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  871. @State isStartAutoPlay: boolean = false //启动后自动播放
  872. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  873. @State isShowHeader: boolean = true
  874. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  875. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  876. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  877. @State isSwipe: boolean = false //listItem的左滑开关
  878. @State openSkipSongAnimate: boolean = true//切歌动画效果
  879. @State customizeBgPath: string | undefined = '';
  880. @State isDarkMode: boolean = false
  881. @State lyricTextWeight: number = 400
  882. @State lyricTextWeightPip: number = 400
  883. @State currentSwiperIndex: number = 0
  884. @State blurValue: number = 0 //背景模糊
  885. @State bgBrightness: number = 0 //背景亮度
  886. private listScroller: ListScroller = new ListScroller()
  887. private playListScroller: Scroller = new Scroller()
  888. @State isOneKeyTags:boolean = false
  889. @State isFixMessy:boolean = false
  890. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  891. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  892. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  893. @StorageProp('windowWidth') windowWidth: number = 0;
  894. @StorageProp('windowHeight') windowHeight: number = 0;
  895. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  896. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  897. private UNKONWN:string = '';
  898. private listArea: Area = {
  899. width: 0,
  900. height: 0,
  901. position: {},
  902. globalPosition: {}
  903. }
  904. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  905. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  906. // WebDAV认证信息缓存(作为实例变量,比全局上下文更可靠)
  907. private currentWebDavAuthInfo: WebDavAuthItem | null = null;
  908. //瀑布流的列数横竖屏动态切换
  909. onIsLandscapeChange() {
  910. if(this.isLandscape){
  911. this.columns = 4
  912. }else{
  913. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  914. }
  915. }
  916. onColorModeChange() {
  917. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  918. }
  919. //点击某个歌单id发生变化的时候回调
  920. onIDChange(){
  921. console.log('onecold 歌单id发生变化this.currentSongListID='+this.currentSongListID)
  922. console.log('onecold 歌单id发生变化this.currentSongListName='+this.currentSongListName)
  923. if(this.modeType==4){
  924. this.titleName = this.currentSongListName
  925. this.rightTopImage = $r('sys.symbol.sort')
  926. //获取缓存
  927. const cacheSongs:string =PreferencesUtil.getStringSync(this.currentSongListID+'currentSongList', '')
  928. console.log('onecold 歌单id发生变化获取缓存2 cacheSongs = '+cacheSongs)
  929. if(StrUtil.isNotEmpty(cacheSongs)){
  930. this.currentSongList = JSON.parse(cacheSongs) as VideoItem[]
  931. this.updateListData(this.currentSongList, true)
  932. }
  933. this.doSongListTask()//获取歌单信息
  934. }
  935. }
  936. async doSongListTask() {
  937. // 初始化歌单数据库
  938. const playlistTable = new PlaylistTable(this.context);
  939. // 查询歌单中的所有歌曲
  940. const playlistSongs: PlaylistSong[] = await playlistTable.queryPlaylistSongs(this.currentSongListID);
  941. console.log('onecold 歌单id发生变化获取缓存7 playlistSongs='+playlistSongs.length)
  942. if (ArrayUtil.isEmpty(playlistSongs)) {
  943. this.updateListData([], true)
  944. } else {
  945. this.currentSongList = await convertPlaylistSongsToVideoItems(this.context, playlistSongs);
  946. console.log('onecold 从数据库读取的歌曲为 playlistSongs='+this.currentSongList.length)
  947. this.updateListData(this.currentSongList, true)
  948. if (ArrayUtil.isNotEmpty(this.currentSongList)&&this.currentSongList.length > 100) {
  949. // 只保存前100条记录到缓存中
  950. let canceList = this.currentSongList.slice(0, 100);
  951. PreferencesUtil.putSync(this.currentSongListID+'currentSongList',
  952. JSON.stringify(canceList))
  953. } else {
  954. PreferencesUtil.putSync(this.currentSongListID+'currentSongList', JSON.stringify(this.currentSongList));
  955. }
  956. }
  957. this.isRefreshing = false
  958. }
  959. onModeChange() {
  960. this.isFavMusic = false
  961. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  962. switch (this.modeType) {
  963. case 0:
  964. this.getSortedFiles(this.currentPath)
  965. break
  966. case 1:
  967. this.rightTopImage = $r('sys.symbol.sort')
  968. this.updateListData(this.mediaKuList)
  969. this.titleName = Utility.resourceToString(this.context,$r('app.string.media_ku'))
  970. break
  971. case 2:
  972. this.rightTopImage = $r('sys.symbol.sort')
  973. this.updateListData(this.artistList)
  974. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  975. break
  976. case 3:
  977. this.rightTopImage = $r('sys.symbol.sort')
  978. this.updateListData(this.albumList)
  979. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  980. break
  981. }
  982. }
  983. // @Consume currentSong: VideoItem | undefined;
  984. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  985. // @StorageLink('isPlay') isPlay: boolean = false;
  986. @Consume isShowPlay: boolean ;
  987. @StorageLink('songList') songList: Array<VideoItem> = [];
  988. @State translateY: number = 0;
  989. @State isShowSheet: boolean = false;
  990. @State isShowSheetView: boolean = false;
  991. @State isShowTimeCloseView: boolean = false;
  992. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  993. @StorageLink('currIndex') curIndex: number = 0;
  994. @Consume isShowDrawer: boolean;
  995. @Consume offsetX: number;
  996. @State isFac: boolean = false;
  997. @State favList: Array<VideoItem> = []
  998. @Consume isFavMusic: boolean
  999. @State isClickedPLayAll: boolean = false;
  1000. private scrollerForlist: ListScroller = new ListScroller();
  1001. private knockController: KnockController | undefined = undefined;
  1002. // 修改为:
  1003. imagesF: ImageFrameInfo[] = CommonConstants.IMAGE_FRAME_INFO;
  1004. @StorageProp('animationState') animationState: AnimationStatus = AnimationStatus.Initial
  1005. // 缓存机制
  1006. private cache: Map<string, Array<VideoItem>> = new Map();
  1007. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  1008. // 持久化缓存
  1009. private async saveCacheToStorage() {
  1010. const cacheArray = Array.from(this.cache.entries());
  1011. const stringCacheArray = Array.from(this.stringCache.entries());
  1012. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  1013. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  1014. }
  1015. // 载入缓存
  1016. private async loadCacheFromStorage() {
  1017. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  1018. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  1019. if (cacheString) {
  1020. const parsedCache: Object | null = JSON.parse(cacheString);
  1021. if (parsedCache && Array.isArray(parsedCache)) {
  1022. const cacheArray: [string, Array<VideoItem>][] = parsedCache;
  1023. this.cache = new Map(cacheArray);
  1024. }
  1025. }
  1026. if (stringCacheString) {
  1027. const parsedStringCache: Object | null = JSON.parse(stringCacheString);
  1028. if (parsedStringCache && Array.isArray(parsedStringCache)) {
  1029. const stringCacheArray: [string, string][] = parsedStringCache;
  1030. this.stringCache = new Map(stringCacheArray);
  1031. }
  1032. }
  1033. }
  1034. // 查找缓存
  1035. private findCache(key: string): Array<VideoItem> | undefined {
  1036. return this.cache.get(key);
  1037. }
  1038. // 查找字符串缓存
  1039. private findStringCache(key: string): string | undefined {
  1040. return this.stringCache.get(key);
  1041. }
  1042. // 添加缓存
  1043. private addCache(key: string, value: Array<VideoItem>) {
  1044. this.cache.set(key, value);
  1045. }
  1046. // 添加字符串缓存
  1047. private addStringCache(key: string, value: string) {
  1048. this.stringCache.set(key, value);
  1049. }
  1050. // 删除缓存
  1051. private deleteCache(key: string) {
  1052. this.cache.delete(key);
  1053. this.saveCacheToStorage()
  1054. }
  1055. // 删除字符串缓存
  1056. private deleteStringCache(key: string) {
  1057. this.stringCache.delete(key);
  1058. }
  1059. // 多选机制
  1060. @State selectedFiles: Array<VideoItem> = [];
  1061. @Consume isMultiSelect: boolean;
  1062. @State isAllSelected: boolean = false;
  1063. @State appName: string = ''
  1064. @State isHasDir: boolean = false
  1065. @State packName: string = ''
  1066. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  1067. doSwipBack() {
  1068. if(this.isSearchMode){
  1069. console.info('onecold doSwipBack = ' +this.isSearchMode)
  1070. this.isSearchMode = false
  1071. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  1072. this.searchText = ''
  1073. this.getSortedFiles(this.currentPath)
  1074. return
  1075. }
  1076. this.onSearchInput('')
  1077. return
  1078. }
  1079. this.isZero = false
  1080. if (this.modeType !== 0 && this.isCanBack) {
  1081. this.onModeChange()
  1082. this.isCanBack = false
  1083. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  1084. setTimeout(() => {
  1085. if (this.modeType == 2) {
  1086. if (this.isGridMusic||this.twoFingerType==4) {
  1087. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  1088. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  1089. if(this.twoFingerType==4){
  1090. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  1091. }else{
  1092. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1093. }
  1094. } else {
  1095. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  1096. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1097. }
  1098. } else if (this.modeType == 3) {
  1099. if (this.isGridMusic||this.twoFingerType==4) {
  1100. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  1101. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 0
  1102. if(this.twoFingerType==4){
  1103. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  1104. }else{
  1105. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1106. }
  1107. } else {
  1108. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  1109. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1110. }
  1111. }
  1112. }, 200)
  1113. return
  1114. }
  1115. if (this.isHistory || this.isFavMusic) {
  1116. this.isHistory = false
  1117. this.getSortedFiles(this.currentPath)
  1118. return
  1119. }
  1120. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  1121. animateTo({ duration: 555 }, () => {
  1122. // 动画闭包内控制Image组件的出现和消失
  1123. this.isShowDrawer = !this.isShowDrawer
  1124. this.offsetX = 0
  1125. })
  1126. return
  1127. }
  1128. //返回上一级歌单的滚动位置
  1129. setTimeout(() => {
  1130. if (this.modeType == 0) {
  1131. if (this.isGridMusic||this.twoFingerType==4) {
  1132. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  1133. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
  1134. if(this.twoFingerType==4){
  1135. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  1136. }else{
  1137. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1138. }
  1139. } else {
  1140. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  1141. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1142. }
  1143. }
  1144. }, 100)
  1145. this.currentPath = Utility.getParentDirectory(this.currentPath)
  1146. Logger.info('this.currentPath2 = ' + this.currentPath)
  1147. this.getSortedFiles(this.currentPath)
  1148. }
  1149. // 组件生命周期
  1150. aboutToAppear() {
  1151. console.info('onecold aboutToAppear sdkApiVersion = '+deviceInfo.sdkApiVersion)
  1152. if(ArrayUtil.isNotEmpty(this.videoLocalList)&&this.modeType==0){
  1153. this.updateListData(this.videoLocalList)
  1154. }
  1155. // 初始化 PlaylistTable
  1156. this.playlistTable = new PlaylistTable(getContext(this))
  1157. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  1158. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  1159. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  1160. this.tipPopup = !this.tipPopup
  1161. PreferencesUtil.putSync('isFirstTiped',false)
  1162. }
  1163. this.initSetting()
  1164. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  1165. Utility.getAppName(getContext(this)).then((appName: string) => {
  1166. this.appName = appName
  1167. })
  1168. this.packName = AppUtil.getBundleName()
  1169. this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
  1170. this.loadCacheFromStorage(); // 加载文件夹缓存
  1171. // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
  1172. this.initLoadCache()
  1173. this.mkDownLoadDir()
  1174. let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
  1175. // 监听广播事件(打开其他应用处理)
  1176. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  1177. this.saveVideoDatas([eventData.data?.message], true)
  1178. });
  1179. //侧滑广播接收时间
  1180. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
  1181. // 监听广播事件(打开其他应用处理)
  1182. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  1183. animateTo({ duration: 555 }, () => {
  1184. this.doSwipBack()
  1185. })
  1186. });
  1187. //ScanFilePage广播接收时间
  1188. let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
  1189. // 监听ScanFilePage广播事件(更新数据库)
  1190. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  1191. this.doUpdateData()
  1192. });
  1193. // 监听歌单播放请求事件
  1194. let eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY }
  1195. emitter.on(eventPlaylistPlay, async (eventData: emitter.EventData) => {
  1196. const data = eventData.data as Record<string, Object>
  1197. if (!data) {
  1198. Logger.error('heanup eventPlaylistPlay: eventData.data is undefined or null')
  1199. return
  1200. }
  1201. // 检查歌单播放数据结构
  1202. if (data.playlistId && data.songFilePaths && data.startIndex !== undefined) {
  1203. const playlistData: PlaylistEventData = {
  1204. playlistId: data.playlistId as string,
  1205. playlistName: data.playlistName as string,
  1206. songCount: data.songCount as number,
  1207. startIndex: data.startIndex as number,
  1208. isJump: data.isJump as boolean,
  1209. songFilePaths: data.songFilePaths as string[]
  1210. }
  1211. await this.handlePlaylistPlayRequest(
  1212. playlistData.playlistId,
  1213. playlistData.playlistName,
  1214. playlistData.songFilePaths,
  1215. playlistData.startIndex,
  1216. playlistData.isJump,
  1217. )
  1218. return
  1219. }
  1220. Logger.error('heanup eventPlaylistPlay: 接收到无效的数据结构')
  1221. });
  1222. let eventRefreshSort: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_REFRESH_SORT }
  1223. // 监听广播事件(通用设置配置更新)
  1224. emitter.on(eventRefreshSort, (eventData: emitter.EventData) => {
  1225. if(this.modeType ==4){
  1226. this.doSongListTask()//获取歌单信息
  1227. }
  1228. });
  1229. let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
  1230. // 监听广播事件(通用设置配置更新)
  1231. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  1232. this.doChangeSetting()
  1233. });
  1234. let event: Callback<InterruptEvent> = (event) => {
  1235. // LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  1236. console.info(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  1237. this.savePlaybackPosition()
  1238. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  1239. this.pause();
  1240. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  1241. console.info(`onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  1242. console.info('onecold startPlayOrResumePlay 514')
  1243. this.startPlayOrResumePlay();
  1244. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  1245. console.info(`onecold 与其他应用音频冲突 被截断点 INTERRUPT_HINT_STOP`)
  1246. if(!this.isSameTimePlay){
  1247. this.stop();
  1248. }
  1249. }
  1250. }
  1251. this.mIjkMediaPlayer.on('audioInterrupt', event);
  1252. // 音频设备断连回调处理比如蓝牙耳机断开
  1253. let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  1254. LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  1255. if (event.reason === DeviceChangeReason.REASON_NEW_DEVICE_AVAILABLE) { // 音频设备连接
  1256. } else if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  1257. console.info('onecold 音频设备断开连接, 暂停播放')
  1258. this.pause();
  1259. }
  1260. }
  1261. // 订阅音频设备断开和连接事件
  1262. this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  1263. const eventPause: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_PAUSE }
  1264. // 监听广播事件(hicar断开暂停播放)
  1265. emitter.on(eventPause, (eventData: emitter.EventData) => {
  1266. this.pause();
  1267. });
  1268. // 有线耳机断开和连接的监听。监听音频设备状态变化。
  1269. let audioManager = audio.getAudioManager(); // 需要先创建AudioManager实例。
  1270. let audioRoutingManager = audioManager.getRoutingManager(); // 再调用AudioManager的方法创建AudioRoutingManager实例。
  1271. audioRoutingManager.on('deviceChange', audio.DeviceFlag.INPUT_DEVICES_FLAG, (deviceChanged: audio.DeviceChangeAction) => {
  1272. console.info('device change type : ' + deviceChanged.type); // 设备连接状态变化,0为连接,1为断开连接。
  1273. // 设备类型 22是USB耳机,带麦克风,3是有线耳机。
  1274. if(deviceChanged.type==1&&
  1275. (deviceChanged.deviceDescriptors[0].deviceType== 22||
  1276. deviceChanged.deviceDescriptors[0].deviceType==3)){
  1277. this.pause();
  1278. }
  1279. });
  1280. this.makeWorker()
  1281. //折叠屏的屏幕显示模式变化
  1282. display.on('foldDisplayModeChange', (data) => {
  1283. this.doChangeBarHeight()
  1284. });
  1285. display.on('foldStatusChange', (data) => {
  1286. Logger.info('onecold foldStatusChange ')
  1287. });
  1288. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  1289. // 读取 themeMode 并同步 currentColorMode
  1290. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  1291. this.applyThemeMode(this.themeMode)
  1292. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  1293. AppStorage.setOrCreate('themeColor', themeColor);
  1294. this.themeColor = themeColor;
  1295. this.doChangeSetting()
  1296. this.windowClass.on('windowSizeChange', (size) => {
  1297. LogUtil.info('onecold windowSizeChange')
  1298. this.doChangeBarHeight()
  1299. let viewWidth = px2vp(size.width);
  1300. let viewHeight = px2vp(size.height);
  1301. if(this.isPhoneLan()){
  1302. this.is_auto_hide_progress = false
  1303. if(this.isHiCar()){
  1304. return
  1305. }
  1306. setTimeout(() => {
  1307. this.is_auto_hide_progress = true
  1308. }, 6000)
  1309. }else{
  1310. this.startAutoHide()
  1311. }
  1312. });
  1313. this.eventHub.on('onStateChange', (fg: boolean) => {
  1314. if (fg && this.curState === 'STARTED') {
  1315. this.stopPip();
  1316. }
  1317. });
  1318. //NewIndex的博空调收到eventHub消息控制播放
  1319. this.getUIContext().getHostContext()!.eventHub.on('playOrPause', () => {
  1320. if (ArrayUtil.isNotEmpty(this.songList)) {
  1321. this.playOrPause();
  1322. } else {
  1323. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1324. }
  1325. });
  1326. this.getUIContext().getHostContext()!.eventHub.on('playPrevious', () => {
  1327. if (ArrayUtil.isNotEmpty(this.songList)) {
  1328. this.playPrevious();
  1329. } else {
  1330. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1331. }
  1332. });
  1333. this.getUIContext().getHostContext()!.eventHub.on('playNext', () => {
  1334. if (ArrayUtil.isNotEmpty(this.songList)) {
  1335. this.playNext();
  1336. } else {
  1337. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1338. }
  1339. });
  1340. this.getUIContext().getHostContext()!.eventHub.on('showPlayerView', () => {
  1341. this.showPlayerView();
  1342. });
  1343. this.getUIContext().getHostContext()!.eventHub.on('openPlayList', () => {
  1344. this.openPlayList();
  1345. });
  1346. }
  1347. //载入媒体库,艺术家,专辑等缓存
  1348. initLoadCache(){
  1349. this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
  1350. this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
  1351. this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
  1352. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  1353. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  1354. if(ArrayUtil.isNotEmpty(cachedList)){
  1355. this.mediaKuList = cachedList
  1356. if(this.modeType==1){
  1357. this.updateListData(this.mediaKuList)
  1358. }
  1359. }
  1360. let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
  1361. let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
  1362. if(ArrayUtil.isNotEmpty(artistCachedList)){
  1363. this.artistList = artistCachedList
  1364. let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
  1365. const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
  1366. this.artistMap = new Map(parsedArray);
  1367. // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
  1368. if(this.modeType==2){
  1369. this.updateListData(this.artistList)
  1370. }
  1371. }
  1372. let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
  1373. let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
  1374. if(ArrayUtil.isNotEmpty(albumCachedList)){
  1375. this.albumList = albumCachedList
  1376. let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
  1377. const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
  1378. this.albumMap = new Map(parsedArray);
  1379. if(this.modeType==3){
  1380. this.updateListData(this.albumList)
  1381. }
  1382. }
  1383. }
  1384. startAutoHide() {
  1385. if(this.isHiCar()){
  1386. return
  1387. }
  1388. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  1389. console.info('onecold startAutoHide')
  1390. this.is_auto_hide_progress = false
  1391. setTimeout(() => {
  1392. this.is_auto_hide_progress = true
  1393. }, 6000)
  1394. }
  1395. }
  1396. applyThemeMode(mode: number) {
  1397. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  1398. if (mode === 1) {
  1399. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  1400. } else if (mode === 2) {
  1401. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1402. }
  1403. AppStorage.setOrCreate('currentColorMode', colorMode)
  1404. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  1405. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  1406. AppStorage.setOrCreate('themeMode', mode)
  1407. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1408. // 只有强制浅色/深色时才主动设置
  1409. const context = getContext(this) as common.UIAbilityContext
  1410. context.getApplicationContext().setColorMode(colorMode)
  1411. }
  1412. initSetting() {
  1413. this.showZMIndex = PreferencesUtil.getBooleanSync('showZMIndex', false)
  1414. this.autoHideTitle = PreferencesUtil.getBooleanSync('autoHideTitle', true)
  1415. this.isShowPrecious = PreferencesUtil.getBooleanSync('isShowPrecious', false)
  1416. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1417. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  1418. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  1419. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, false)
  1420. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  1421. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  1422. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  1423. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  1424. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  1425. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  1426. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  1427. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  1428. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  1429. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 2)
  1430. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  1431. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  1432. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  1433. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  1434. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  1435. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  1436. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  1437. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  1438. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  1439. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  1440. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  1441. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  1442. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  1443. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  1444. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  1445. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  1446. this.isCopyFileToDownLoad = PreferencesUtil.getBooleanSync(SettingPage.IS_COPYFILE_TO_DOWNLOAD, false)
  1447. let audioManager = audio.getAudioManager();
  1448. let audioSessionManager: audio.AudioSessionManager = audioManager.getSessionManager();
  1449. if(this.isSameTimePlay){
  1450. //与其他应用同时播放,关键代码
  1451. let strategy: audio.AudioSessionStrategy = {
  1452. concurrencyMode: audio.AudioConcurrencyMode.CONCURRENCY_MIX_WITH_OTHERS
  1453. };
  1454. audioSessionManager.activateAudioSession(strategy).then(() => {
  1455. console.info('onecold Succeeded in doing activateAudioSession.');
  1456. }).catch((err: BusinessError) => {
  1457. console.error(`Failed to activateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1458. });
  1459. }else{
  1460. let isActivated = audioSessionManager.isAudioSessionActivated();
  1461. if(isActivated){
  1462. audioSessionManager.deactivateAudioSession().then(() => {
  1463. console.info('Succeeded in doing deactivateAudioSession.');
  1464. }).catch((err: BusinessError) => {
  1465. console.error(`Failed to deactivateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1466. });
  1467. }
  1468. }
  1469. if(this.volumeSmall){
  1470. this.volume = 0.5
  1471. }else{
  1472. this.volume = 1
  1473. }
  1474. //如果是hicar连接状态,这些都是false
  1475. if(this.isHiCar()){
  1476. this.autoHideTitle = false
  1477. this.isCoverRectangle= true
  1478. this.columns=4
  1479. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  1480. {
  1481. this.isGridMusic= false//用list不用网格
  1482. this.isCoverTopBig = false
  1483. }
  1484. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  1485. }
  1486. if (this.isSavePlayMode) {
  1487. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  1488. }
  1489. }
  1490. doChangeSetting() {
  1491. this.initSetting()
  1492. this.deleteCache(this.currentPath)
  1493. if (this.modeType === 0) {
  1494. this.getSortedFiles(this.currentPath)
  1495. }
  1496. }
  1497. doChangeBarHeight() {
  1498. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  1499. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  1500. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  1501. this.setBarHeightNormal()
  1502. }
  1503. }
  1504. onPageShow() {
  1505. this.knockController?.immersiveListening();
  1506. app.setImageCacheCount(100);
  1507. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  1508. app.setImageRawDataCacheSize(104857600);
  1509. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  1510. }
  1511. //开启线程查看各个数据库
  1512. makeWorker() {
  1513. setTimeout(() => {
  1514. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  1515. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  1516. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  1517. // workerInstance.postMessage({
  1518. // code: 1,
  1519. // data1: this.context,
  1520. // data2: this.rootPath,
  1521. // data3: this.lockPath,
  1522. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1523. // data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  1524. // });
  1525. PreferencesUtil.putSync('isFirstApp', false)
  1526. } else {
  1527. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1528. workerInstance.postMessage({ code: 3, data: this.context });
  1529. workerInstance.postMessage({ code: 4, data: this.context });
  1530. this.getHistoryList(false)
  1531. }
  1532. }, 1000)
  1533. workerInstance.onmessage = (e: MessageEvents): void => {
  1534. switch (e.data.code) {
  1535. case 101: //第一次扫描文件夹入库
  1536. ToastUtil.showToast('刷新同步数据库成功!')
  1537. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  1538. this.doAllUpdateData()
  1539. break;
  1540. case 102: //查询媒体库列表
  1541. this.isRefreshing = false
  1542. this.mediaKuList = e.data.data
  1543. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  1544. Utility.doSortListAscending(this.mediaKuList)
  1545. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  1546. if (this.modeType === 1) {
  1547. this.updateListData(this.mediaKuList)
  1548. }
  1549. PreferencesUtil.putSync('mediaKuCount', this.mediaKuList.length)
  1550. // 处理媒体库前100条记录,列表长度并存储到PreferencesUtil
  1551. if (ArrayUtil.isNotEmpty(this.mediaKuList)&&this.mediaKuList.length > 100) {
  1552. // 只保存前100条记录到缓存中
  1553. let truncatedList = this.mediaKuList.slice(0, 100);
  1554. PreferencesUtil.putSync('mediaKuList', JSON.stringify(truncatedList));
  1555. } else {
  1556. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  1557. }
  1558. break;
  1559. case 103: //收到查询艺术家列表
  1560. this.isRefreshing = false
  1561. this.artistMap = e.data.data1;
  1562. this.artistList = e.data.data2;
  1563. PreferencesUtil.putSync('artistCount', this.artistList.length)
  1564. // 处理艺术家前100条记录,列表长度并存储到PreferencesUtil
  1565. if (ArrayUtil.isNotEmpty(this.artistList)&&this.artistList.length > 100) {
  1566. // 只保存前100条记录到缓存中
  1567. let truncatedList = this.artistList.slice(0, 100);
  1568. PreferencesUtil.putSync('artistList', JSON.stringify(truncatedList));
  1569. } else {
  1570. PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
  1571. }
  1572. // 处理并缓存前60条艺术家数据
  1573. const sortedEntries = Array.from(this.artistMap.entries())
  1574. .sort((a, b) => b[1].length - a[1].length)
  1575. .slice(0, 60);
  1576. PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
  1577. break;
  1578. case 104: //收到查询专辑列表
  1579. this.isRefreshing = false
  1580. this.albumMap = e.data.data1;
  1581. this.albumList = e.data.data2
  1582. //查询完毕在启动是否自动播放
  1583. if (this.isStartAutoPlay&&this.isCanAuto) {
  1584. this.isCanAuto = false
  1585. console.info('onecold startPlayOrResumePlay 757')
  1586. this.startPlayOrResumePlay()
  1587. }
  1588. PreferencesUtil.putSync('albumCount', this.albumList.length)
  1589. // 处理专辑前100条记录,列表长度并存储到PreferencesUtil
  1590. if (ArrayUtil.isNotEmpty(this.albumList)&&this.albumList.length > 100) {
  1591. // 只保存前100条记录到缓存中
  1592. let truncatedList = this.albumList.slice(0, 100);
  1593. PreferencesUtil.putSync('albumList', JSON.stringify(truncatedList));
  1594. } else {
  1595. PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
  1596. }
  1597. const mapArrayAlbum = Array.from(this.albumMap.entries())
  1598. .sort((a, b) => b[1].length - a[1].length)
  1599. .slice(0, 60);
  1600. PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
  1601. break;
  1602. case 105: // 缓存完成后返回的元数据
  1603. this.handleWorkerMetadataPayload(e.data.data as WorkerMetadataPayload);
  1604. break;
  1605. case 106: // 编辑音乐元数据和封面完成
  1606. this.handleEditMusicResult(e.data);
  1607. break;
  1608. }
  1609. };
  1610. // 在调用terminate后,执行onexit
  1611. workerInstance.onexit = (code) => {
  1612. metadataExtractionInFlight.clear();
  1613. Logger.info(TAG, 'workerInstance 线程已退出,code: ' + code);
  1614. }
  1615. workerInstance.onerror = (err: ErrorEvent) => {
  1616. metadataExtractionInFlight.clear();
  1617. console.error('workerInstance 线程执行发生异常: ' + err.message)
  1618. }
  1619. }
  1620. private handleWorkerMetadataPayload(payload: WorkerMetadataPayload | undefined): void {
  1621. if (!payload || !payload.originFilePath) {
  1622. return;
  1623. }
  1624. metadataExtractionInFlight.delete(payload.originFilePath);
  1625. if (payload.error) {
  1626. Logger.warn(TAG, `缓存文件元数据解析失败: ${payload.error}`);
  1627. return;
  1628. }
  1629. this.applyMetadataToCollections(payload.originFilePath, payload);
  1630. }
  1631. private applyMetadataToCollections(filePath: string, payload: WorkerMetadataPayload): void {
  1632. const targets: Array<VideoItem> = [];
  1633. let mainListUpdated = false;
  1634. let playlistUpdated = false;
  1635. if (this.currentSong && this.currentSong.filePath === filePath) {
  1636. targets.push(this.currentSong);
  1637. }
  1638. const collectFromList = (list?: Array<VideoItem>, markUpdated?: () => void) => {
  1639. if (!list || list.length === 0) {
  1640. return;
  1641. }
  1642. const found = Utility.getItemByFilePath(list, filePath);
  1643. if (found) {
  1644. markUpdated?.();
  1645. targets.push(found);
  1646. }
  1647. };
  1648. collectFromList(this.videoLocalList, () => {
  1649. mainListUpdated = true;
  1650. });
  1651. collectFromList(this.songList, () => {
  1652. playlistUpdated = true;
  1653. });
  1654. collectFromList(this.historyList);
  1655. collectFromList(this.favList);
  1656. const remoteManager = RemoteDriveManager.getInstance();
  1657. collectFromList(remoteManager.webDavSongs);
  1658. const updated = new Set<VideoItem>();
  1659. const remoteMetadataUpdates: Map<string, WebDavMetadataUpdatePayload> = new Map();
  1660. for (let i = 0; i < targets.length; i++) {
  1661. const target = targets[i];
  1662. if (!target || updated.has(target)) {
  1663. continue;
  1664. }
  1665. updated.add(target);
  1666. this.mergeVideoItemWithPayload(target, payload);
  1667. if (isRemoteCloudType(target.type) && StrUtil.isNotEmpty(target.filePath)) {
  1668. remoteMetadataUpdates.set(target.filePath, {
  1669. filePath: target.filePath,
  1670. pixelMapPath: target.pixelMapPath,
  1671. name: target.name,
  1672. artist: target.artist
  1673. });
  1674. }
  1675. }
  1676. if (this.currentSong && this.currentSong.filePath === filePath) {
  1677. this.mergeVideoItemWithPayload(this.currentSong, payload);
  1678. if (payload.name) {
  1679. this.name = payload.name;
  1680. }
  1681. if (payload.artist) {
  1682. this.artist = payload.artist;
  1683. }
  1684. if (payload.pixelMapPath) {
  1685. this.cover = payload.pixelMapPath;
  1686. }
  1687. if (payload.lyricContent) {
  1688. this.applyInlineLyricContent(payload.lyricContent);
  1689. }
  1690. let avSessionDurationMs = this.duration;
  1691. if (payload.duration) {
  1692. const durationSeconds = Number(payload.duration);
  1693. if (!Number.isNaN(durationSeconds) && durationSeconds > 0) {
  1694. avSessionDurationMs = durationSeconds * 1000;
  1695. this.duration = avSessionDurationMs;
  1696. this.durationTime = Math.floor(avSessionDurationMs / 1000);
  1697. this.durationStringTime = secondToTime(this.durationTime);
  1698. }
  1699. }
  1700. if (avSessionDurationMs > 0) {
  1701. this.avSessionController.setAVMetadataMusic(this.currentSong, avSessionDurationMs, this.lyricContent);
  1702. }
  1703. this.currentSong = cloneVideoItem(this.currentSong);
  1704. AppStorage.setOrCreate('currentSong', this.currentSong);
  1705. }
  1706. const primaryTarget = targets.length > 0 ? targets[0] : undefined;
  1707. if (primaryTarget) {
  1708. this.persistRemoteMetadataToDb(primaryTarget).catch((error: Error) => {
  1709. Logger.error(TAG, `缓存元数据持久化失败: ${error.message}`);
  1710. });
  1711. }
  1712. if (remoteMetadataUpdates.size > 0) {
  1713. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  1714. emitter.emit(eventUpdate, { data: Array.from(remoteMetadataUpdates.values()) });
  1715. }
  1716. this.refreshLazyListViews(mainListUpdated, playlistUpdated);
  1717. }
  1718. private handleEditMusicResult(result: WorkerEditMusicResult): void {
  1719. // 关闭进度条
  1720. DialogHelper.closeDialog(this.loadingDialogId)
  1721. if (result.success) {
  1722. console.log("heanup 编辑信息成功,数据库已同步");
  1723. if (result.coverResult) {
  1724. ToastUtil.showToast('内嵌封面成功');
  1725. }
  1726. ToastUtil.showToast('内嵌音乐标签成功');
  1727. this.isShowMoreView = false;
  1728. this.name = this.titleStr;
  1729. // 同步当前播放的歌曲信息
  1730. if (this.editingItem && this.editingItem.filePath == this.currentSong?.filePath) {
  1731. this.currentSong.name = this.titleStr;
  1732. this.artist = this.artistStr;
  1733. this.currentSong.artist = this.artistStr;
  1734. this.currentSong.album = this.ablumStr;
  1735. this.currentSong.year = this.yearStr;
  1736. this.currentSong.genre = this.genreStr;
  1737. this.currentSong.track = this.trackStr;
  1738. this.currentSong.lyricContent = this.lyricConStr;
  1739. this.currentSong.ALBUMARTIST = this.albumArtistStr;
  1740. this.currentSong.COMPOSER = this.composerStr;
  1741. this.currentSong.LYRICIST = this.lyricistStr;
  1742. this.currentSong.COMMENT = this.commentStr;
  1743. }
  1744. // if (result.needRefreshList && this.modeType == 0) {
  1745. // this.deleteCache(this.currentPath);
  1746. // this.getSortedFiles(this.currentPath);
  1747. // }
  1748. // 同步编辑字段到本地列表
  1749. if (this.editingItem) {
  1750. this.syncEditedFields(this.editingItem);
  1751. this.syncListsAfterEdit(this.editingItem.filePath);
  1752. this.doUpateEditedFields(this.editingItem);
  1753. }
  1754. // 清理临时变量
  1755. this.longItemFilePath = '';
  1756. this.tempLyricContent = '';
  1757. this.isShowEdit = false;
  1758. this.imagePathStr = '';
  1759. } else {
  1760. console.error("heanup 编辑信息失败: " + result.error);
  1761. ToastUtil.showToast('编辑失败: ' + (result.error || '未知错误'));
  1762. // 清理临时变量
  1763. this.longItemFilePath = '';
  1764. this.tempLyricContent = '';
  1765. this.isShowEdit = false;
  1766. this.imagePathStr = '';
  1767. }
  1768. }
  1769. private assignStringMetadata(target: VideoItem, key: keyof VideoItem, value?: string | null, allowEmpty = false): void {
  1770. if (value === undefined || value === null) {
  1771. return;
  1772. }
  1773. const text = value.toString();
  1774. if (!allowEmpty && text.trim().length === 0) {
  1775. return;
  1776. }
  1777. Reflect.set(target, key as string, value);
  1778. }
  1779. private assignNumberMetadata(target: VideoItem, key: keyof VideoItem, value?: number | null): void {
  1780. if (value === undefined || value === null || Number.isNaN(value)) {
  1781. return;
  1782. }
  1783. Reflect.set(target, key as string, value);
  1784. }
  1785. private mergeVideoItemWithPayload(target: VideoItem, payload: WorkerMetadataPayload): void {
  1786. if (!target || !payload) {
  1787. return;
  1788. }
  1789. this.assignStringMetadata(target, 'name', payload.name);
  1790. this.assignStringMetadata(target, 'artist', payload.artist);
  1791. this.assignStringMetadata(target, 'album', payload.album);
  1792. this.assignStringMetadata(target, 'bit_rate', payload.bit_rate);
  1793. this.assignStringMetadata(target, 'duration', payload.duration);
  1794. this.assignStringMetadata(target, 'sampleRate', payload.sampleRate);
  1795. this.assignStringMetadata(target, 'mimeType', payload.mimeType);
  1796. this.assignStringMetadata(target, 'size', payload.size);
  1797. this.assignStringMetadata(target, 'pixelMapPath', payload.pixelMapPath);
  1798. this.assignStringMetadata(target, 'lyricContent', payload.lyricContent, true);
  1799. this.assignStringMetadata(target, 'genre', payload.genre);
  1800. this.assignStringMetadata(target, 'track', payload.track);
  1801. this.assignStringMetadata(target, 'bits_per_raw_sample', payload.bits_per_raw_sample);
  1802. this.assignStringMetadata(target, 'channels', payload.channels);
  1803. this.assignStringMetadata(target, 'channel_layout', payload.channel_layout);
  1804. this.assignStringMetadata(target, 'start_time', payload.start_time);
  1805. this.assignStringMetadata(target, 'year', payload.year);
  1806. this.assignStringMetadata(target, 'disc', payload.disc);
  1807. this.assignStringMetadata(target, 'ALBUMARTIST', payload.ALBUMARTIST);
  1808. this.assignStringMetadata(target, 'COMPOSER', payload.COMPOSER);
  1809. this.assignStringMetadata(target, 'LYRICIST', payload.LYRICIST);
  1810. this.assignStringMetadata(target, 'COMMENT', payload.COMMENT, true);
  1811. this.assignNumberMetadata(target, 'videoSize', payload.videoSize);
  1812. this.assignNumberMetadata(target, 'probe_score', payload.probe_score);
  1813. this.assignNumberMetadata(target, 'nb_streams', payload.nb_streams);
  1814. this.assignNumberMetadata(target, 'nb_programs', payload.nb_programs);
  1815. }
  1816. private mergeVideoItemFromSource(target: VideoItem, source: VideoItem): void {
  1817. if (!target || !source) {
  1818. return;
  1819. }
  1820. this.assignStringMetadata(target, 'name', source.name);
  1821. this.assignStringMetadata(target, 'artist', source.artist);
  1822. this.assignStringMetadata(target, 'album', source.album);
  1823. this.assignStringMetadata(target, 'bit_rate', source.bit_rate);
  1824. this.assignStringMetadata(target, 'duration', source.duration);
  1825. this.assignStringMetadata(target, 'sampleRate', source.sampleRate);
  1826. this.assignStringMetadata(target, 'trackCount', source.trackCount);
  1827. this.assignStringMetadata(target, 'mimeType', source.mimeType);
  1828. this.assignStringMetadata(target, 'size', source.size);
  1829. this.assignStringMetadata(target, 'pixelMapPath', source.pixelMapPath);
  1830. this.assignStringMetadata(target, 'lyricContent', source.lyricContent, true);
  1831. this.assignStringMetadata(target, 'genre', source.genre);
  1832. this.assignStringMetadata(target, 'track', source.track);
  1833. this.assignStringMetadata(target, 'bits_per_raw_sample', source.bits_per_raw_sample);
  1834. this.assignStringMetadata(target, 'channels', source.channels);
  1835. this.assignStringMetadata(target, 'channel_layout', source.channel_layout);
  1836. this.assignStringMetadata(target, 'start_time', source.start_time);
  1837. this.assignStringMetadata(target, 'year', source.year);
  1838. this.assignStringMetadata(target, 'disc', source.disc);
  1839. this.assignStringMetadata(target, 'ALBUMARTIST', source.ALBUMARTIST);
  1840. this.assignStringMetadata(target, 'COMPOSER', source.COMPOSER);
  1841. this.assignStringMetadata(target, 'LYRICIST', source.LYRICIST);
  1842. this.assignStringMetadata(target, 'COMMENT', source.COMMENT, true);
  1843. this.assignNumberMetadata(target, 'videoSize', source.videoSize);
  1844. this.assignNumberMetadata(target, 'probe_score', source.probe_score);
  1845. this.assignNumberMetadata(target, 'nb_streams', source.nb_streams);
  1846. this.assignNumberMetadata(target, 'nb_programs', source.nb_programs);
  1847. if (source.remote_rel_path && StrUtil.isEmpty(target.remote_rel_path)) {
  1848. target.remote_rel_path = source.remote_rel_path;
  1849. }
  1850. }
  1851. private async hydrateRemoteSongFromDb(item: VideoItem | undefined): Promise<void> {
  1852. if (!item || !isRemoteCloudType(item.type)) {
  1853. return;
  1854. }
  1855. const storagePath = item.remote_rel_path || WebDavUrlUtil.toStoragePath(item.filePath);
  1856. if (!storagePath) {
  1857. return;
  1858. }
  1859. try {
  1860. const cached = await this.table.queryVideoByFilePath(storagePath);
  1861. if (!cached) {
  1862. return;
  1863. }
  1864. this.mergeVideoItemFromSource(item, cached);
  1865. if (StrUtil.isEmpty(item.remote_rel_path)) {
  1866. item.remote_rel_path = storagePath;
  1867. }
  1868. if (item === this.currentSong) {
  1869. if (StrUtil.isNotEmpty(item.name)) {
  1870. this.name = item.name;
  1871. }
  1872. if (StrUtil.isNotEmpty(item.artist)) {
  1873. this.artist = item.artist!;
  1874. }
  1875. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  1876. this.cover = item.pixelMapPath!;
  1877. }
  1878. if (StrUtil.isNotEmpty(item.lyricContent) && StrUtil.isEmpty(this.lyricContent)) {
  1879. this.applyInlineLyricContent(item.lyricContent as string);
  1880. }
  1881. }
  1882. } catch (error) {
  1883. Logger.error(TAG, `hydrateRemoteSongFromDb 失败: ${(error as Error).message}`);
  1884. }
  1885. }
  1886. private applyInlineLyricContent(content: string): void {
  1887. if (StrUtil.isEmpty(content)) {
  1888. return;
  1889. }
  1890. this.lyricContent = content;
  1891. const lines = content.split('\n').map(line => line.trim());
  1892. const lyric = this.parser.parse(lines);
  1893. this.lyricController.setLyric(lyric);
  1894. this.lyricControllerXF.setLyric(lyric);
  1895. this.lyricControllerSingle.setLyric(lyric);
  1896. }
  1897. private extractParentPathFromStoragePath(path: string): string {
  1898. if (!path) {
  1899. return '';
  1900. }
  1901. const lastSlash = path.lastIndexOf('/');
  1902. if (lastSlash <= 0) {
  1903. return '';
  1904. }
  1905. return path.substring(0, lastSlash);
  1906. }
  1907. private resolveRemoteStoragePath(target: VideoItem): string | null {
  1908. if (!target || !isRemoteCloudType(target.type)) {
  1909. return null;
  1910. }
  1911. if (isWebDavType(target.type)) {
  1912. const storagePath = target.remote_rel_path || WebDavUrlUtil.toStoragePath(target.filePath);
  1913. if (storagePath) {
  1914. target.remote_rel_path = storagePath;
  1915. return storagePath;
  1916. }
  1917. return null;
  1918. }
  1919. if (target.remote_rel_path && target.remote_rel_path.length > 0) {
  1920. return target.remote_rel_path;
  1921. }
  1922. return null;
  1923. }
  1924. private async persistRemoteMetadataToDb(target: VideoItem): Promise<void> {
  1925. if (!this.context || !target || !isRemoteCloudType(target.type)) {
  1926. return;
  1927. }
  1928. const storagePath = this.resolveRemoteStoragePath(target);
  1929. if (!storagePath) {
  1930. return;
  1931. }
  1932. const table = new MediaTable(this.context);
  1933. await new Promise<void>((resolve) => {
  1934. table.getRdbStore(this.context as Context, () => resolve());
  1935. });
  1936. const cloneItem = cloneVideoItem(target);
  1937. cloneItem.filePath = storagePath;
  1938. cloneItem.remote_rel_path = storagePath;
  1939. cloneItem.parentPath = this.extractParentPathFromStoragePath(storagePath);
  1940. await table.saveOrUpdateWebDavItem(cloneItem);
  1941. }
  1942. onPageHide(): void {
  1943. this.knockController?.immersiveDisableListening();
  1944. }
  1945. @State isFirstStartPlay: boolean = false
  1946. private async startFileDeletionWatcher(): Promise<void> {
  1947. if (!this.rootPath) {
  1948. return;
  1949. }
  1950. if (!this.deletionWatcher) {
  1951. this.deletionWatcher = new FileDeletionWatcher(this.context, this.table);
  1952. }
  1953. try {
  1954. await this.deletionWatcher.watchDirectories([
  1955. this.rootPath,
  1956. this.lockPath,
  1957. this.favPath,
  1958. this.historyPath
  1959. ]);
  1960. } catch (error) {
  1961. Logger.error(TAG, `初始化文件删除监听失败: ${(error as Error).message}`);
  1962. }
  1963. }
  1964. //获取download_path
  1965. async mkDownLoadDir() {
  1966. const documentViewPicker = new picker.DocumentViewPicker()
  1967. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  1968. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  1969. PreferencesUtil.putSync('download_path', this.rootPath+'/')
  1970. this.currentPath = this.rootPath
  1971. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  1972. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  1973. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  1974. Logger.info('onecold rootPath = ' + this.rootPath)
  1975. Logger.info('onecold lockPath = ' + this.lockPath)
  1976. if (!FileUtil.accessSync(this.lockPath)) {
  1977. FileUtil.mkdirSync(this.lockPath)
  1978. }
  1979. if (!FileUtil.accessSync(this.favPath)) {
  1980. FileUtil.mkdirSync(this.favPath)
  1981. }
  1982. if (!FileUtil.accessSync(this.historyPath)) {
  1983. FileUtil.mkdirSync(this.historyPath)
  1984. }
  1985. // await this.startFileDeletionWatcher();
  1986. this.getSortedFiles(this.rootPath).then(async () => {
  1987. this.isFavMusic = false
  1988. //穿山甲
  1989. // this.loadBannerAd(CSJUtil.getBannerID())
  1990. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  1991. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  1992. if (ArrayUtil.isEmpty(this.songList)) {
  1993. this.songList = this.getCurFileList()
  1994. } else {
  1995. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  1996. }
  1997. if (ArrayUtil.isNotEmpty(this.songList)) {
  1998. this.isFirstStartPlay = true
  1999. this.sonDataSource.pushArrayData(this.songList)
  2000. if (this.currentSong === undefined) {
  2001. this.isFirstStartPlay = false
  2002. this.currentSong = this.songList[0]
  2003. }
  2004. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  2005. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  2006. context: this.context,
  2007. autoParseMusicName: this.autoParseMusicName
  2008. });
  2009. Logger.info(TAG, `WebDAV URL同步构建完成: ${this.videoUrl}`);
  2010. this.name = this.currentSong.name
  2011. this.cover = this.currentSong.pixelMapPath
  2012. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  2013. } else {
  2014. this.name = '空空如也'
  2015. }
  2016. })
  2017. this.getFavList(false)
  2018. }
  2019. getFavList(isFavRefresh: boolean) {
  2020. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  2021. this.favList = result
  2022. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  2023. this.videoLocalList = this.favList
  2024. this.updateListData(this.videoLocalList)
  2025. }
  2026. })
  2027. }
  2028. getHistoryList(isRefresh: boolean) {
  2029. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  2030. this.historyList = result
  2031. // for (let i = 0; i < this.historyList.length; i++) {
  2032. //
  2033. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  2034. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  2035. // }
  2036. if (isRefresh) {
  2037. this.videoLocalList = this.historyList
  2038. this.updateListData(this.videoLocalList, true)
  2039. }
  2040. })
  2041. }
  2042. // 组件消失生命周期
  2043. aboutToDisappear() {
  2044. console.info('LifeCycleComponent aboutToDisappear');
  2045. this.deletionWatcher?.stop();
  2046. this.knockController?.immersiveDisableListening();
  2047. this.curIndex = 0
  2048. emitter.off(EventConstants.EVENT_AUDIO_OPEN);
  2049. emitter.off(EventConstants.EVENT_SCAN_UPDATE);
  2050. emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
  2051. emitter.off(EventConstants.EVENT_SETTING_UPDATE);
  2052. this.mDestroyPage = true;
  2053. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  2054. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  2055. this.stop();
  2056. }
  2057. this.mIjkMediaPlayer.off('audioInterrupt');
  2058. this.mIjkMediaPlayer.off('deviceChange');
  2059. if (workerInstance) {
  2060. workerInstance.terminate();
  2061. }
  2062. this.stopPip();
  2063. this.destroyPipController()
  2064. this.getUIContext().getHostContext()!.eventHub.off('playOrPause');
  2065. this.getUIContext().getHostContext()!.eventHub.off('playPrevious');
  2066. this.getUIContext().getHostContext()!.eventHub.off('playNext');
  2067. this.getUIContext().getHostContext()!.eventHub.off('showPlayerView');
  2068. this.getUIContext().getHostContext()!.eventHub.off('openPlayList');
  2069. }
  2070. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean,openItem?:VideoItem) {
  2071. this.isFavMusic = false
  2072. console.info('onecold getSortedFiles 1 curPath '+curPath)
  2073. if (isWorkerPost) {
  2074. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  2075. }
  2076. if (this.modeType !== 0) {
  2077. return
  2078. }
  2079. console.info('onecold getSortedFiles 2')
  2080. this.isCanBack = false
  2081. this.currentPath = curPath
  2082. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  2083. this.titleName = getFileDirName(this.currentPath,this.rootPath)
  2084. if (curPath === this.rootPath) {
  2085. this.rightTopImage = $r('sys.symbol.sort')
  2086. } else {
  2087. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  2088. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  2089. this.rightTopImage = $r('sys.symbol.chevron_left')
  2090. }
  2091. }
  2092. // Get the current file list and calculate its hash
  2093. this.fileList = FileUtil.listFileSync(curPath);
  2094. const currentHash = simpleHash(this.fileList);
  2095. // Check cache
  2096. const cachedValue = this.findCache(curPath);
  2097. Logger.info('onecold cachedValue = ' + cachedValue)
  2098. const cachedHash = this.findStringCache(curPath + '_hash');
  2099. const cachedDirList = this.findCache(curPath + "_dirList");
  2100. if (cachedValue !== undefined&&!this.isRefreshing) {
  2101. // this.videoLocalList = cachedValue;
  2102. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  2103. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  2104. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  2105. }
  2106. this.isRefreshing = false
  2107. this.updateListData(cachedValue)
  2108. }
  2109. if (cachedDirList !== undefined) {
  2110. this.dirList = cachedDirList
  2111. }
  2112. //通过当前hash值和缓存hash判断list有没有变化
  2113. if (cachedValue && cachedHash === currentHash) {
  2114. return;
  2115. }
  2116. // this.fileList = FileUtil.listFileSync(curPath)
  2117. let directories: Array<VideoItem> = [];
  2118. let files: Array<VideoItem> = [];
  2119. for (let i = 0; i < this.fileList.length; i++) {
  2120. // console.info(`The name of file: ${this.fileList[i]}`);
  2121. let path = curPath + '/' + this.fileList[i]
  2122. if (FileUtil.isDirectory(path)) {
  2123. let item: VideoItem =
  2124. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  2125. '')
  2126. if (this.isShowDir(item.name)) {
  2127. directories.push(item);
  2128. }
  2129. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2130. // Utility.doSortListAscending(directories)
  2131. } else {
  2132. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  2133. let item: VideoItem =
  2134. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  2135. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  2136. files.push(item);
  2137. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2138. // this.doSortListAscending(files)
  2139. }
  2140. }
  2141. }
  2142. }
  2143. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  2144. if (this.currentPath !== this.lockPath) {
  2145. files = result;
  2146. }
  2147. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2148. Utility.doSortListAscending(files)
  2149. if (this.currentPath === this.rootPath) {
  2150. this.dirList = directories
  2151. this.addCache(curPath + "_dirList", this.dirList);
  2152. }
  2153. //插入广告先注释掉
  2154. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  2155. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  2156. // directories.push(adItem)
  2157. // }
  2158. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  2159. this.videoLocalList = directories.concat(files);
  2160. this.updateListData(this.videoLocalList)
  2161. if (ArrayUtil.isNotEmpty(files)) {
  2162. if (this.currentPath != this.rootPath) {
  2163. if (files) {
  2164. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  2165. }
  2166. }
  2167. // 缓存结果
  2168. this.addCache(curPath, this.videoLocalList);
  2169. await this.saveCacheToStorage(); // 保存缓存至本地存储
  2170. this.addStringCache(curPath + '_hash', currentHash);
  2171. }
  2172. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  2173. for (let i = 0; i < this.videoLocalList.length; i++) {
  2174. console.info(`onecold gengxin 1: ${this.videoLocalList[i].name}`);
  2175. }
  2176. // this.setButtonStatus()
  2177. this.openMusic(isOpen, destPath,openItem)
  2178. this.isRefreshing = false
  2179. });
  2180. }
  2181. //第三方app打开天天静听导入音乐后播放
  2182. openMusic(isOpen?: boolean, destPath?: string,openItem?:VideoItem){
  2183. if (isOpen&&destPath) {
  2184. if (destPath === undefined) {
  2185. // 处理 destPath 为 undefined 的情况
  2186. return
  2187. }
  2188. if (destPath.endsWith('.lrc')) {
  2189. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  2190. if (StrUtil.isNotEmpty(this.videoUrl)) {
  2191. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  2192. this.initLyric(lyricPath);
  2193. }
  2194. return
  2195. }
  2196. if(openItem){
  2197. this.doPlay(openItem,0,false,true)
  2198. // this.isShowPlay = true
  2199. this.setShowPlayTrue()
  2200. }
  2201. }
  2202. }
  2203. //扫描文件夹入库
  2204. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  2205. const files = FileUtil.listFileSync(curPath);
  2206. let mediaItems: VideoItem[] = [];
  2207. Logger.info('onecold scanDirectory start ')
  2208. for (const file of files) {
  2209. const fPath = `${curPath}/${file}`;
  2210. if (fPath === this.lockPath) {
  2211. Logger.info(`Skipping locked path: ${fPath}`);
  2212. continue;
  2213. }
  2214. if (FileUtil.isDirectory(fPath)) {
  2215. // Recursively scan subdirectories
  2216. const subDirItems = await this.scanDirectory(fPath);
  2217. mediaItems = mediaItems.concat(subDirItems);
  2218. } else {
  2219. Logger.info('onecold scanDirectory filePath = ' + fPath)
  2220. // Process media files
  2221. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  2222. let mediaItem: VideoItem =
  2223. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2224. mediaItems.push(mediaItem);
  2225. this.table.insert(mediaItem, (id: number) => {
  2226. });
  2227. }
  2228. }
  2229. }
  2230. return mediaItems;
  2231. }
  2232. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  2233. this.isShowTitleBar = true
  2234. animateTo({ duration: 666 }, () => {
  2235. this.opacityItem = 0.5;
  2236. });
  2237. setTimeout(() => {
  2238. this.videoLocalList = mList;
  2239. if (!noSort) {
  2240. if (this.modeType === 0 || this.modeType === 1) {
  2241. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  2242. this.doSortType(this.sortType)
  2243. }
  2244. }
  2245. this.dataSource.pushArrayData(this.videoLocalList)
  2246. animateTo({ duration: 666 }, () => {
  2247. this.opacityItem = 1;
  2248. });
  2249. this.setButtonStatus()
  2250. //添加到字母索引表
  2251. this.setAlphaBet()
  2252. }, 200);
  2253. }
  2254. getCurFileList(): Array<VideoItem> {
  2255. if(this.isSearchMode){
  2256. return this.filteredList
  2257. }
  2258. let files: Array<VideoItem> = [];
  2259. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2260. for (let i = 0; i < this.videoLocalList.length; i++) {
  2261. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  2262. files.push(this.videoLocalList[i]);
  2263. }
  2264. }
  2265. }
  2266. return files
  2267. }
  2268. setButtonStatus() {
  2269. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2270. this.isZero = false
  2271. } else {
  2272. this.isZero = true
  2273. }
  2274. if (this.currentPath !== this.rootPath &&
  2275. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  2276. this.isHasDir = true //不为空,说明有子文件夹
  2277. } else {
  2278. this.isHasDir = false
  2279. }
  2280. }
  2281. @Builder
  2282. SortMenuBuilder() {
  2283. Menu() {
  2284. MenuItem({
  2285. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2286. content: "按艺术家升序"
  2287. })
  2288. .onClick(async () => {
  2289. this.doSortType(0)
  2290. PreferencesUtil.put(SettingPage.SORT_TYPE, 0)
  2291. this.updateListData(this.videoLocalList, true)
  2292. })
  2293. MenuItem({
  2294. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2295. content: "按艺术家降序"
  2296. })
  2297. .onClick(async () => {
  2298. this.doSortType(1)
  2299. PreferencesUtil.put(SettingPage.SORT_TYPE, 1)
  2300. this.updateListData(this.videoLocalList, true)
  2301. })
  2302. MenuItem({
  2303. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat_size_square')),
  2304. content: "按专辑升序"
  2305. })
  2306. .onClick(async () => {
  2307. this.doSortType(2)
  2308. PreferencesUtil.put(SettingPage.SORT_TYPE, 2)
  2309. this.updateListData(this.videoLocalList, true)
  2310. })
  2311. MenuItem({
  2312. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.character_arrow_clockwise')),
  2313. content: "按专辑降序"
  2314. })
  2315. .onClick(async () => {
  2316. this.doSortType(3)
  2317. PreferencesUtil.put(SettingPage.SORT_TYPE, 3)
  2318. this.updateListData(this.videoLocalList, true)
  2319. })
  2320. MenuItem({
  2321. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2322. content: $r('app.string.sort_by_name')
  2323. })
  2324. .onClick(async () => {
  2325. this.doSortType(4)
  2326. PreferencesUtil.put(SettingPage.SORT_TYPE, 4)
  2327. this.updateListData(this.videoLocalList, true)
  2328. })
  2329. MenuItem({
  2330. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2331. content: '按名称降序'
  2332. })
  2333. .onClick(async () => {
  2334. this.doSortType(5)
  2335. PreferencesUtil.put(SettingPage.SORT_TYPE, 5)
  2336. this.updateListData(this.videoLocalList, true)
  2337. })
  2338. MenuItem({
  2339. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2340. content: $r('app.string.sort_by_time')
  2341. })
  2342. .onClick(async () => {
  2343. this.doSortType(6)
  2344. PreferencesUtil.put(SettingPage.SORT_TYPE, 6)
  2345. this.updateListData(this.videoLocalList, true)
  2346. })
  2347. MenuItem({
  2348. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  2349. content: '按添加时间降序'
  2350. })
  2351. .onClick(async () => {
  2352. this.doSortType(7)
  2353. PreferencesUtil.put(SettingPage.SORT_TYPE, 7)
  2354. this.updateListData(this.videoLocalList, true)
  2355. })
  2356. }.attributeModifier(new MenuModifier())
  2357. }
  2358. @Builder
  2359. SortMenuForArtistAblumBuilder() {
  2360. Menu() {
  2361. MenuItem({
  2362. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2363. content: $r('app.string.sort_by_name')
  2364. })
  2365. .onClick(async () => {
  2366. this.doSortType(4)
  2367. // PreferencesUtil.put(SettingPage.SORT_TYPE, 2)
  2368. this.updateListData(this.videoLocalList, true)
  2369. })
  2370. MenuItem({
  2371. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2372. content: '按名称降序'
  2373. })
  2374. .onClick(async () => {
  2375. this.doSortType(5)
  2376. this.updateListData(this.videoLocalList, true)
  2377. })
  2378. MenuItem({
  2379. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2380. content: '按数量升序'
  2381. })
  2382. .onClick(async () => {
  2383. this.doSortType(8)
  2384. this.updateListData(this.videoLocalList, true)
  2385. })
  2386. MenuItem({
  2387. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  2388. content: '按数量降序'
  2389. })
  2390. .onClick(async () => {
  2391. this.doSortType(9)
  2392. this.updateListData(this.videoLocalList, true)
  2393. })
  2394. }.attributeModifier(new MenuModifier())
  2395. }
  2396. doSortType(index: number) {
  2397. switch (index) {
  2398. case 0:
  2399. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2400. // 类型排序优先级
  2401. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2402. if (typeOrder !== 0) {
  2403. return typeOrder;
  2404. }
  2405. // 处理艺术家可能为undefined的字符串比较
  2406. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  2407. const artistB = b.artist?.trim() || '';
  2408. return artistA.localeCompare(artistB);
  2409. });
  2410. break;
  2411. case 1:
  2412. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2413. // 类型排序优先级
  2414. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2415. if (typeOrder !== 0) {
  2416. return typeOrder;
  2417. }
  2418. // 处理艺术家可能为undefined的字符串比较
  2419. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  2420. const artistB = b.artist?.trim() || '';
  2421. return artistB.localeCompare(artistA);
  2422. });
  2423. break;
  2424. case 2:
  2425. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2426. // 类型排序优先级
  2427. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2428. if (typeOrder !== 0) {
  2429. return typeOrder;
  2430. }
  2431. // 处理专辑可能为undefined的字符串比较
  2432. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  2433. const albumB = b.album?.trim() || '';
  2434. return albumA.localeCompare(albumB);
  2435. });
  2436. break;
  2437. case 3:
  2438. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2439. // 类型排序优先级
  2440. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2441. if (typeOrder !== 0) {
  2442. return typeOrder;
  2443. }
  2444. // 处理专辑可能为undefined的字符串比较
  2445. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  2446. const albumB = b.album?.trim() || '';
  2447. return albumB.localeCompare(albumA);
  2448. });
  2449. break;
  2450. case 4:
  2451. Utility.doSortListAscending(this.videoLocalList,this.isShowFileName)
  2452. break;
  2453. case 5:
  2454. Utility.doSortListDescending(this.videoLocalList,this.isShowFileName)
  2455. break;
  2456. case 6:
  2457. this.videoLocalList.sort((a, b) => {
  2458. // First, sort by type
  2459. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2460. if (typeOrder !== 0) {
  2461. return typeOrder;
  2462. }
  2463. // If types are the same, sort by cTime in ascending order
  2464. return a.cTime.localeCompare(b.cTime);
  2465. });
  2466. break;
  2467. case 7:
  2468. this.videoLocalList.sort((a, b) => {
  2469. // First, sort by type
  2470. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2471. if (typeOrder !== 0) {
  2472. return typeOrder;
  2473. }
  2474. // If types are the same, sort by cTime in descending order
  2475. return b.cTime.localeCompare(a.cTime);
  2476. });
  2477. break;
  2478. case 8:
  2479. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  2480. // 1. Sort by type first
  2481. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  2482. if (typeOrder !== 0) {
  2483. return typeOrder;
  2484. }
  2485. // 2. Then sort by artist count (numeric comparison)
  2486. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  2487. if(this.modeType === 2){
  2488. sortMap = this.artistMap
  2489. }else{
  2490. sortMap = this.albumMap
  2491. }
  2492. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  2493. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  2494. return aArtistCount - bArtistCount;
  2495. });
  2496. break;
  2497. case 9:
  2498. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  2499. // 1. Sort by type first
  2500. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  2501. if (typeOrder !== 0) {
  2502. return typeOrder;
  2503. }
  2504. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  2505. if(this.modeType === 2){
  2506. sortMap = this.artistMap
  2507. }else{
  2508. sortMap = this.albumMap
  2509. }
  2510. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  2511. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  2512. return bArtistCount - aArtistCount;
  2513. });
  2514. break;
  2515. }
  2516. }
  2517. showSheelDialog() {
  2518. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  2519. // this.showTips()
  2520. // return
  2521. // }
  2522. this.showAddDialog()
  2523. }
  2524. showAddDialog() {
  2525. if (this.modeType === 2 || this.modeType === 3) {
  2526. return
  2527. }
  2528. DialogHelper.showActionSheetDialog({
  2529. title: "请选择添加方式(建议歌词文件一起导入)",
  2530. sheets: [
  2531. { value: "新建文件夹", fontColor: $r('app.color.text_color') },
  2532. { value: "手动导入", fontColor: $r('app.color.text_color') },
  2533. { value: "自动导入", fontColor: $r('app.color.text_color') },
  2534. { value: "全选导入", fontColor: $r('app.color.text_color') },
  2535. ],
  2536. maskColor: Color.Transparent,
  2537. backgroundColor: $r('app.color.bg_card'),
  2538. transition: AnimationHelper.transitionInDown(555),
  2539. onAction: (index) => {
  2540. switch (index) {
  2541. case 0:
  2542. if (this.modeType === 0) {
  2543. this.showMkDialog()
  2544. } else {
  2545. ToastUtil.showToast('请切换到首页才能新建文件夹!')
  2546. }
  2547. break;
  2548. case 1:
  2549. this.callFilePickerSelectFile()
  2550. break;
  2551. case 2:
  2552. this.showTips()
  2553. break;
  2554. case 3:
  2555. this.goSelectMusic()
  2556. break;
  2557. }
  2558. }
  2559. })
  2560. }
  2561. //拉起音频
  2562. goSelectMusic() {
  2563. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  2564. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  2565. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  2566. ) {
  2567. ToastUtil.showToast('暂时不支持该设备')
  2568. return
  2569. }
  2570. try {
  2571. let documentSelectOptions = new picker.DocumentSelectOptions();
  2572. documentSelectOptions.authMode = true
  2573. documentSelectOptions.multiAuthMode = true
  2574. if( deviceInfo.sdkApiVersion>=21){//如果api大于21 ,可以支持1w首歌以上
  2575. documentSelectOptions.maxSelectNumber = 20000
  2576. }
  2577. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  2578. let documentPicker = new picker.DocumentViewPicker(this.context);
  2579. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  2580. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  2581. this.saveVideoDatas(documentSelectResult)
  2582. }
  2583. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  2584. JSON.stringify(documentSelectResult));
  2585. }).catch((err: BusinessError) => {
  2586. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  2587. });
  2588. } catch (error) {
  2589. let err: BusinessError = error as BusinessError;
  2590. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2591. }
  2592. }
  2593. async showTips() {
  2594. try {
  2595. this.getUIContext().getPromptAction().showDialog({
  2596. title: '导入指南',
  2597. message:'用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2598. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2599. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2600. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后去文件扫描一下。\n',
  2601. buttons: [
  2602. {
  2603. text: '知道了',
  2604. color: '#000000'
  2605. },
  2606. ]
  2607. }, (err, data) => {
  2608. if (err) {
  2609. console.error('showDialog err: ' + err);
  2610. return;
  2611. }
  2612. console.info('showDialog success callback, click button: ' + data.index);
  2613. });
  2614. } catch (error) {
  2615. let message = (error as BusinessError).message;
  2616. let code = (error as BusinessError).code;
  2617. console.error(`showDialog args error code is ${code}, message is ${message}`);
  2618. };
  2619. // DialogHelper.showTipsDialog({
  2620. // title: '使用提示:自动导入教程',
  2621. //
  2622. // content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2623. // + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2624. // '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2625. // '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  2626. // onAction: (action) => {
  2627. // if (action == DialogAction.TWO) {
  2628. // PreferencesUtil.putSync('isFirstMusic', false)
  2629. // router.pushUrl({
  2630. // url: 'pages/ScanFilePage'
  2631. // });
  2632. // }
  2633. // }
  2634. // })
  2635. }
  2636. showMkDialog() {
  2637. DialogHelper.showTextInputDialog({
  2638. title: '新建歌单',
  2639. maskColor: Color.Transparent,
  2640. text: '',
  2641. transition: AnimationHelper.transitionInDown(666),
  2642. onChange: (text) => {
  2643. console.error("onChange: " + text);
  2644. },
  2645. onAction: (action, dialogId, content) => {
  2646. // ToastUtil.showToast('content = ' +content)
  2647. if (action == DialogAction.TWO) {
  2648. const newName = content
  2649. const newPath = this.currentPath + '/' + newName
  2650. FileUtil.mkdir(newPath, true).then(() => {
  2651. this.cache.delete(this.currentPath); // 删除目标路径缓存
  2652. this.getSortedFiles(this.currentPath)
  2653. }).catch((error: BusinessError) => {
  2654. console.error(error.message);
  2655. });
  2656. }
  2657. }
  2658. })
  2659. }
  2660. @State progress: number = 0;
  2661. async saveVideoDatas(uris:string[],isOpen?:boolean){
  2662. if (ArrayUtil.isEmpty(uris)) {
  2663. return;
  2664. }
  2665. console.info('onecold this.isCopyFileToDownLoad = ' + this.isCopyFileToDownLoad);
  2666. if(this.isCopyFileToDownLoad||this.currentPath==this.lockPath||isOpen){
  2667. this.saveVideoDatasToDownLoad(uris,isOpen)
  2668. return
  2669. }
  2670. // 初始化进度条
  2671. this.progress = 0;
  2672. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  2673. progress: this.progress,
  2674. backCancel: false,
  2675. autoCancel: false,
  2676. loadColor: $r('app.color.title_bar_bg'),
  2677. fontColor: $r('app.color.title_bar_bg')
  2678. });
  2679. // 计算处理总数用于进度计算
  2680. const totalItems = uris.length;
  2681. let processedItems = 0;
  2682. for (let i = 0; i < uris.length; i++) {
  2683. let filePath = uris[i];
  2684. try {
  2685. if (this.currentPath !== this.lockPath) { // 判断不是私密音乐,才入库
  2686. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2687. let mediaItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context,
  2688. filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2689. console.info('onecold saveVideoDatas filePath = ' + filePath)
  2690. if (!filePath.includes(this.rootPath)) {
  2691. console.info('onecold saveVideoDatas mediaItem.parentPath111 = ' + mediaItem.parentPath)
  2692. mediaItem.parentPath = this.currentPath;
  2693. }
  2694. console.info('onecold saveVideoDatas mediaItem.parentPath = ' + mediaItem.parentPath)
  2695. this.table.insert(mediaItem, (id: number) => {
  2696. // 插入完成回调
  2697. });
  2698. }
  2699. }
  2700. // 更新进度
  2701. processedItems++;
  2702. this.progress = Math.floor((processedItems / totalItems) * 100);
  2703. DialogHelper.updateLoading(this.loadingProgressDialogId,` 正在处理 ${this.progress}%`, this.progress);
  2704. } catch (error) {
  2705. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2706. // 即使出错也更新进度
  2707. processedItems++;
  2708. this.progress = Math.floor((processedItems / totalItems) * 100);
  2709. DialogHelper.updateLoading(this.loadingProgressDialogId,` 正在处理 ${this.progress}%`, this.progress);
  2710. }
  2711. }
  2712. // 关闭进度条
  2713. DialogHelper.closeDialog(this.loadingProgressDialogId)
  2714. this.isZero = false
  2715. // 删除目标路径缓存
  2716. setTimeout(() => {
  2717. this.cache.delete(this.currentPath);
  2718. this.getSortedFiles(this.currentPath,false,uris[0],isOpen)
  2719. this.setButtonStatus()
  2720. }, 500);
  2721. }
  2722. async saveVideoDatasToDownLoad(uris: string[], isOpen?: boolean) {
  2723. if (ArrayUtil.isEmpty(uris)) {
  2724. return;
  2725. }
  2726. let newUris: string[] = [];
  2727. this.progress = 0
  2728. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  2729. progress: this.progress,
  2730. backCancel: false,
  2731. autoCancel: false,
  2732. loadColor: this.themeColor,
  2733. fontColor: this.themeColor
  2734. });
  2735. // 计算所有文件的总大小
  2736. let totalSize = 0;
  2737. for (let uri of uris) {
  2738. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  2739. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  2740. await fileIo.close(sourceFile.fd);
  2741. }
  2742. let totalRead = 0;
  2743. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  2744. Logger.info(TAG, 'destPath uri: ' + destPath);
  2745. for (let i = 0; i < uris.length; i++) {
  2746. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  2747. Logger.info(TAG, 'filePath uri: ' + filePath);
  2748. newUris.push(filePath);
  2749. try {
  2750. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  2751. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  2752. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  2753. const buffer = new ArrayBuffer(buffSize);
  2754. let len = await fileIo.read(sourceFile.fd, buffer);
  2755. while (len > 0) {
  2756. await fileIo.write(destFile.fd, buffer.slice(0, len));
  2757. totalRead += len;
  2758. // 计算总进度
  2759. this.progress = Math.floor((totalRead / totalSize) * 100);
  2760. DialogHelper.updateLoading( this.loadingProgressDialogId,`正在导入 ${this.progress}%`, this.progress);
  2761. len = await fileIo.read(sourceFile.fd, buffer);
  2762. }
  2763. await fileIo.close(sourceFile.fd);
  2764. await fileIo.close(destFile.fd);
  2765. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  2766. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2767. let mediaItem: VideoItem =
  2768. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2769. this.table.insert(mediaItem, (id: number) => {
  2770. // 删除目标路径缓存
  2771. this.cache.delete(this.currentPath);
  2772. this.getSortedFiles(this.currentPath, true, destPath, isOpen,mediaItem)
  2773. });
  2774. }
  2775. }
  2776. } catch (error) {
  2777. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2778. }
  2779. }
  2780. DialogHelper.closeDialog(this.loadingProgressDialogId);
  2781. this.isZero = false
  2782. Logger.info(TAG, 'scan select video result:' + newUris)
  2783. }
  2784. //拉起音频
  2785. // goSelectMusic(){
  2786. //
  2787. // try {
  2788. // let audioSelectOptions = new picker.AudioSelectOptions();
  2789. // let audioPicker = new picker.AudioViewPicker(this.context);
  2790. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  2791. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  2792. // this.saveVideoDatas(audioSelectResult)
  2793. // }
  2794. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  2795. // }).catch((err: BusinessError) => {
  2796. //
  2797. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  2798. // });
  2799. // } catch (error) {
  2800. // let err: BusinessError = error as BusinessError;
  2801. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2802. // }
  2803. //
  2804. //
  2805. //
  2806. // }
  2807. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  2808. if (!item) {
  2809. return undefined;
  2810. }
  2811. try {
  2812. let selectUris: Array<string> = [];
  2813. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  2814. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  2815. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  2816. photoSelectOptions.maxSelectNumber = 1;
  2817. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  2818. selectUris = photoSelectResult.photoUris;
  2819. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  2820. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  2821. console.info('file fd: ' + file.fd);
  2822. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  2823. let imagePath = this.context.filesDir + FileUtil.separator + name
  2824. imagePath = fileUri.getUriFromPath(imagePath)
  2825. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  2826. fileIo.copyFileSync(file.fd, file2.fd)
  2827. fileIo.closeSync(file);
  2828. fileIo.closeSync(file2);
  2829. if (item.filePath == this.currentSong?.filePath) {
  2830. this.cover = imagePath
  2831. }
  2832. if (item) {
  2833. item.pixelMapPath = imagePath
  2834. }
  2835. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  2836. if (success) {
  2837. this.doUpdateData()
  2838. console.log("onecold 更新音乐封面成功,数据库已同步");
  2839. } else {
  2840. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  2841. }
  2842. });
  2843. LogUtil.debug("onecold this.cover =" + this.cover)
  2844. return FileUtil.getFilePath(imagePath); // Return the image path here
  2845. } catch (err) {
  2846. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  2847. return undefined;
  2848. }
  2849. }
  2850. // 拉起picker选择文件管理器
  2851. async callFilePickerSelectFile(): Promise<void> {
  2852. try {
  2853. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  2854. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  2855. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  2856. } else {
  2857. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  2858. }
  2859. let documentPicker = new picker.DocumentViewPicker();
  2860. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  2861. Logger.info(TAG,
  2862. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  2863. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  2864. this.saveVideoDatas(DocumentSelectResult)
  2865. }
  2866. }).catch((err: BusinessError) => {
  2867. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  2868. });
  2869. } catch (err) {
  2870. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  2871. }
  2872. }
  2873. //重命名的对话框
  2874. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  2875. if(!item.filePath.includes(this.packName)){
  2876. ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限重命名')
  2877. return
  2878. }
  2879. DialogHelper.showTextInputDialog({
  2880. title: '重命名',
  2881. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  2882. maskColor: Color.Transparent,
  2883. backgroundColor: Color.Grey,
  2884. transition: AnimationHelper.transitionInDown(666),
  2885. onChange: (text) => {
  2886. console.error("onChange: " + text);
  2887. },
  2888. onAction: (action, dialogId, content) => {
  2889. // ToastUtil.showToast('content = ' +content)
  2890. if (action == DialogAction.TWO) {
  2891. const newName = content
  2892. const newPath = this.currentPath + '/' + newName
  2893. console.log("onecold item = " + item.type);
  2894. this.doReName(index, newName, filePath, newPath, item)
  2895. }
  2896. }
  2897. })
  2898. }
  2899. //剪切 移动到另个文件夹的对话框
  2900. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2901. Logger.info('onecold showCutDialog')
  2902. let mList: Array<string> = []
  2903. let rPath = this.rootPath
  2904. if (isCurrent) {
  2905. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2906. rPath = this.currentPath
  2907. } else {
  2908. mList = Utility.getNameList(this.dirList);
  2909. rPath = this.rootPath
  2910. }
  2911. let dataBean = new BubbleBean()
  2912. dataBean.data = mList
  2913. dataBean.color = this.themeColor
  2914. dataBean.onItemClick = (i) => {
  2915. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2916. Logger.info('newPath = ' + newPath)
  2917. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  2918. ToastUtil.showToast('移动成功')
  2919. this.table.deleteData(item, () => {
  2920. });
  2921. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2922. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2923. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2924. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2925. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2926. this.table.insert(newItem, (id: number) => {
  2927. //加入数据库
  2928. });
  2929. }
  2930. this.cache.delete(this.currentPath); // 删除原路径缓存
  2931. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2932. this.getSortedFiles(this.currentPath, true)
  2933. }).catch((error: BusinessError) => {
  2934. console.error(error.message);
  2935. });
  2936. XPopup.dismissTop()
  2937. }
  2938. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2939. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2940. popupPosition = PopupPosition.TOP
  2941. }
  2942. if (index <= 3) {
  2943. popupPosition = PopupPosition.BOTTOM
  2944. }
  2945. let pup: XPopup
  2946. if (this.isDarkMode) {
  2947. pup = XPopup.Builder()
  2948. .setPopupPosition(popupPosition)
  2949. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  2950. .setBackgroundColor(Color.Black)
  2951. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2952. .show()
  2953. } else {
  2954. pup = XPopup.Builder()
  2955. .setPopupPosition(popupPosition)
  2956. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  2957. .setBackgroundColor(Color.White)
  2958. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2959. .show()
  2960. }
  2961. }
  2962. //复制 到另个文件夹的对话框
  2963. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2964. Logger.info('onecoldv showCopyDialog')
  2965. let mList: Array<string> = []
  2966. let rPath = this.rootPath
  2967. if (isCurrent) {
  2968. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2969. rPath = this.currentPath
  2970. } else {
  2971. mList = Utility.getNameList(this.dirList);
  2972. rPath = this.rootPath
  2973. }
  2974. let dataBean = new BubbleBean()
  2975. dataBean.data = mList
  2976. dataBean.isCopy = true
  2977. dataBean.color = this.themeColor
  2978. dataBean.onItemClick = (i) => {
  2979. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2980. Logger.info('newPath = ' + newPath)
  2981. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2982. ToastUtil.showToast('复制成功')
  2983. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2984. this.getSortedFiles(this.currentPath)
  2985. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2986. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2987. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2988. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2989. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2990. this.table.insert(newItem, (id: number) => {
  2991. //加入数据库
  2992. });
  2993. }
  2994. }).catch((error: BusinessError) => {
  2995. console.error(error.message);
  2996. });
  2997. XPopup.dismissTop()
  2998. }
  2999. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  3000. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  3001. popupPosition = PopupPosition.TOP
  3002. }
  3003. if (index <= 3) {
  3004. popupPosition = PopupPosition.BOTTOM
  3005. }
  3006. let pup: XPopup
  3007. if (this.isDarkMode) {
  3008. pup = XPopup.Builder()
  3009. .setPopupPosition(popupPosition)
  3010. .atView(id)
  3011. .setMaxHeight('60%')
  3012. .setBackgroundColor(Color.Black)
  3013. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3014. .show();
  3015. } else {
  3016. pup = XPopup.Builder()
  3017. .setPopupPosition(popupPosition)
  3018. .atView(id)
  3019. .setMaxHeight('60%')
  3020. .setBackgroundColor(Color.White)
  3021. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3022. .show();
  3023. }
  3024. }
  3025. //重命名索引index的视频
  3026. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  3027. FileUtil.rename(oldPath, newPath).then(async () => {
  3028. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  3029. if (info.type === CommonConstants.TYPE_IS_DIR) {
  3030. //如果是文件夹先删除源数据,再添加新数据
  3031. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  3032. if (success) {
  3033. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  3034. } else {
  3035. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  3036. }
  3037. });
  3038. this.scanDirectory(newPath)
  3039. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  3040. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  3041. if (success) {
  3042. console.log(" onecold 重命名成功,数据库已同步");
  3043. } else {
  3044. console.error(" onecold 重命名数据库失败原因: " + error);
  3045. }
  3046. });
  3047. }
  3048. let mediaItem: VideoItem =
  3049. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3050. this.videoLocalList[index] = mediaItem;
  3051. }
  3052. this.cache.delete(this.currentPath)
  3053. this.getSortedFiles(this.currentPath, true)
  3054. }).catch((error: BusinessError) => {
  3055. console.error(error.message);
  3056. });
  3057. }
  3058. build() {
  3059. Stack() {
  3060. this.ContentBuild()
  3061. Stack() {
  3062. Column()
  3063. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  3064. height: '95%',
  3065. dragBar: true,
  3066. showClose: true,
  3067. blurStyle: BlurStyle.Thin,
  3068. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3069. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  3070. title: {
  3071. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  3072. + `(${this.songList.length}首)`
  3073. }
  3074. })
  3075. }
  3076. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  3077. modalTransition: this.isCoverRectangle?ModalTransition.DEFAULT:ModalTransition.NONE,
  3078. transition: this.isCoverRectangle?null:AnimationHelper.transitionInDown(500),
  3079. onWillDisappear: () => {
  3080. this.setShowPlayFalse()
  3081. },
  3082. })
  3083. }
  3084. .alignContent(Alignment.Bottom)
  3085. .width('100%')
  3086. .height('100%')
  3087. }
  3088. @Builder
  3089. ContentBuild() {
  3090. Scroll() {
  3091. Column() {
  3092. Stack() {
  3093. //libraryname加上去后onKeyEvent监听不了,因为目前的解决方案是上面的XComponent,去掉libraryname
  3094. XComponent({ id: 'for_onKeyEvent',type: XComponentType.SURFACE,
  3095. controller: this.xcomponentController })
  3096. .onLoad(async (event?: object) => {
  3097. })
  3098. .focusable(true)
  3099. .height(0)
  3100. .focusOnTouch(true)
  3101. .defaultFocus(true) // 自动获取键盘焦点
  3102. .onKeyEvent((event?: KeyEvent) => {
  3103. console.info('onecold点击 onKeyEvent')
  3104. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  3105. if (!event || event.type !== KeyType.Down) {
  3106. return;
  3107. }
  3108. console.info('onecold点击 onKeyEvent event.keyCode: ' + event.keyCode)
  3109. //空格键 Space key controls pause/play
  3110. if (event.keyCode === KeyCode.KEYCODE_SPACE|| event.keyCode === KeyCode.KEYCODE_MEDIA_PLAY_PAUSE) {
  3111. this.playOrPause()
  3112. }
  3113. if (event.keyCode === KeyCode.KEYCODE_DPAD_UP) {
  3114. this.playPrevious()
  3115. }
  3116. if (event.keyCode === KeyCode.KEYCODE_DPAD_DOWN) {
  3117. this.playNext()
  3118. }
  3119. // Right-click to fast forward
  3120. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  3121. this.fastForward()
  3122. }
  3123. // Left-click to rewind
  3124. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  3125. this.backForward()
  3126. }
  3127. })
  3128. Column() {
  3129. XComponent({
  3130. id: 'xcomponentId',
  3131. type: 'surface',
  3132. libraryname: 'ijkplayer_napi',
  3133. controller: this.xcomponentController
  3134. })
  3135. .onLoad((event?: object) => {
  3136. if (!!event) {
  3137. this.initDelayPlay(event);
  3138. }
  3139. })
  3140. .onDestroy(() => {
  3141. })
  3142. .width('100%')// .width(this.videoWidth)
  3143. .aspectRatio(this.videoAspectRatio)
  3144. }
  3145. .aspectRatio(this.videoAspectRatio)
  3146. .justifyContent(FlexAlign.Center)
  3147. .backgroundColor(Color.Transparent)
  3148. .visibility(Visibility.Hidden)
  3149. .height(CommonConstants.FULL_PERCENT)
  3150. .width(CommonConstants.FULL_PERCENT)
  3151. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  3152. height:this.isLandscape?'80%': '43%',
  3153. dragBar: true,
  3154. showClose: true,
  3155. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3156. blurStyle:BlurStyle.Thin,
  3157. backgroundColor:Color.Transparent,
  3158. title: { title: 'AB循环' }
  3159. })
  3160. Stack() {
  3161. Column() {
  3162. if(this.twoFingerType==4){
  3163. this.getWaterView()
  3164. }else{
  3165. if(this.isGridMusic){
  3166. this.getGridView()
  3167. }else {
  3168. this.getList()
  3169. }
  3170. }
  3171. if (this.modeType ==0||this.modeType==4) {
  3172. Column() {
  3173. emptyView(this.themeColor)
  3174. }
  3175. .onClick(()=>{
  3176. this.asyncCurrentPathOnlyFile()
  3177. })
  3178. .position({ top: 200 })
  3179. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  3180. .animation({ duration: 500 }),
  3181. TransitionEffect.scale({ x: 0, y: 0 })))
  3182. .justifyContent(FlexAlign.Center)
  3183. .opacity(this.isZero ? 1 : 0)
  3184. .visibility(this.isZero && !this.isFavMusic && !this.isHistory
  3185. ? Visibility.Visible : Visibility.None)
  3186. .animation({
  3187. duration: 500,
  3188. curve: Curve.Friction // 可选动画曲线
  3189. })
  3190. .width('100%')
  3191. }
  3192. }
  3193. .layoutWeight(1)
  3194. .height('100%')
  3195. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  3196. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3197. .onDrop((event?: DragEvent) => {
  3198. try {
  3199. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3200. if (dragData !== undefined) {
  3201. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3202. if (records.length > 0) {
  3203. for (let i = 0; i < records.length; i++) {
  3204. let types = records[i].getTypes();
  3205. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3206. const fileUriUds =
  3207. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3208. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3209. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3210. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3211. this.targetFile = fileUriUds.oriUri;
  3212. this.saveVideoDatas([this.targetFile])
  3213. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3214. }
  3215. }
  3216. }
  3217. } else {
  3218. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3219. }
  3220. } else {
  3221. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3222. }
  3223. } catch (error) {
  3224. const err = error as BusinessError;
  3225. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3226. }
  3227. })
  3228. // 右侧居中的字母表索引
  3229. if(this.showZMIndex){
  3230. this.indexBuilder()
  3231. }
  3232. this.topTitleBar()
  3233. }
  3234. .alignContent(Alignment.Top)
  3235. .layoutWeight(1)
  3236. .height('100%')
  3237. Row() {
  3238. Button(this.isAllSelected ? '反选' : '全选', { 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(() => {
  3246. if (this.isAllSelected) {
  3247. // 全不选
  3248. this.selectedFiles = [];
  3249. } else {
  3250. // 全选
  3251. this.selectedFiles = [...this.getCurFileList()];
  3252. }
  3253. this.isAllSelected = !this.isAllSelected;
  3254. })
  3255. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  3256. .width(72)
  3257. .height(45)
  3258. .fontSize(10)
  3259. .margin({ top: 10, bottom: 10, right: 6 })
  3260. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3261. .backgroundColor(this.themeColor)
  3262. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  3263. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3264. })
  3265. .onClick(() => {
  3266. // if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  3267. this.isOneKeyTags = !this.isOneKeyTags
  3268. // }else{
  3269. // ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限批量内嵌标签,导入的时候请勾选复制一份。')
  3270. // }
  3271. })
  3272. Button('合并', { type: ButtonType.Circle, stateEffect: true })
  3273. .width(45)
  3274. .height(45)
  3275. .fontSize(10)
  3276. .margin({ top: 10, bottom: 10, right: 6 })
  3277. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3278. .backgroundColor(this.themeColor)
  3279. .bindContentCover($$this.isMergeAudio, this.MergeAudioBuilder(), {
  3280. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3281. })
  3282. .onClick(() => {
  3283. if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  3284. this.isMergeAudio = !this.isMergeAudio
  3285. }else{
  3286. ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限合并')
  3287. }
  3288. })
  3289. Button('+歌单', { type: ButtonType.Circle, stateEffect: true })
  3290. .width(45)
  3291. .height(45)
  3292. .fontSize(10)
  3293. .margin({ top: 10, bottom: 10, right: 6 })
  3294. .backgroundColor(this.themeColor)
  3295. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3296. .onClick(async () => {
  3297. this.longItemFilePath = ''
  3298. await this.openAddToPlaylistDialog(this.selectedFiles)
  3299. })
  3300. // Button('乱码', { type: ButtonType.Circle, stateEffect: true })
  3301. // .width(45)
  3302. // .height(45)
  3303. // .fontSize(10)
  3304. // .margin({ top: 10, bottom: 10, right: 6 })
  3305. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3306. // .backgroundColor(this.themeColor)
  3307. // .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  3308. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3309. // })
  3310. // .onClick(() => {
  3311. // this.isFixMessy = !this.isFixMessy
  3312. // })
  3313. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  3314. // .width('35%')
  3315. // .height(60)
  3316. // .id('music_cut')
  3317. // .margin({ top: 10, bottom: 10, right: 6 })
  3318. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3319. // .backgroundColor(this.themeColor)
  3320. // .onClick(() => {
  3321. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  3322. // })
  3323. //
  3324. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  3325. // .width('35%')
  3326. // .height(60)
  3327. // .id('music_cut_current')
  3328. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  3329. // .margin({ top: 10, bottom: 10, right: 6 })
  3330. // .backgroundColor(this.themeColor)
  3331. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3332. // .onClick(() => {
  3333. //
  3334. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  3335. // })
  3336. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  3337. // .width('35%')
  3338. // .height(60)
  3339. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  3340. // .margin({ top: 10, bottom: 10, right: 6 })
  3341. // .backgroundColor(this.themeColor)
  3342. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3343. // .onClick(() => {
  3344. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  3345. // })
  3346. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  3347. .width(45)
  3348. .height(45)
  3349. .fontSize(10)
  3350. .margin({ top: 10, bottom: 10, right: 6 })
  3351. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  3352. .backgroundColor(this.themeColor)
  3353. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3354. .onClick(() => {
  3355. this.showWarnIsDelete()
  3356. })
  3357. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  3358. .width(45)
  3359. .height(45)
  3360. .fontSize(10)
  3361. .margin({ top: 10, bottom: 10, right: 6 })
  3362. .backgroundColor(this.themeColor)
  3363. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3364. .onClick(() => {
  3365. this.selectedFiles = [];
  3366. this.isAllSelected = false
  3367. this.isMultiSelect = false
  3368. })
  3369. }
  3370. .width('100%')
  3371. .justifyContent(FlexAlign.Center)
  3372. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  3373. .opacity(this.isMultiSelect ? 1 : 0)
  3374. .animation({
  3375. duration: 666,
  3376. curve: 'ease-in-out' // 可选动画曲线
  3377. })
  3378. .position({ bottom: 20 }) // 将 Row 固定在底部
  3379. }
  3380. .width('100%')
  3381. .height('100%')
  3382. .alignContent(Alignment.Top)
  3383. }
  3384. .width('100%')
  3385. .height('100%')
  3386. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  3387. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  3388. .backgroundImagePosition(Alignment.Center)
  3389. .backdropBlur(this.blurValue)
  3390. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  3391. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  3392. }
  3393. }
  3394. //字母表索引
  3395. @Builder
  3396. indexBuilder(){
  3397. if(this.enableShowAlphabet){
  3398. Column({space: 5}){
  3399. if(this.isShowAlphaBet&&!(this.modeType==2&&!this.isCanBack)
  3400. &&!(this.modeType==3&&!this.isCanBack)){
  3401. AlphabetIndexer({arrayValue: this.alphaBet,selected: this.selectAlphaBetIndex})
  3402. .attributeModifier(this.alphaBetStyle)
  3403. .usingPopup(this.isTouchingAlphaBet)
  3404. .onAreaChange((old_value,new_value)=>{
  3405. this.alphabetHeight = new_value.height as number
  3406. })
  3407. .popupPosition({
  3408. x: 40,
  3409. y: this.alphabetHeight / 2
  3410. })
  3411. .onSelect((index: number) => {
  3412. this.onSelectIndexItem(this.alphaBet[index])
  3413. })
  3414. .onTouch((event: TouchEvent) =>{
  3415. this.isShowAlphaBet = true
  3416. if(event.type === TouchType.Up || event.type === TouchType.Cancel){
  3417. this.isTouchingAlphaBet = false
  3418. }else{
  3419. this.isTouchingAlphaBet = true
  3420. }
  3421. })
  3422. .transition(
  3423. TransitionEffect.translate({x: 10})
  3424. .combine(TransitionEffect.opacity(0.1))
  3425. .animation({
  3426. duration: 150,
  3427. curve: Curve.EaseInOut,
  3428. })
  3429. )
  3430. }else{
  3431. Blank()
  3432. .layoutWeight(1)
  3433. }
  3434. // ListLocateButton()
  3435. // .onClick(() =>{
  3436. // this.locateSong()
  3437. // })
  3438. // .clickEffect({level:ClickEffectLevel.LIGHT,scale: 0.5})
  3439. // .margin({
  3440. // bottom: 10
  3441. // })
  3442. }
  3443. .padding({
  3444. bottom: 0
  3445. })
  3446. .position({x:'92%'})
  3447. .height('100%')
  3448. .justifyContent(FlexAlign.Center)
  3449. }
  3450. }
  3451. onSelectIndexItem(letter: string) {
  3452. let songs = this.videoLocalList
  3453. let targetIndex = -1;
  3454. for (let i = 0; i < songs.length; i++) {
  3455. let song = songs[i]
  3456. let text = this.isShowFileName?song.fileName:
  3457. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  3458. if(this.sortType === 0||this.sortType==1){
  3459. text = song.artist
  3460. }else if(this.sortType === 2||this.sortType==3){
  3461. text = song.album
  3462. }
  3463. if(text){
  3464. let firstPinyin = getFirstLetter(text)
  3465. if (firstPinyin&&firstPinyin === letter) {
  3466. targetIndex = i;
  3467. break;
  3468. }
  3469. }
  3470. }
  3471. if (targetIndex !== -1) {
  3472. this.listScroller.scrollToIndex(targetIndex);
  3473. }
  3474. }
  3475. // 找到对应字母表的索引
  3476. findAlphaBetIndex(song: VideoItem):number{
  3477. let text = this.isShowFileName?song.fileName:
  3478. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  3479. if(this.sortType === 0||this.sortType==1){
  3480. text = song.artist
  3481. }else if(this.sortType === 2||this.sortType==3){
  3482. text = song.album
  3483. }
  3484. if(text){
  3485. let firstLetter = getFirstLetter(text)
  3486. for(let i=0;i<this.alphaBet.length;i++){
  3487. if(this.alphaBet[i] === firstLetter){
  3488. return i
  3489. }
  3490. }
  3491. }
  3492. return 0
  3493. }
  3494. async setAlphaBet(){
  3495. if(!this.showZMIndex){
  3496. return
  3497. }
  3498. return new Promise<void>((resolve,reject) => {
  3499. try {
  3500. let songs = this.videoLocalList
  3501. if(songs.length > 40000){
  3502. this.alphaBet = []
  3503. resolve()
  3504. return
  3505. }
  3506. let alphabetSet = new Set<string>();
  3507. for (let song of songs) {
  3508. let text = this.isShowFileName?song.fileName:
  3509. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  3510. if(this.sortType === 0||this.sortType==1){
  3511. text = song.artist
  3512. }else if(this.sortType === 2||this.sortType==3){
  3513. text = song.album
  3514. }
  3515. if(text){
  3516. let firstPinyin = getFirstLetter(text)
  3517. if(!alphabetSet.has(firstPinyin)){
  3518. alphabetSet.add(firstPinyin)
  3519. }
  3520. }
  3521. // const pyStr = song.pyStr
  3522. // if(pyStr){
  3523. // if(!alphabetSet.has(pyStr)){
  3524. // alphabetSet.add(pyStr)
  3525. // }
  3526. // }
  3527. }
  3528. this.alphaBet = Array.from(alphabetSet).sort((a,b)=>{
  3529. if(this.sortType ===4||this.sortType==0||this.sortType==2||this.sortType==6){
  3530. return a.localeCompare(b)
  3531. }else{
  3532. return b.localeCompare(a)
  3533. }
  3534. })
  3535. if(this.videoLocalList.length > 0){
  3536. this.listScroller.scrollToIndex(0)
  3537. this.selectAlphaBetIndex = 0
  3538. }
  3539. resolve()
  3540. }catch (e) {
  3541. console.error('testTag','排序字母表出错',JSON.stringify(e))
  3542. resolve()
  3543. }
  3544. })
  3545. }
  3546. @Builder
  3547. topTitleBar(){
  3548. Column() {
  3549. Row({ space: 15 }) {
  3550. if (!this.isSearchMode ) {
  3551. //左侧滑动按钮
  3552. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3553. SymbolGlyph(this.rightTopImage)
  3554. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3555. }
  3556. .attributeModifier(new ButtonFancyModifier(40, 40))
  3557. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3558. .animation({ duration: 300, curve: Curve.Ease })
  3559. .onClick(() => {
  3560. this.doSwipBack()
  3561. })
  3562. .attributeModifier(new ShadowModifier())
  3563. .zIndex(0)
  3564. }else{
  3565. //左侧搜索返回按钮
  3566. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3567. SymbolGlyph($r('sys.symbol.chevron_left'))
  3568. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3569. }
  3570. .attributeModifier(new ButtonFancyModifier(40, 40))
  3571. .margin({bottom:5})
  3572. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3573. .animation({ duration: 300, curve: Curve.Ease })
  3574. .onClick(() => {
  3575. this.isSearchMode = false
  3576. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  3577. this.searchText = ''
  3578. this.getSortedFiles(this.currentPath)
  3579. return
  3580. }
  3581. this.onSearchInput('')
  3582. })
  3583. .attributeModifier(new ShadowModifier())
  3584. .zIndex(0)
  3585. }
  3586. if (!this.isSearchMode) {
  3587. Text(this.modeType==1?`${this.titleName}(${this.mediaKuCount}首)`:this.titleName)
  3588. .margin({left:3,right:10})
  3589. .fontColor($r('app.color.text_color'))
  3590. .fontSize(this.twoFingerType==3?17:16)
  3591. .maxLines(1)
  3592. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3593. .layoutWeight(1)
  3594. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3595. }
  3596. //搜索框
  3597. Search({ controller: this.searchController,value: this.searchText, placeholder: '搜索标题、艺术家...' })
  3598. .searchButton('搜索',{fontColor:this.themeColor})
  3599. .searchIcon({
  3600. src: $r('sys.media.ohos_ic_public_search_filled')
  3601. })
  3602. .cancelButton({
  3603. style: CancelButtonStyle.CONSTANT,
  3604. icon: {
  3605. src: $r('sys.media.ohos_ic_public_cancel_filled')
  3606. }
  3607. })
  3608. .layoutWeight(1)
  3609. .height(40)
  3610. .maxLength(20)
  3611. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  3612. .placeholderColor(Color.Grey)
  3613. .placeholderFont({ size: 14, weight: 400 })
  3614. .textFont({ size: 14, weight: 400 })
  3615. .onSubmit((value: string) => {
  3616. console.log('onecold onSubmit ='+value)
  3617. this.searchController.stopEditing()
  3618. this.onSearchInput(this.searchText);
  3619. })
  3620. .onChange((value: string) => {
  3621. console.log('onecold onChange ='+value)
  3622. this.onSearchInput(value);
  3623. })
  3624. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  3625. .animation({ duration: 300, curve: Curve.Ease })
  3626. //搜索按钮
  3627. if (!this.isSearchMode) {
  3628. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3629. SymbolGlyph($r('sys.symbol.magnifyingglass'))
  3630. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3631. }
  3632. .attributeModifier(new ButtonFancyModifier(40, 40))
  3633. .animation({ duration: 300, curve: Curve.Ease })
  3634. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3635. .attributeModifier(new ShadowModifier())
  3636. .zIndex(0)
  3637. .onClick(()=>{
  3638. this.isSearchMode = true
  3639. })
  3640. //排序按钮
  3641. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3642. SymbolGlyph($r('sys.symbol.list_number'))
  3643. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3644. }
  3645. .attributeModifier(new ButtonFancyModifier(40, 40))
  3646. .animation({ duration: 300, curve: Curve.Ease })
  3647. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3648. .bindMenu((this.modeType==2&&!this.isCanBack)||(this.modeType==3&&!this.isCanBack)
  3649. ?this.SortMenuForArtistAblumBuilder:this.SortMenuBuilder)
  3650. .attributeModifier(new ShadowModifier())
  3651. .zIndex(0)
  3652. //添加按钮
  3653. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3654. SymbolGlyph($r('sys.symbol.plus'))
  3655. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3656. }
  3657. .attributeModifier(new ButtonFancyModifier(40, 40))
  3658. .animation({ duration: 300, curve: Curve.Ease })
  3659. .visibility(this.modeType==0||this.modeType==1?Visibility.Visible:Visibility.None)
  3660. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3661. .bindSheet($$this.showAddSheet, this.addSheet(), {
  3662. height: SheetSize.FIT_CONTENT,
  3663. dragBar: true,
  3664. showClose: true,
  3665. preferType: SheetType.CENTER ,
  3666. title: {
  3667. title: '导入音乐'
  3668. }
  3669. })
  3670. .onClick(() => {
  3671. this.showAddSheet = !this.showAddSheet;
  3672. })
  3673. .attributeModifier(new ShadowModifier())
  3674. .zIndex(0)
  3675. }
  3676. }
  3677. }
  3678. .padding({ top: this.topSafeHeight+10, left: 10, right: 10 })
  3679. .width('100%')
  3680. .visibility(this.isShowTitleBar?Visibility.Visible:
  3681. this.autoHideTitle?Visibility.None:Visibility.Visible)
  3682. .animation({
  3683. duration: 500,
  3684. curve: Curve.Friction // 可选动画曲线
  3685. })
  3686. }
  3687. @Builder
  3688. addSheet() {
  3689. Scroll() {
  3690. Column() {
  3691. Column() {
  3692. Row() {
  3693. Text('导入音乐复制到DownLoad目录')
  3694. .margin({ left: 18 })
  3695. .fontSize(14)
  3696. .fontColor($r('app.color.text_color'))
  3697. .fontWeight(480)
  3698. .layoutWeight(1)
  3699. Toggle({ type: ToggleType.Switch, isOn: this.isCopyFileToDownLoad })
  3700. .selectedColor(this.themeColor)
  3701. .switchPointColor(Color.White)
  3702. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  3703. .margin({ right: 18 })
  3704. .onChange((checked: boolean) => {
  3705. this.isCopyFileToDownLoad = checked;
  3706. PreferencesUtil.put(SettingPage.IS_COPYFILE_TO_DOWNLOAD, this.isCopyFileToDownLoad)
  3707. })
  3708. .width(50)
  3709. .height(30);
  3710. }
  3711. .height(88)
  3712. }
  3713. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3714. .backgroundColor($r('app.color.start_window_background'))
  3715. .borderRadius(15)
  3716. .margin({
  3717. left: 30,
  3718. right: 30,
  3719. top: 10,
  3720. bottom: 10
  3721. })
  3722. .padding(0)
  3723. .border({
  3724. color: Color.White,
  3725. width: 1.8
  3726. })
  3727. Menu() {
  3728. MenuItem({
  3729. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder_badge_plus')),
  3730. content: "新建文件夹"
  3731. })
  3732. .backgroundColor($r('app.color.silvery'))
  3733. .border({
  3734. width: { bottom: 1 },
  3735. color: '#12ec5c87'
  3736. })
  3737. .margin(10)
  3738. .padding({left:15,right:15})
  3739. .onClick(async () => {
  3740. this.showMkDialog()
  3741. this.showAddSheet = !this.showAddSheet
  3742. })
  3743. MenuItem({
  3744. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder')),
  3745. content: $r('app.string.import_from_files')
  3746. })
  3747. .padding({left:15,right:15})
  3748. .backgroundColor($r('app.color.silvery'))
  3749. .border({
  3750. width: { bottom: 1 },
  3751. color: '#12ec5c87'
  3752. })
  3753. .margin(10)
  3754. .onClick(async () => {
  3755. this.callFilePickerSelectFile()
  3756. this.showAddSheet = !this.showAddSheet
  3757. })
  3758. MenuItem({
  3759. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square')),
  3760. content: '全选导入'
  3761. // content: '从下载文件夹导入(路径:Download/' +
  3762. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  3763. })
  3764. .padding({left:15,right:15})
  3765. .backgroundColor($r('app.color.silvery'))
  3766. .border({
  3767. width: { bottom: 1 },
  3768. color: '#12ec5c87'
  3769. })
  3770. .margin(10)
  3771. .onClick(async () => {
  3772. this.goSelectMusic()
  3773. this.showAddSheet = !this.showAddSheet
  3774. })
  3775. MenuItem({
  3776. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.save')),
  3777. content: '自动导入教程'
  3778. // content: '从下载文件夹导入(路径:Download/' +
  3779. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  3780. })
  3781. .padding({left:15,right:15})
  3782. .backgroundColor($r('app.color.silvery'))
  3783. .border({
  3784. width: { bottom: 1 },
  3785. color: '#12ec5c87'
  3786. })
  3787. .margin(10)
  3788. .onClick(async () => {
  3789. this.showTips()
  3790. this.showAddSheet = !this.showAddSheet
  3791. })
  3792. }.attributeModifier(new MenuModifier())
  3793. .margin({bottom:30})
  3794. }
  3795. .layoutWeight(1)
  3796. }
  3797. }
  3798. @Builder
  3799. TagsContentCoverBuilder() {
  3800. Scroll() {
  3801. Column() {
  3802. TagsContentCover(
  3803. {
  3804. selectedFiles:this.selectedFiles,
  3805. isOneKeyTags:this.isOneKeyTags,
  3806. onSeePath:(path:string)=>{
  3807. this.modeType = 0
  3808. this.deleteCache(path)
  3809. this.getSortedFiles(path)
  3810. },
  3811. onTagsResult:(result: boolean,deleteCache_path?:string)=>{
  3812. this.isMultiSelect = false
  3813. if(result){//如果嵌入成功,更新数据
  3814. this.listRefreshKey++
  3815. setTimeout(()=>{
  3816. this.doUpdateData()
  3817. },500)
  3818. }
  3819. console.info('onecold onTagsResult deleteCache_path =' +deleteCache_path)
  3820. if(deleteCache_path){
  3821. this.deleteCache(deleteCache_path)
  3822. }
  3823. }
  3824. }
  3825. )
  3826. }
  3827. }
  3828. .width('100%')
  3829. .height('100%')
  3830. }
  3831. @Builder
  3832. FixMessyViewBuilder() {
  3833. Scroll() {
  3834. Column() {
  3835. FixMessyView(
  3836. {
  3837. selectedFiles:this.selectedFiles,
  3838. isFixMessy:this.isFixMessy,
  3839. onFixResult:(result: boolean)=>{
  3840. this.isMultiSelect = false
  3841. if(result){//如果嵌入成功,更新数据
  3842. this.deleteCache(this.currentPath)
  3843. this.doUpdateData()
  3844. }
  3845. }
  3846. }
  3847. )
  3848. }
  3849. }
  3850. .width('100%')
  3851. .height('100%')
  3852. }
  3853. //剪辑音频
  3854. @Builder
  3855. EditAudioBuilder(item:VideoItem) {
  3856. Scroll() {
  3857. Column() {
  3858. EditAudio(
  3859. {
  3860. mVideoItem:item,
  3861. currentPath:this.currentPath,
  3862. videoUrl:this.videoUrl,
  3863. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3864. currentTime:this.currentTime,
  3865. progressValue:this.progressValue,
  3866. onBack:()=>{
  3867. this.isEditAudio = !this.isEditAudio
  3868. },
  3869. onSeeOutputPath:(outPutPath:string)=>{
  3870. this.isEditAudio = !this.isEditAudio
  3871. this.longItemFilePath = ''
  3872. this.modeType = 0
  3873. this.isShowFileName = true
  3874. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3875. },
  3876. onPlayOrPause:()=>{
  3877. if(this.videoUrl==item.filePath){
  3878. this.playOrPause()
  3879. }else{//如果不是当前播放的,则播放该文件
  3880. this.videoUrl==item.filePath
  3881. this.doPlay(item,0,false,true)
  3882. }
  3883. },
  3884. onSliderChange:(value:number)=>{
  3885. if(this.videoUrl!=item.filePath){
  3886. this.videoUrl==item.filePath
  3887. return
  3888. }
  3889. this.isSeekTo = true;
  3890. this.mDestroyPage = false;
  3891. this.showLoadIng();
  3892. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  3893. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3894. this.seekTo(seekValue + "");
  3895. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  3896. this.isSeekTo = false;
  3897. },
  3898. onResult:(result: boolean,outPath:string)=>{
  3899. if(result){//如果剪辑成功,更新数据
  3900. this.doUpdateData()
  3901. }else{
  3902. ToastUtil.showToast('剪辑失败')
  3903. }
  3904. }
  3905. }
  3906. )
  3907. }
  3908. }
  3909. .width('100%')
  3910. .height('100%')
  3911. }
  3912. //提取伴奏
  3913. @Builder
  3914. ConverterBuilder(item:VideoItem) {
  3915. Scroll() {
  3916. Column() {
  3917. AudioFormatConverter(
  3918. {
  3919. mVideoItem:item,
  3920. videoUrl:this.videoUrl,
  3921. currentPath:this.currentPath,
  3922. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3923. currentTime:this.currentTime,
  3924. progressValue:this.progressValue,
  3925. onBack:()=>{
  3926. this.isConverter = !this.isConverter
  3927. this.longItemFilePath = ''
  3928. },
  3929. onPlayOrPause:()=>{
  3930. if(this.videoUrl==item.filePath){
  3931. this.playOrPause()
  3932. }else{//如果不是当前播放的,则播放该文件
  3933. this.videoUrl==item.filePath
  3934. this.doPlay(item,0,false,true)
  3935. }
  3936. },
  3937. onSeeOutputPath:(outPutPath:string)=>{
  3938. this.isConverter = !this.isConverter
  3939. this.longItemFilePath = ''
  3940. this.modeType = 0
  3941. this.isShowFileName = true
  3942. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3943. },
  3944. onSliderChange:(value:number)=>{
  3945. if(this.videoUrl!=item.filePath){
  3946. this.videoUrl==item.filePath
  3947. return
  3948. }
  3949. this.isSeekTo = true;
  3950. this.mDestroyPage = false;
  3951. this.showLoadIng();
  3952. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3953. this.seekTo(seekValue + "");
  3954. this.isSeekTo = false;
  3955. },
  3956. onResult:(result: boolean,outPath:string)=>{
  3957. if(result){//如果成功,更新数据
  3958. this.doUpdateData()
  3959. }else{
  3960. ToastUtil.showToast('格式转化失败')
  3961. }
  3962. }
  3963. }
  3964. )
  3965. }
  3966. }
  3967. .width('100%')
  3968. .height('100%')
  3969. }
  3970. //提取伴奏
  3971. @Builder
  3972. ExtractAccBuilder(item:VideoItem) {
  3973. Scroll() {
  3974. Column() {
  3975. ExtractAccompaniment(
  3976. {
  3977. mVideoItem:item,
  3978. currentPath:this.currentPath,
  3979. videoUrl:this.videoUrl,
  3980. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3981. currentTime:this.currentTime,
  3982. progressValue:this.progressValue,
  3983. onBack:()=>{
  3984. this.isExtractAcc = !this.isExtractAcc
  3985. this.longItemFilePath = ''
  3986. },
  3987. onPlayOrPause:()=>{
  3988. if(this.videoUrl==item.filePath){
  3989. this.playOrPause()
  3990. }else{//如果不是当前播放的,则播放该文件
  3991. this.videoUrl==item.filePath
  3992. this.doPlay(item,0,false,true)
  3993. }
  3994. },
  3995. onSeeOutputPath:(outPutPath:string)=>{
  3996. this.isExtractAcc = !this.isExtractAcc
  3997. this.longItemFilePath = ''
  3998. this.modeType = 0
  3999. this.isShowFileName = true
  4000. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4001. },
  4002. onSliderChange:(value:number)=>{
  4003. if(this.videoUrl!=item.filePath){
  4004. this.videoUrl==item.filePath
  4005. return
  4006. }
  4007. this.isSeekTo = true;
  4008. this.mDestroyPage = false;
  4009. this.showLoadIng();
  4010. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  4011. this.seekTo(seekValue + "");
  4012. this.isSeekTo = false;
  4013. },
  4014. onResult:(result: boolean,outPath:string)=>{
  4015. if(result){//如果成功,更新数据
  4016. this.doUpdateData()
  4017. }else{
  4018. ToastUtil.showToast('提取伴奏失败')
  4019. }
  4020. }
  4021. }
  4022. )
  4023. }
  4024. }
  4025. .width('100%')
  4026. .height('100%')
  4027. }
  4028. //AI人声分离
  4029. @Builder
  4030. AiBuilder(item:VideoItem) {
  4031. Scroll() {
  4032. Column() {
  4033. AIVoiceSeparation(
  4034. {
  4035. mVideoItem:item,
  4036. videoUrl:this.videoUrl,
  4037. currentPath:this.currentPath,
  4038. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4039. currentTime:this.currentTime,
  4040. progressValue:this.progressValue,
  4041. onBack:()=>{
  4042. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  4043. this.longItemFilePath = ''
  4044. },
  4045. onPlayOrPause:()=>{
  4046. if(this.videoUrl==item.filePath||this.isPlaying){
  4047. this.playOrPause()
  4048. }else{//如果不是当前播放的,则播放该文件
  4049. this.videoUrl==item.filePath
  4050. this.doPlay(item,0,false,true)
  4051. }
  4052. },
  4053. onPlayPath:(path:string)=>{
  4054. this.videoUrl==path
  4055. const itemP = Utility.getItemByFilePath(this.videoLocalList,path)
  4056. if(itemP)
  4057. this.doPlay(itemP,0,false,true)
  4058. },
  4059. onSeeOutputPath:(outPutPath:string)=>{
  4060. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  4061. this.longItemFilePath = ''
  4062. this.modeType = 0
  4063. this.isShowFileName = true
  4064. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4065. },
  4066. onSliderChange:(value:number)=>{
  4067. if(this.videoUrl!=item.filePath){
  4068. this.videoUrl==item.filePath
  4069. return
  4070. }
  4071. this.isSeekTo = true;
  4072. this.mDestroyPage = false;
  4073. this.showLoadIng();
  4074. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  4075. this.seekTo(seekValue + "");
  4076. this.isSeekTo = false;
  4077. },
  4078. onResult:(result: boolean,outPath:string)=>{
  4079. if(result){//如果成功,更新数据
  4080. this.doUpdateData()
  4081. }else{
  4082. ToastUtil.showToast('Ai人声分离失败')
  4083. }
  4084. }
  4085. }
  4086. )
  4087. }
  4088. }
  4089. .width('100%')
  4090. .height('100%')
  4091. }
  4092. //变速变调
  4093. @Builder
  4094. ChangeToneBuilder(item:VideoItem) {
  4095. Scroll() {
  4096. Column() {
  4097. ChangeTone(
  4098. {
  4099. mVideoItem:item,
  4100. currentPath:this.currentPath,
  4101. videoUrl:this.videoUrl,
  4102. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4103. currentTime:this.currentTime,
  4104. progressValue:this.progressValue,
  4105. onBack:()=>{
  4106. this.isChangeTone = !this.isChangeTone
  4107. this.longItemFilePath = ''
  4108. },
  4109. onPlayOrPause:()=>{
  4110. if(this.videoUrl==item.filePath){
  4111. this.playOrPause()
  4112. }else{//如果不是当前播放的,则播放该文件
  4113. this.videoUrl==item.filePath
  4114. this.doPlay(item,0,false,true)
  4115. }
  4116. },
  4117. onSeeOutputPath:(outPutPath:string)=>{
  4118. this.isChangeTone = !this.isChangeTone
  4119. this.longItemFilePath = ''
  4120. this.modeType = 0
  4121. this.isShowFileName = true
  4122. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4123. },
  4124. onSliderChange:(value:number)=>{
  4125. if(this.videoUrl!=item.filePath){
  4126. this.videoUrl==item.filePath
  4127. return
  4128. }
  4129. this.isSeekTo = true;
  4130. this.mDestroyPage = false;
  4131. this.showLoadIng();
  4132. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  4133. this.seekTo(seekValue + "");
  4134. this.isSeekTo = false;
  4135. },
  4136. onResult:(result: boolean,outPath:string)=>{
  4137. if(result){//如果成功,更新数据
  4138. this.doUpdateData()
  4139. }else{
  4140. ToastUtil.showToast('变速变调失败')
  4141. }
  4142. }
  4143. }
  4144. )
  4145. }
  4146. }
  4147. .width('100%')
  4148. .height('100%')
  4149. }
  4150. //提取视频中的音频
  4151. @Builder
  4152. extractAudioFromVideoBuilder(item:VideoItem) {
  4153. Scroll() {
  4154. Column() {
  4155. ExtractAudioFromVideo(
  4156. {
  4157. mVideoItem:item,
  4158. currentPath:this.currentPath,
  4159. videoUrl:this.videoUrl,
  4160. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4161. currentTime:this.currentTime,
  4162. progressValue:this.progressValue,
  4163. onBack:()=>{
  4164. this.isExtractAudio = !this.isExtractAudio
  4165. this.longItemFilePath = ''
  4166. },
  4167. onPlayOrPause:()=>{
  4168. if(this.videoUrl==item.filePath){
  4169. this.playOrPause()
  4170. }else{//如果不是当前播放的,则播放该文件
  4171. this.videoUrl==item.filePath
  4172. this.doPlay(item,0,false,true)
  4173. }
  4174. },
  4175. onSeeOutputPath:(outPutPath:string)=>{
  4176. this.isExtractAudio = !this.isExtractAudio
  4177. this.longItemFilePath = ''
  4178. this.modeType = 0
  4179. this.isShowFileName = true
  4180. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4181. },
  4182. onSliderChange:(value:number)=>{
  4183. if(this.videoUrl!=item.filePath){
  4184. this.videoUrl==item.filePath
  4185. return
  4186. }
  4187. this.isSeekTo = true;
  4188. this.mDestroyPage = false;
  4189. this.showLoadIng();
  4190. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  4191. this.seekTo(seekValue + "");
  4192. this.isSeekTo = false;
  4193. },
  4194. onResult:(result: boolean,outPath:string)=>{
  4195. if(result){//如果成功,更新数据
  4196. this.doUpdateData()
  4197. }else{
  4198. ToastUtil.showToast('提取音频失败')
  4199. }
  4200. }
  4201. }
  4202. )
  4203. }
  4204. }
  4205. .width('100%')
  4206. .height('100%')
  4207. }
  4208. //合并音频
  4209. @Builder
  4210. MergeAudioBuilder() {
  4211. Scroll() {
  4212. Column() {
  4213. MergeAudio(
  4214. {
  4215. videoUrl:this.videoUrl,
  4216. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4217. currentPath:this.currentPath,
  4218. selectedFiles:this.selectedFiles,
  4219. currentTime:this.currentTime,
  4220. progressValue:this.progressValue,
  4221. onBack:()=>{
  4222. this.isMergeAudio = !this.isMergeAudio
  4223. this.longItemFilePath = ''
  4224. },
  4225. // onPlayPath:(path:string)=>{
  4226. // if(this.videoUrl==item.filePath){
  4227. // this.playOrPause()
  4228. // }else{//如果不是当前播放的,则播放该文件
  4229. // this.videoUrl==item.filePath
  4230. // this.doPlay(item,0,false,true)
  4231. // }
  4232. //
  4233. // },
  4234. onSeeOutputPath:(outPutPath:string)=>{
  4235. this.isMergeAudio = !this.isMergeAudio
  4236. this.longItemFilePath = ''
  4237. this.modeType = 0
  4238. this.isShowFileName = true
  4239. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4240. },
  4241. onResult:(result: boolean,outPath:string)=>{
  4242. if(result){//如果成功,更新数据
  4243. this.doUpdateData()
  4244. }else{
  4245. if(this.selectedFiles.length>=3){
  4246. ToastUtil.showToast('合并数量太多导致失败')
  4247. }else{
  4248. ToastUtil.showToast('合并失败')
  4249. }
  4250. }
  4251. }
  4252. }
  4253. )
  4254. }
  4255. }
  4256. .width('100%')
  4257. .height('100%')
  4258. }
  4259. asyncCurrentPathData() {
  4260. if (this.modeType == 0) {
  4261. workerInstance.postMessage({
  4262. code: 1,
  4263. data1: this.context,
  4264. data2: this.currentPath,
  4265. data3: this.lockPath,
  4266. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  4267. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  4268. });
  4269. }
  4270. }
  4271. // 处理文件选择的函数
  4272. handleFileSelection(item: VideoItem, checked: boolean) {
  4273. if (checked) {
  4274. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  4275. this.selectedFiles.push(item);
  4276. }
  4277. } else {
  4278. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  4279. if (index > -1) {
  4280. this.selectedFiles.splice(index, 1);
  4281. }
  4282. }
  4283. }
  4284. private deleteComponentId: number = 0
  4285. //多选删除文件
  4286. showWarnIsDelete(){
  4287. this.getUIContext().getPromptAction().openCustomDialog({
  4288. builder: () => {
  4289. this.deleteComptentBuilder()
  4290. },
  4291. isModal:true,
  4292. showInSubWindow:false,
  4293. maskColor: Color.Transparent,
  4294. dialogTransition: // 设置弹窗内容显示的过渡效果
  4295. TransitionEffect.translate({ x: 0, y: 290, z: 0 })
  4296. .animation({ duration: 600, curve: Curve.Smooth }),
  4297. maskTransition: // 设置蒙层显示的过渡效果
  4298. TransitionEffect.opacity(0)
  4299. .animation({ duration: 600, curve: Curve.Smooth })
  4300. }).then((dialogId: number) => {
  4301. this.deleteComponentId = dialogId
  4302. })
  4303. .catch((error: BusinessError) => {
  4304. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  4305. })
  4306. }
  4307. @Builder
  4308. deleteComptentBuilder(){
  4309. DeleteComptent({
  4310. selectedFiles:this.selectedFiles,
  4311. onCancel:()=>{
  4312. this.isMultiSelect = false
  4313. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  4314. },
  4315. onDeleteResult:(result: boolean)=>{
  4316. this.isMultiSelect = false
  4317. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  4318. if(result){//如果删除成功,更新数据
  4319. this.selectedFiles = [];
  4320. this.isAllSelected = false
  4321. this.cache.delete(this.currentPath);
  4322. this.getSortedFiles(this.currentPath, true);
  4323. }
  4324. }
  4325. })
  4326. }
  4327. //多选移动文件
  4328. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  4329. Logger.info('onecold showCutDialogForMultipleFiles')
  4330. let mList: Array<string> = []
  4331. let rPath = this.rootPath
  4332. if (isCurrent) {
  4333. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  4334. rPath = this.currentPath
  4335. } else {
  4336. mList = Utility.getNameList(this.dirList);
  4337. rPath = this.rootPath
  4338. }
  4339. let dataBean = new BubbleBean();
  4340. dataBean.data = mList;
  4341. dataBean.color = this.themeColor
  4342. dataBean.onItemClick = (i) => {
  4343. const newDirPath = rPath + '/' + mList[i];
  4344. // Logger.info('newDirPath = ' + newDirPath)
  4345. this.selectedFiles.forEach((item) => {
  4346. const newPath = newDirPath + '/' + item.fileName;
  4347. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  4348. ToastUtil.showToast('移动成功');
  4349. this.table.deleteData(item, () => {
  4350. this.cache.delete(this.currentPath); // 删除原路径缓存
  4351. this.cache.delete(newDirPath); // 删除目标路径缓存
  4352. this.getSortedFiles(this.currentPath, true);
  4353. });
  4354. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  4355. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  4356. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  4357. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  4358. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  4359. this.table.insert(newItem, (id: number) => {
  4360. //加入数据库
  4361. });
  4362. }
  4363. }).catch((error: Error) => {
  4364. console.error(error.message);
  4365. });
  4366. });
  4367. this.isMultiSelect = false
  4368. this.selectedFiles = [];
  4369. this.isAllSelected = false
  4370. XPopup.dismissTop();
  4371. };
  4372. let pup: XPopup
  4373. if (this.isDarkMode) {
  4374. pup = XPopup.Builder()
  4375. .setPopupPosition(PopupPosition.TOP)
  4376. .atView(viewId)
  4377. .setBackgroundColor(Color.Black)
  4378. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4379. .show();
  4380. } else {
  4381. pup = XPopup.Builder()
  4382. .setPopupPosition(PopupPosition.TOP)
  4383. .atView(viewId)
  4384. .setBackgroundColor(Color.White)
  4385. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4386. .show();
  4387. }
  4388. }
  4389. /**
  4390. * 加载所有歌单
  4391. */
  4392. async loadAllPlaylists() {
  4393. try {
  4394. this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
  4395. LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
  4396. } catch (error) {
  4397. LogUtil.error('heaunp Failed to load playlists: ' + error.message)
  4398. }
  4399. }
  4400. /**
  4401. * 显示添加到歌单对话框
  4402. */
  4403. async openAddToPlaylistDialog(items: VideoItem | VideoItem[]) {
  4404. const songs = Array.isArray(items) ? items : [items]
  4405. const musicItems = songs.filter(song => song.type !== CommonConstants.TYPE_IS_DIR)
  4406. if (musicItems.length === 0) {
  4407. ToastUtil.showToast('请选择要添加的歌曲')
  4408. return
  4409. }
  4410. // 加载最新的歌单列表
  4411. await this.loadAllPlaylists()
  4412. showAddToPlaylistDialog(
  4413. musicItems,
  4414. this.allPlaylists,
  4415. async (playlistId: string) => {
  4416. // 添加歌曲到歌单
  4417. const success = await this.playlistTable?.addSongsToPlaylist(playlistId,
  4418. musicItems.map(song => song.filePath))
  4419. if (success) {
  4420. const count = musicItems.length
  4421. ToastUtil.showToast(count > 1 ? `已添加 ${count} 首歌曲` : '已添加到歌单')
  4422. // 重新加载歌单列表
  4423. await this.loadAllPlaylists()
  4424. } else {
  4425. ToastUtil.showToast(musicItems.length > 1 ? '选中的歌曲已在该歌单中' : '歌曲已在该歌单中')
  4426. }
  4427. this.longItemFilePath = ''
  4428. if (this.isMultiSelect) {
  4429. this.isMultiSelect = false
  4430. this.isAllSelected = false
  4431. this.selectedFiles = []
  4432. }
  4433. },
  4434. () => {
  4435. LogUtil.info('取消添加到歌单')
  4436. },
  4437. () => {
  4438. // 创建新歌单
  4439. showCreatePlaylistDialog(
  4440. async (name: string, description: string, coverPath?: string) => {
  4441. const success = await this.playlistTable?.createPlaylist(name, description, coverPath)
  4442. if (success) {
  4443. ToastUtil.showToast('歌单创建成功')
  4444. // 重新加载歌单列表并打开添加对话框
  4445. await this.loadAllPlaylists()
  4446. await this.openAddToPlaylistDialog(musicItems)
  4447. } else {
  4448. ToastUtil.showToast('歌单创建失败')
  4449. }
  4450. },
  4451. () => {
  4452. // 取消创建歌单
  4453. }
  4454. )
  4455. }
  4456. )
  4457. }
  4458. doFav(item: VideoItem) {
  4459. LogUtil.info('onecold doFav isFav=' + item.isFav)
  4460. let isFav = 0
  4461. if (Utility.getIsFav(this.favList, item)) {
  4462. isFav = 0
  4463. } else {
  4464. isFav = 1
  4465. }
  4466. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  4467. if (result) {
  4468. if (isFav === 1) {
  4469. ToastUtil.showToast('收藏成功');
  4470. } else {
  4471. ToastUtil.showToast('取消收藏成功');
  4472. }
  4473. this.deleteCache(this.currentPath)
  4474. this.getFavList(false)
  4475. if (this.modeType === 0 && !this.isFavMusic) {
  4476. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  4477. this.getSortedFiles(this.currentPath)
  4478. }
  4479. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  4480. workerInstance.postMessage({ code: 3, data: this.context });
  4481. workerInstance.postMessage({ code: 4, data: this.context });
  4482. }
  4483. })
  4484. }
  4485. //多选复制文件
  4486. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  4487. console.log('onecold showCopyDialogForMultipleFiles');
  4488. let mList: Array<string> = []
  4489. let rPath = this.rootPath
  4490. if (isCurrent) {
  4491. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  4492. rPath = this.currentPath
  4493. } else {
  4494. mList = Utility.getNameList(this.dirList);
  4495. rPath = this.rootPath
  4496. }
  4497. let dataBean = new BubbleBean();
  4498. dataBean.data = mList;
  4499. dataBean.isCopy = true
  4500. dataBean.color = this.themeColor
  4501. dataBean.onItemClick = (i) => {
  4502. const newDirPath = rPath + '/' + mList[i];
  4503. // Logger.info('newDirPath = ' + newDirPath)
  4504. this.selectedFiles.forEach((item) => {
  4505. const newPath = newDirPath + '/' + item.fileName;
  4506. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  4507. ToastUtil.showToast('复制成功');
  4508. this.cache.delete(newDirPath); // 删除目标路径缓存
  4509. this.getSortedFiles(this.currentPath);
  4510. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  4511. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  4512. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  4513. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  4514. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  4515. this.table.insert(newItem, (id: number) => {
  4516. //加入数据库
  4517. });
  4518. }
  4519. }).catch((error: Error) => {
  4520. console.error(error.message);
  4521. });
  4522. });
  4523. this.isMultiSelect = false
  4524. this.selectedFiles = [];
  4525. this.isAllSelected = false
  4526. XPopup.dismissTop();
  4527. };
  4528. let pup: XPopup
  4529. if (this.isDarkMode) {
  4530. pup = XPopup.Builder()
  4531. .setPopupPosition(PopupPosition.TOP)
  4532. .atView(viewId)
  4533. .setBackgroundColor(Color.Black)
  4534. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4535. .show();
  4536. } else {
  4537. pup = XPopup.Builder()
  4538. .setPopupPosition(PopupPosition.TOP)
  4539. .atView(viewId)
  4540. .setBackgroundColor(Color.White)
  4541. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4542. .show();
  4543. }
  4544. }
  4545. @Builder
  4546. private DirItem(item: VideoItem, index?: number) {
  4547. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  4548. Row() {
  4549. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  4550. $r('app.media.music_group'))
  4551. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4552. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4553. .fillColor(this.themeColor)// .fontSize(33)
  4554. .alt($r('app.media.music_group'))
  4555. .borderRadius(this.isCoverRectangle?9:'100%')
  4556. .clip(true)
  4557. .shadow({
  4558. radius: 2,
  4559. type: ShadowType.BLUR,
  4560. color: 'on_primary'
  4561. })
  4562. .sourceSize({width:38, height:38})
  4563. .margin({ left: 20, top: 8, bottom: 8 })
  4564. Column() {
  4565. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4566. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4567. .maxLines(1)// .width('88%')
  4568. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4569. .animation({
  4570. duration: 555,
  4571. curve: 'ease-in-out',
  4572. })
  4573. .transition({
  4574. type: TransitionType.Insert,
  4575. opacity: 0,
  4576. translate: { x: 160 }
  4577. })
  4578. .margin({ left: 10, right: 20 })
  4579. .fontColor($r('app.color.text_color'))
  4580. Row() {
  4581. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  4582. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4583. .padding({ top: 8 })
  4584. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  4585. .fontColor($r('app.color.text_color'))
  4586. .margin({ left: 10 })
  4587. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  4588. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4589. .padding({ top: 8 })
  4590. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  4591. .fontColor($r('app.color.text_color'))
  4592. .margin({ left: 10 })
  4593. Blank()
  4594. }
  4595. }
  4596. .height('100%')
  4597. .layoutWeight(1)
  4598. .justifyContent(FlexAlign.Center)
  4599. .alignItems(HorizontalAlign.Start)
  4600. Blank()
  4601. Image($r('app.media.arrow_right'))
  4602. .height(25)
  4603. .alignSelf(ItemAlign.Center)
  4604. .id(item.filePath)
  4605. .visibility(this.isShowAlphaBet?Visibility.None:Visibility.Visible)
  4606. .animation({ duration: 300, curve: Curve.Ease })
  4607. }
  4608. }
  4609. .backgroundColor(Color.Transparent)
  4610. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  4611. .width('98%')
  4612. .reuseId('dir_item')
  4613. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  4614. .opacity(this.opacityItem) // 绑定透明度
  4615. }
  4616. isShowDir(dirName: string) {
  4617. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  4618. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  4619. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  4620. if (dirName === undefined) {
  4621. return true
  4622. }
  4623. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  4624. return this.isShowSimi
  4625. }
  4626. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  4627. return this.isShowFAV
  4628. }
  4629. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  4630. return this.isShowHistory
  4631. }
  4632. return true
  4633. }
  4634. @State opacityItem: number = 1; // 控制透明度的状态变量
  4635. @Builder
  4636. private MusicItem(item: VideoItem, index?: number) {
  4637. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  4638. Row() {
  4639. Stack() {
  4640. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  4641. .fillColor(this.themeColor)
  4642. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4643. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4644. .alt($r('app.media.alt'))
  4645. .borderRadius(this.isCoverRectangle?9:'100%')
  4646. .clip(true)
  4647. .draggable(false)
  4648. .sourceSize({width:38, height:38})
  4649. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4650. // .autoResize(true) // 重采样,可减少内存占用
  4651. .opacity(this.opacityItem)// 绑定透明度
  4652. .margin({ left: 20 })
  4653. .shadow({
  4654. radius: StrUtil.isEmpty(item.pixelMapPath) ?6:14,
  4655. type: ShadowType.BLUR,
  4656. color: 'on_primary'
  4657. })
  4658. .gesture(LongPressGesture()
  4659. .onAction(async () => {
  4660. //如果是专辑和艺术家的首页,不能长按
  4661. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4662. return
  4663. //如果是我的收藏 最近播放等也不能长按
  4664. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4665. item.name === LocalMusic.STR_HISTORY_MUSIC
  4666. )
  4667. return
  4668. this.longItemFilePath = item.filePath
  4669. this.tempLyricContent = await this.getLyricContent(item)
  4670. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4671. })
  4672. .onActionEnd((event: GestureEvent) => {
  4673. }))
  4674. .onClick(()=>{
  4675. if (this.isMultiSelect) {
  4676. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4677. this.handleFileSelection(item, !isChecked);
  4678. } else {
  4679. this.doPlay(item,index)
  4680. this.setShowPlayTrue()
  4681. }
  4682. })
  4683. }
  4684. Column() {
  4685. Column() {
  4686. Text(this.isShowFileName?item.fileName :item.name)
  4687. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4688. .maxLines(1)
  4689. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4690. .animation({
  4691. duration: 555,
  4692. curve: 'Linear',
  4693. })
  4694. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4695. $r('app.color.text_color'))
  4696. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4697. .padding({right:25})
  4698. .bindPopup(this.longItemFilePath === item.filePath, {
  4699. builder: this.MenuBuilder(item,index,item.filePath),
  4700. placement: Placement.Top,
  4701. // autoCancel: true,
  4702. mask: {color:'#33000000'},
  4703. // popupColor: Color.Yellow,
  4704. enableArrow: false,//是否显示箭头
  4705. showInSubWindow: false,
  4706. onStateChange: (e) => {
  4707. if (!e.isVisible) {
  4708. this.longItemFilePath = ''
  4709. this.tempLyricContent = ''
  4710. }
  4711. }
  4712. })
  4713. .gesture(LongPressGesture()
  4714. .onAction(async () => {
  4715. //如果是专辑和艺术家的首页,不能长按
  4716. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4717. return
  4718. //如果是我的收藏 最近播放等也不能长按
  4719. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4720. item.name === LocalMusic.STR_HISTORY_MUSIC
  4721. )
  4722. return
  4723. this.longItemFilePath = item.filePath
  4724. this.tempLyricContent = await this.getLyricContent(item)
  4725. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4726. })
  4727. .onActionEnd((event: GestureEvent) => {
  4728. })
  4729. )
  4730. Row() {
  4731. Column(){
  4732. Text(item.md5Str?.includes('Lossless')?
  4733. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4734. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  4735. .padding({ top: 3,right:6,left:6,bottom:3 })
  4736. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4737. $r('app.color.text_color'))
  4738. .fontWeight(500)
  4739. .borderRadius(12)
  4740. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  4741. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4742. .backgroundColor('#FFC107')
  4743. }
  4744. .padding({ top: 8 })
  4745. Text(StrUtil.isEmpty(item.artist) ? item.duration
  4746. :this.twoFingerType==2? item.artist +' ' + item.duration
  4747. : item.artist + ' ' + item?.duration)
  4748. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4749. .padding({ top: 8 ,right:25})
  4750. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  4751. .maxLines(1)
  4752. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4753. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4754. Color.Gray)
  4755. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4756. Blank()
  4757. Text(this.isShowFileName?item.duration:item.size)
  4758. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4759. .padding({ top: 8 })
  4760. .maxLines(1)
  4761. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  4762. ? Visibility.Visible : Visibility.None)
  4763. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4764. Color.Gray)
  4765. .margin({ left: StrUtil.isEmpty(item.artist) ?0:10 })
  4766. }
  4767. .gesture(LongPressGesture()
  4768. .onAction(async () => {
  4769. //如果是专辑和艺术家的首页,不能长按
  4770. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4771. return
  4772. //如果是我的收藏 最近播放等也不能长按
  4773. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4774. item.name === LocalMusic.STR_HISTORY_MUSIC
  4775. )
  4776. return
  4777. this.longItemFilePath = item.filePath
  4778. this.tempLyricContent = await this.getLyricContent(item)
  4779. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4780. })
  4781. .onActionEnd((event: GestureEvent) => {
  4782. })
  4783. )
  4784. }
  4785. .height('100%')
  4786. .width('100%')
  4787. .margin({ right: 10 })
  4788. .justifyContent(FlexAlign.Center)
  4789. .alignItems(HorizontalAlign.Start)
  4790. }
  4791. .height('100%')
  4792. .margin({ left: 5 })
  4793. .layoutWeight(1)
  4794. Column() {
  4795. Checkbox({ name: 'checkbox' + index })
  4796. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  4797. .selectedColor(this.themeColor)
  4798. .shape(CheckBoxShape.CIRCLE)
  4799. .opacity(this.isMultiSelect ? 1 : 0)
  4800. .animation({
  4801. duration: 666,
  4802. curve: 'Smooth' // 可选动画曲线
  4803. })
  4804. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  4805. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  4806. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  4807. .width(22)
  4808. .height(22)
  4809. ImageAnimator()
  4810. .images(this.imagesF)// 动画数组
  4811. .duration(1000)// 持续
  4812. .state(this.animationState)// 动画状态
  4813. .fillMode(FillMode.Forwards)
  4814. .width(18)
  4815. .margin({ right: 20, top: 8, bottom: 8 })
  4816. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  4817. Visibility.None)
  4818. .height(18)
  4819. .iterations(-1) // 播放次数
  4820. }
  4821. }
  4822. }
  4823. .backgroundColor(Color.Transparent)
  4824. .width('100%')
  4825. .reuseId('file_item')
  4826. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  4827. }
  4828. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  4829. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  4830. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  4831. direction: Direction.Ltr,
  4832. buttonPadding:{top:12,bottom:12},
  4833. backgroundColor: Color.Transparent,
  4834. fontSize:14,
  4835. selectedFontSize:15,
  4836. selectedFontColor:Color.White,
  4837. selectedBackgroundColor: this.themeColor,
  4838. localizedTextPadding: {
  4839. end: LengthMetrics.vp(20),
  4840. start: LengthMetrics.vp(20)
  4841. }
  4842. })
  4843. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  4844. //当胶囊按钮的选择发生变化时调用此函数
  4845. capsuleSelectedIndexesChanged() {
  4846. this.modeType = this.tabSelectedIndexes[0]
  4847. }
  4848. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  4849. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  4850. isShowCoverHeader() {
  4851. if (!this.isShowHeader) {
  4852. return false
  4853. }
  4854. if (this.modeType == 0) {
  4855. if (this.isHistory || this.isFavMusic) {
  4856. return true
  4857. }
  4858. if (this.currentPath != this.rootPath) {
  4859. return true
  4860. }
  4861. }
  4862. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  4863. }
  4864. getCoverTitleBg(): ResourceStr | image.PixelMap {
  4865. if (this.isCustomizeBg) {
  4866. return ('rgba(255,255,255,0.2)')
  4867. }
  4868. if (this.isDarkMode) {
  4869. return $r('app.color.user_center_card_background')
  4870. }
  4871. return this.currentTitleCover
  4872. }
  4873. // 第二步:popup构造器定义弹框内容
  4874. @Builder popupBuilder() {
  4875. Column({ space: 2 }) {
  4876. Text('友情提示:双指缩放可以放大缩小列表')
  4877. .fontSize(12)
  4878. .fontWeight(FontWeight.Regular)
  4879. .fontColor($r('app.color.text_color'))
  4880. }
  4881. .justifyContent(FlexAlign.SpaceAround)
  4882. .width(220)
  4883. .height(55)
  4884. .padding(15)
  4885. }
  4886. //搜索功能的实现
  4887. @State searchText: string = ''; // 用户输入内容
  4888. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  4889. @State isSearchMode: boolean = false
  4890. // 实时搜索逻辑(带防抖)
  4891. private onSearchInput(value: string) {
  4892. this.searchText = value.trim();
  4893. let mSearchList: Array<VideoItem> = []
  4894. switch (this.modeType) {
  4895. case 0:
  4896. case 1:
  4897. mSearchList = this.mediaKuList
  4898. break;
  4899. case 2:
  4900. mSearchList = this.artistList
  4901. break;
  4902. case 3:
  4903. mSearchList = this.albumList
  4904. break;
  4905. default :
  4906. mSearchList = this.videoLocalList
  4907. break;
  4908. }
  4909. // 新增条件判断:空输入时显示所有数据
  4910. if (this.searchText === '') {
  4911. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  4912. } else {
  4913. this.filteredList = mSearchList.filter((item: VideoItem) => {
  4914. //支持模糊匹配和艺术家 专辑匹配
  4915. const regex = new RegExp(this.searchText.toLowerCase().replace(/\s+/g, '.*'), 'i');
  4916. return regex.test(item.name.toLowerCase())||
  4917. regex.test(item.fileName?.toLowerCase() ?? "") ||
  4918. regex.test(item.artist?.toLowerCase() ?? "") ||
  4919. regex.test(item.album?.toLowerCase() ?? "")
  4920. });
  4921. }
  4922. this.updateListData(this.filteredList);
  4923. // this.isSearchMode = false; // 根据业务需求决定是否启用
  4924. }
  4925. @State dragItem: number = -1
  4926. @State scaleItem: number = -1
  4927. @State neighborItem: number = -1
  4928. @State neighborScale: number = -1
  4929. @State offsetY: number = 0
  4930. private dragRefOffset: number = 0
  4931. private ITEM_INTV: number = 78
  4932. scaleSelect(item: number): number {
  4933. if (this.scaleItem === item) {
  4934. return 1.05
  4935. } else if (this.neighborItem === item) {
  4936. return this.neighborScale
  4937. } else {
  4938. return 1
  4939. }
  4940. }
  4941. itemMove(index: number, newIndex: number): void {
  4942. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  4943. return;
  4944. }
  4945. let tmp = this.videoLocalList.splice(index, 1);
  4946. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  4947. this.dataSource.pushArrayData(this.videoLocalList)
  4948. if(this.modeType==4&&this.playlistTable){
  4949. updateAllSongsSortOrder(this.playlistTable, this.videoLocalList,this.currentSongListID)
  4950. }
  4951. }
  4952. //瀑布流布局 支持双指缩放
  4953. @State columns: number = 2;
  4954. @State waterFlowScale: number = 1;
  4955. @State imageScale: number = 1;
  4956. @State waterFlowOpacity: number = 1;
  4957. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  4958. private columnChanged: boolean = false;
  4959. private oldColumn: number = this.columns;
  4960. private pinchTime: number = 0;
  4961. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  4962. changeColumns(scale: number) {
  4963. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  4964. this.columns--;
  4965. this.columnChanged = true;
  4966. } else if (scale < 1 && this.columns < 4) {
  4967. this.columns++;
  4968. this.columnChanged = true;
  4969. }
  4970. }
  4971. @Builder
  4972. getWaterView(){
  4973. Scroll(this.scroller) {
  4974. Column() {
  4975. Blank().height(this.topSafeHeight + 55)
  4976. WaterFlow({
  4977. scroller:this.waterScroller,
  4978. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  4979. }) {
  4980. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  4981. FlowItem() {
  4982. this.MusicWaterCardItem(item,index)
  4983. }
  4984. .width('100%')
  4985. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  4986. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  4987. {
  4988. preview: MenuPreviewMode.IMAGE,
  4989. previewAnimationOptions: { scale: [0.8, 1.0] },
  4990. })
  4991. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  4992. {
  4993. preview: MenuPreviewMode.IMAGE,
  4994. previewAnimationOptions: { scale: [0.8, 1.0] },
  4995. })
  4996. .transition(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }))
  4997. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  4998. TransitionEffect.scale({ x: 0, y: 0 })))
  4999. .gesture(
  5000. GestureGroup(GestureMode.Exclusive,
  5001. SwipeGesture({ direction: SwipeDirection.Horizontal })
  5002. .onAction((event: GestureEvent) => {
  5003. if (event) {
  5004. // this.sideBarController.openSideBar()
  5005. }
  5006. }),
  5007. TapGesture({ count: 1, fingers: 1 })
  5008. .onAction(async () => {
  5009. })
  5010. )
  5011. )
  5012. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5013. }
  5014. // .columnsTemplate('repeat(auto-fit, 160)')
  5015. .id('waterflow') // 设置id用于截图
  5016. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  5017. .columnsGap(12) // 列间距
  5018. .rowsGap(16) // 行间距
  5019. .cachedCount(6)
  5020. .padding({bottom:this.bottomBarHeight+10})
  5021. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  5022. .animation({ duration: 500, curve: Curve.Ease }))
  5023. .scrollBar(BarState.Off)
  5024. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  5025. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  5026. .edgeEffect(EdgeEffect.Spring, { alwaysEnabled: true })
  5027. .width('90%')
  5028. .height('100%')
  5029. .opacity(this.waterFlowOpacity)
  5030. .scale({
  5031. x: this.waterFlowScale,
  5032. y: this.waterFlowScale,
  5033. centerX: 0,
  5034. centerY: 0
  5035. })
  5036. .onAppear(() => {
  5037. this.scroller.scrollEdge(Edge.Top)
  5038. })
  5039. .nestedScroll({
  5040. scrollForward: NestedScrollMode.PARENT_FIRST,
  5041. scrollBackward: NestedScrollMode.SELF_FIRST
  5042. })
  5043. .priorityGesture(
  5044. PinchGesture()
  5045. .onActionStart((event: GestureEvent) => {
  5046. // 双指捏合手势识别成功时截图
  5047. this.pinchTime = event.timestamp;
  5048. this.columnChanged = false;
  5049. this.oldColumn = this.columns;
  5050. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  5051. if (error) {
  5052. console.info('error:' + JSON.stringify(error));
  5053. return;
  5054. }
  5055. this.waterFlowSnapshot = pixmap;
  5056. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  5057. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  5058. if (this.oldColumn ===4) {
  5059. this.twoFingerType =3
  5060. this.isGridMusic = true
  5061. }else if (this.oldColumn ===1) {
  5062. this.twoFingerType =1
  5063. this.isGridMusic = false
  5064. }
  5065. return;
  5066. }
  5067. })
  5068. })
  5069. .onActionUpdate((event: GestureEvent) => {
  5070. // 手势更新:处理缩放逻辑和视觉效果
  5071. // 边界限制:防止超出列数范围时继续缩放
  5072. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  5073. return;
  5074. }
  5075. // 节流处理:避免过于频繁的更新,提升性能
  5076. if (event.timestamp - this.pinchTime < 10000000) {
  5077. return;
  5078. }
  5079. this.pinchTime = event.timestamp;
  5080. this.waterFlowScale = event.scale;
  5081. this.imageScale = event.scale;
  5082. // 根据缩放比例设置WaterFlow透明度
  5083. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  5084. this.waterFlowOpacity *= 3;
  5085. if (!this.columnChanged) {
  5086. this.changeColumns(event.scale);
  5087. }
  5088. // 列数改变后的缩放比例调整:避免出现空白区域
  5089. if (this.columnChanged) {
  5090. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  5091. // 限制缩放范围,确保视觉效果自然
  5092. if (event.scale < 1) {
  5093. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  5094. } else {
  5095. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  5096. }
  5097. }
  5098. })
  5099. .onActionEnd((event: GestureEvent) => {
  5100. // 手势结束:执行归位动画并保存状态
  5101. // 执行归位动画:平滑过渡到正常状态
  5102. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  5103. this.waterFlowScale = 1;
  5104. this.waterFlowOpacity = 1;
  5105. })
  5106. // 持久化保存当前列数:下次启动时恢复
  5107. PreferencesUtil.putSync('lastColumns', this.columns);
  5108. })
  5109. )
  5110. .onScrollFrameBegin((offset: number) => {
  5111. // 获取当前滚动偏移量
  5112. if(this.autoHideTitle){
  5113. const currentOffsetY = this.waterScroller.currentOffset().yOffset;
  5114. // 判断滚动方向
  5115. if (currentOffsetY > this.prevOffsetY) {
  5116. // console.log("onecold 向上滚动");
  5117. this.isShowTitleBar = false
  5118. } else if (currentOffsetY < this.prevOffsetY) {
  5119. // console.log("onecold 向下滚动");
  5120. this.isShowTitleBar = true
  5121. }
  5122. // 更新前一次偏移量
  5123. this.prevOffsetY = currentOffsetY;
  5124. }
  5125. return { offsetRemain: offset };
  5126. })
  5127. }
  5128. }
  5129. .scrollBar(BarState.Off)
  5130. }
  5131. //瀑布流卡片布局
  5132. @Builder
  5133. private MusicWaterCardItem(item: VideoItem, index: number) {
  5134. Button({ type: ButtonType.Normal, stateEffect: false }) {
  5135. Stack() {
  5136. Column() {
  5137. Image(item.pixelMapPath)
  5138. .backgroundImageSize(ImageSize.Auto)
  5139. .borderRadius({
  5140. topLeft: 12,
  5141. topRight : 12,
  5142. bottomLeft: 0,
  5143. bottomRight: 0
  5144. })
  5145. .draggable(false)// 禁止长按手势拖动
  5146. .autoResize(true) // 重采样,可减少内存占用
  5147. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  5148. .width('100%')
  5149. .height('auto')
  5150. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  5151. .objectFit(ImageFit.Auto)
  5152. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  5153. height: '99%' ,
  5154. dragBar: true,
  5155. onDisappear: () => {
  5156. this.longItemFilePath = '';
  5157. this.tempLyricContent = ''
  5158. },
  5159. showClose: true,
  5160. preferType: SheetType.CENTER ,
  5161. title: { title: '编辑标签' }
  5162. })
  5163. .draggable(false)
  5164. .opacity(this.opacityItem)// 绑定透明度
  5165. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  5166. // .animation({ duration: 500, curve: Curve.Ease }))
  5167. .animation({
  5168. duration: 666,
  5169. curve: 'ease-in-out' // 可选动画曲线
  5170. })
  5171. .margin({
  5172. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5173. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5174. })
  5175. Column() {
  5176. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5177. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  5178. .maxLines(1)
  5179. .fontWeight(FontWeight.Bold)
  5180. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5181. .animation({
  5182. duration: 555,
  5183. curve: 'Linear',
  5184. })
  5185. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  5186. height: '95%',
  5187. dragBar: true,
  5188. showClose: true,
  5189. onDisappear: () => {
  5190. this.longItemFilePathDetail = '';
  5191. },
  5192. blurStyle:BlurStyle.Thin,
  5193. backgroundColor:Color.Transparent,
  5194. preferType: SheetType.CENTER ,
  5195. title: { title: '详情' }
  5196. })
  5197. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5198. $r('app.color.text_color'))
  5199. Column() {
  5200. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  5201. .fontSize(11)
  5202. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  5203. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5204. .fontColor($r('app.color.text_color'))
  5205. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  5206. .fontSize(11)
  5207. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  5208. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5209. .fontColor($r('app.color.text_color'))
  5210. Row(){
  5211. Column(){
  5212. Text(item.md5Str?.includes('Lossless')?
  5213. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5214. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  5215. .padding({ top: 3,right:6,left:6,bottom:3 })
  5216. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5217. $r('app.color.text_color'))
  5218. .fontWeight(500)
  5219. .borderRadius(12)
  5220. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5221. .backgroundColor('#FFC107')
  5222. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  5223. }
  5224. .margin({ top: 2 ,right:6})
  5225. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  5226. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  5227. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  5228. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  5229. .maxLines(1)
  5230. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5231. .margin({ top: 2})
  5232. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  5233. || item.type == CommonConstants.TYPE_IS_ALBUM
  5234. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5235. .fontWeight(FontWeight.Medium)
  5236. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5237. $r('app.color.text_color'))
  5238. }
  5239. }
  5240. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  5241. }
  5242. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  5243. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  5244. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  5245. .width('100%')
  5246. .justifyContent(FlexAlign.Center)
  5247. .margin({
  5248. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5249. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5250. })
  5251. }
  5252. .width('100%')
  5253. .borderRadius(12)
  5254. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  5255. .backgroundImageSize({ height: '100%', width: '100%' })
  5256. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  5257. .animation({ curve: Curve.Sharp, duration: 300 })
  5258. Checkbox({ name: 'checkbox' + index })
  5259. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  5260. .selectedColor(this.themeColor)
  5261. .shape(CheckBoxShape.CIRCLE)
  5262. .opacity(this.isMultiSelect ? 1 : 0)
  5263. .animation({
  5264. duration: 666,
  5265. curve: 'Smooth' // 可选动画曲线
  5266. })
  5267. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  5268. Visibility.None)
  5269. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5270. .margin({ left: 20, top: 8, bottom: 8 })
  5271. .width(38)
  5272. .height(38)
  5273. }
  5274. }
  5275. .backgroundColor(Color.Transparent)
  5276. .width('100%')
  5277. .height('auto')
  5278. .padding({top:2})
  5279. .shadow({
  5280. radius: 10,
  5281. type: ShadowType.BLUR,
  5282. color: 'on_primary'
  5283. })
  5284. .reuseId('card_item')
  5285. .onClick(() => {
  5286. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5287. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5288. this.handleFileSelection(item, !isChecked);
  5289. } else {
  5290. this.doPlay(item, index)
  5291. }
  5292. })
  5293. }
  5294. // Grid布局的开始
  5295. private dragRefOffSetX: number = 0;
  5296. private dragRefOffSetY: number = 0;
  5297. private FIX_VP_X: number = 180;
  5298. private FIX_VP_Y: number = 84;
  5299. isDraggable(index: number): boolean {
  5300. return index >= 0;
  5301. }
  5302. getRowEnd(item: number) {
  5303. if (item.toString() === '0') {
  5304. return 1;
  5305. } else {
  5306. return 0;
  5307. }
  5308. }
  5309. isInLeft(index: number) {
  5310. return index % 2 == 0;
  5311. }
  5312. down(index: number): void {
  5313. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  5314. return;
  5315. }
  5316. this.offsetY -= this.FIX_VP_Y;
  5317. this.dragRefOffSetY += this.FIX_VP_Y;
  5318. this.itemMove(index, index + 1);
  5319. }
  5320. up(index: number): void {
  5321. if (!this.isDraggable(index - 2)) {
  5322. return;
  5323. }
  5324. this.offsetY += this.FIX_VP_Y;
  5325. this.dragRefOffSetY -= this.FIX_VP_Y;
  5326. this.itemMove(index, index - 1);
  5327. }
  5328. left(index: number): void {
  5329. if (this.isInLeft(index)) {
  5330. return;
  5331. }
  5332. if (!this.isDraggable(index - 1)) {
  5333. return;
  5334. }
  5335. this.offsetX += this.FIX_VP_X;
  5336. this.dragRefOffSetX -= this.FIX_VP_X;
  5337. this.itemMove(index, index - 1)
  5338. }
  5339. right(index: number): void {
  5340. if (!this.isInLeft(index)) {
  5341. return;
  5342. }
  5343. if (!this.isDraggable(index + 1)) {
  5344. return;
  5345. }
  5346. this.offsetX -= this.FIX_VP_X;
  5347. this.dragRefOffSetX += this.FIX_VP_X;
  5348. this.itemMove(index, index + 1)
  5349. }
  5350. private scroller: Scroller = new Scroller();
  5351. private waterScroller: Scroller = new Scroller();
  5352. @State startIndex: number = 0
  5353. @State endIndex: number = 0
  5354. @State scaleValue: number = 1
  5355. @State pinchValue: number = 1
  5356. layoutOptionsForHeader: GridLayoutOptions = {
  5357. regularSize: [1, 1], // 只支持[1, 1]
  5358. irregularIndexes: [0], // 索引为0的GridItem占用一行
  5359. };
  5360. @Builder
  5361. getGridView() {
  5362. Grid(this.scroller, this.layoutOptionsForHeader) {
  5363. GridItem() {
  5364. Column(){
  5365. Blank().height(this.topSafeHeight + 45)
  5366. }
  5367. }
  5368. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5369. GridItem() {
  5370. Stack({ alignContent: Alignment.Center }) {
  5371. this.MusicItemGrid(item, index)
  5372. }
  5373. }
  5374. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  5375. {
  5376. preview: MenuPreviewMode.IMAGE,
  5377. previewAnimationOptions: { scale: [0.8, 1.0] },
  5378. })
  5379. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  5380. {
  5381. preview: MenuPreviewMode.IMAGE,
  5382. previewAnimationOptions: { scale: [0.8, 1.0] },
  5383. })
  5384. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  5385. TransitionEffect.scale({ x: 0, y: 0 })))
  5386. .clickEffect({ level: ClickEffectLevel.LIGHT })
  5387. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  5388. .zIndex(this.dragItem === index ? 1 : 0)
  5389. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  5390. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5391. }
  5392. .width('94%')
  5393. .height('100%')
  5394. .editMode(true)
  5395. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  5396. .animation({ duration: 500, curve: Curve.Ease }))
  5397. .padding({bottom:this.bottomBarHeight+this.bottomSafeHeight+10})
  5398. .reuseId('grid_item')
  5399. .layoutWeight(1)
  5400. .scrollBar(BarState.Off)
  5401. .supportAnimation(true)
  5402. .cachedCount(this.twoFingerType==1?5:this.twoFingerType==2?4:3)
  5403. .columnsTemplate(
  5404. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  5405. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  5406. )
  5407. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  5408. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  5409. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5410. .gesture(PinchGesture({ fingers: 2 })
  5411. .onActionEnd((event: GestureEvent) => {
  5412. this.setGridTwoFingers()
  5413. })
  5414. .onActionUpdate(e => {
  5415. this.scaleValue = this.pinchValue * e.scale
  5416. })
  5417. .onActionStart(e => {
  5418. }))
  5419. .enableScrollInteraction(true)
  5420. .onScrollIndex((start: number, end: number) => {
  5421. this.startIndex = start
  5422. this.endIndex = end
  5423. })
  5424. .onScrollFrameBegin((offset: number) => {
  5425. if(this.autoHideTitle){
  5426. const currentOffsetY = this.scroller.currentOffset().yOffset;
  5427. // 判断滚动方向
  5428. if (currentOffsetY > this.prevOffsetY) {
  5429. // console.log("onecold 向上滚动");
  5430. this.isShowTitleBar = false
  5431. } else if (currentOffsetY < this.prevOffsetY) {
  5432. // console.log("onecold 向下滚动");
  5433. this.isShowTitleBar = true
  5434. }
  5435. // 更新前一次偏移量
  5436. this.prevOffsetY = currentOffsetY;
  5437. }
  5438. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  5439. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  5440. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  5441. if (this.isScrollHide) {
  5442. this.setBarHeightHide2(offset)
  5443. } else {
  5444. this.setBarHeightNormal()
  5445. }
  5446. } else {
  5447. this.setBarHeightHide(offset)
  5448. }
  5449. return { offsetRemain: offset };
  5450. })
  5451. }
  5452. @State targetFile: string = '';
  5453. setGridTwoFingers() {
  5454. this.pinchValue = this.scaleValue;
  5455. Logger.info('this.pinchValue = ' + this.pinchValue);
  5456. if (this.pinchValue >= 1) {
  5457. this.twoFingerType++
  5458. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  5459. if(this.twoFingerType >= 4){
  5460. this.twoFingerType = 4//切换成瀑布流
  5461. this.columns = 4
  5462. }
  5463. } else {
  5464. this.twoFingerType--
  5465. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  5466. if (this.twoFingerType < 1) {
  5467. this.twoFingerType = 3
  5468. this.isGridMusic = false
  5469. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5470. }
  5471. }
  5472. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5473. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5474. this.pinchValue = 1;
  5475. this.scaleValue = 1;
  5476. }
  5477. @State longItemFilePath: string = ''
  5478. @State tempLyricContent: string = ''
  5479. @State editingItem: VideoItem | null = null
  5480. @Builder
  5481. private MusicItemGrid(item: VideoItem, index: number) {
  5482. Button({ type: ButtonType.Normal, stateEffect: false }) {
  5483. Stack() {
  5484. Column() {
  5485. Image(item.pixelMapPath)
  5486. .height(this.getGridHeight())
  5487. .width(this.getGridWight())
  5488. .draggable(false)
  5489. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  5490. .autoResize(true) // 重采样,可减少内存占用
  5491. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  5492. .clip(true)
  5493. .borderRadius({
  5494. topLeft: 12,
  5495. topRight: 12,
  5496. bottomLeft: 0,
  5497. bottomRight: 0
  5498. })
  5499. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  5500. height: '99%' ,
  5501. dragBar: true,
  5502. onDisappear: () => {
  5503. this.longItemFilePath = '';
  5504. this.tempLyricContent = ''
  5505. },
  5506. showClose: true,
  5507. preferType: SheetType.CENTER ,
  5508. title: { title: '编辑标签' }
  5509. })
  5510. .draggable(false)
  5511. .opacity(this.opacityItem)// 绑定透明度
  5512. .animation({
  5513. duration: 666,
  5514. curve: 'ease-in-out' // 可选动画曲线
  5515. })
  5516. .margin({
  5517. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5518. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5519. })
  5520. Column() {
  5521. Text(this.isShowFileName&&item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5522. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5523. .maxLines(1)
  5524. .fontWeight(FontWeight.Bold)
  5525. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5526. .animation({
  5527. duration: 555,
  5528. curve: 'Linear',
  5529. })
  5530. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  5531. height: '100%',
  5532. dragBar: true,
  5533. showClose: true,
  5534. onDisappear: () => {
  5535. this.longItemFilePathDetail = '';
  5536. },
  5537. blurStyle:BlurStyle.Thin,
  5538. backgroundColor:Color.Transparent,
  5539. preferType: SheetType.CENTER ,
  5540. title: { title: '详情' }
  5541. })
  5542. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5543. $r('app.color.text_color'))
  5544. Column() {
  5545. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  5546. .fontSize(11)
  5547. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  5548. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5549. .fontColor($r('app.color.text_color'))
  5550. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  5551. .fontSize(11)
  5552. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  5553. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5554. .fontColor($r('app.color.text_color'))
  5555. Row(){
  5556. Column(){
  5557. Text(item.md5Str?.includes('Lossless')?
  5558. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5559. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5560. .padding({ top: 3,right:6,left:6,bottom:3 })
  5561. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5562. $r('app.color.text_color'))
  5563. .fontWeight(500)
  5564. .borderRadius(12)
  5565. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5566. .backgroundColor('#FFC107')
  5567. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  5568. }
  5569. .margin({ top: 2 ,right:6})
  5570. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  5571. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  5572. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  5573. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  5574. .maxLines(1)
  5575. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5576. .margin({ top: 2})
  5577. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  5578. || item.type == CommonConstants.TYPE_IS_ALBUM
  5579. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5580. .fontWeight(FontWeight.Medium)
  5581. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5582. $r('app.color.text_color'))
  5583. }
  5584. }
  5585. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  5586. }
  5587. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  5588. .width(this.getGridWight())
  5589. .justifyContent(FlexAlign.Center)
  5590. .margin({
  5591. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5592. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5593. })
  5594. }
  5595. .width(this.getGridWight())
  5596. .borderRadius(12)
  5597. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?$r('app.media.alt'):item.pixelMapPath)
  5598. .backgroundImageSize({ height: '100%', width: '100%' })
  5599. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  5600. .animation({ curve: Curve.Sharp, duration: 300 })
  5601. Checkbox({ name: 'checkbox' + index })
  5602. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  5603. .selectedColor(this.themeColor)
  5604. .shape(CheckBoxShape.CIRCLE)
  5605. .opacity(this.isMultiSelect ? 1 : 0)
  5606. .animation({
  5607. duration: 666,
  5608. curve: 'Smooth' // 可选动画曲线
  5609. })
  5610. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  5611. Visibility.None)
  5612. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5613. .margin({ left: 20, top: 8, bottom: 8 })
  5614. .width(38)
  5615. .height(38)
  5616. }
  5617. }
  5618. .backgroundColor(Color.Transparent)
  5619. .width('100%')
  5620. .padding({ top: 15 })
  5621. .height(this.getGridAllHeight())
  5622. .onClick(() => {
  5623. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5624. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5625. this.handleFileSelection(item, !isChecked);
  5626. } else {
  5627. this.doPlay(item, index)
  5628. }
  5629. })
  5630. }
  5631. getGridAllHeight() {
  5632. let heightG = 222
  5633. switch (this.twoFingerType) {
  5634. case 1:
  5635. heightG = 143
  5636. break;
  5637. case 2:
  5638. heightG = 178
  5639. break;
  5640. case 3:
  5641. heightG = 222
  5642. break;
  5643. }
  5644. return heightG
  5645. }
  5646. getGridHeight() {
  5647. let heightG = 150
  5648. switch (this.twoFingerType) {
  5649. case 1:
  5650. heightG = 80
  5651. break;
  5652. case 2:
  5653. heightG = 110
  5654. break;
  5655. case 3:
  5656. heightG = 150
  5657. break;
  5658. }
  5659. return heightG
  5660. }
  5661. getGridWight() {
  5662. let wightG = 158
  5663. switch (this.twoFingerType) {
  5664. case 1:
  5665. wightG = 80
  5666. break;
  5667. case 2:
  5668. wightG = 110
  5669. break;
  5670. case 3:
  5671. wightG = 158
  5672. break;
  5673. }
  5674. return wightG
  5675. }
  5676. @State isShowDetail:boolean = false
  5677. @State longItemFilePathDetail:string =''
  5678. @Builder
  5679. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  5680. if(
  5681. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  5682. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5683. item.name === LocalMusic.STR_HISTORY_MUSIC)
  5684. ){
  5685. //如果是专辑和艺术家的首页,不能长按
  5686. //如果是我的收藏 最近播放等也不能长按
  5687. }else{
  5688. Scroll() {
  5689. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  5690. Menu() {
  5691. MenuItem({
  5692. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  5693. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  5694. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  5695. })
  5696. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5697. .onClick(() => {
  5698. if (item) {
  5699. this.doFav(item)
  5700. }
  5701. this.longItemFilePath = ''
  5702. })
  5703. MenuItem({
  5704. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  5705. content: '下一首播放'
  5706. })
  5707. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5708. .onClick(() => {
  5709. this.addToNextPlay(item);
  5710. this.longItemFilePath = ''
  5711. })
  5712. MenuItem({
  5713. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  5714. content: '添加到歌单'
  5715. })
  5716. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5717. .onClick(async () => {
  5718. this.longItemFilePath = ''
  5719. await this.openAddToPlaylistDialog(item)
  5720. })
  5721. MenuItem({
  5722. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  5723. content: '编辑标签'
  5724. })
  5725. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  5726. height: '99%',
  5727. dragBar: true,
  5728. showClose: true,
  5729. preferType: SheetType.CENTER ,
  5730. title: { title: '编辑标签' }
  5731. })
  5732. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5733. .onClick(async() => {
  5734. this.initEditFields(item)
  5735. this.tempLyricContent = await this.getLyricContent(item);
  5736. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  5737. this.lyricConStr = this.tempLyricContent
  5738. }
  5739. if(this.isGridMusic||this.twoFingerType==4){
  5740. this.longItemFilePath = item.filePath
  5741. }else{
  5742. this.isShowEdit = !this.isShowEdit;
  5743. }
  5744. })
  5745. MenuItem({
  5746. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  5747. content: $r('app.string.select_all')
  5748. })
  5749. .onClick(() => {
  5750. this.isMultiSelect = !this.isMultiSelect
  5751. this.longItemFilePath = ''
  5752. this.selectedFiles.push(item)
  5753. })
  5754. MenuItem({
  5755. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.cut')),
  5756. content: $r('app.string.edit_audio')
  5757. })
  5758. .bindContentCover($$this.isEditAudio, this.EditAudioBuilder(item), {
  5759. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5760. })
  5761. .onClick(() => {
  5762. this.isEditAudio = !this.isEditAudio
  5763. })
  5764. MenuItem({
  5765. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  5766. content: $r('app.string.extract_accompaniment')
  5767. })
  5768. .bindContentCover($$this.isExtractAcc, this.ExtractAccBuilder(item), {
  5769. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5770. })
  5771. .onClick(() => {
  5772. if (!Utility.isNoble()) {
  5773. this.showVipDialog()
  5774. return
  5775. }
  5776. this.isExtractAcc = !this.isExtractAcc
  5777. })
  5778. MenuItem({
  5779. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.repeat')),
  5780. content: $r('app.string.converter_audio')
  5781. })
  5782. .bindContentCover($$this.isConverter, this.ConverterBuilder(item), {
  5783. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5784. })
  5785. .onClick(() => {
  5786. if (!Utility.isNoble()) {
  5787. this.showVipDialog()
  5788. return
  5789. }
  5790. this.isConverter = !this.isConverter
  5791. })
  5792. MenuItem({
  5793. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.ai_edit')),
  5794. content: $r('app.string.vocal_separation')
  5795. })
  5796. .bindContentCover($$this.isAIVoiceSeparation, this.AiBuilder(item), {
  5797. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5798. })
  5799. .onClick(() => {
  5800. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  5801. })
  5802. MenuItem({
  5803. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_counterclockwise_clock')),
  5804. content: $r('app.string.change_tone')
  5805. })
  5806. .bindContentCover($$this.isChangeTone, this.ChangeToneBuilder(item), {
  5807. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5808. })
  5809. .onClick(() => {
  5810. this.isChangeTone = !this.isChangeTone
  5811. })
  5812. if(Utility.isVideoByExtension(item.filePath)){
  5813. MenuItem({
  5814. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.identify_song')),
  5815. content: $r('app.string.extract_audio')
  5816. })
  5817. .bindContentCover($$this.isExtractAudio, this.extractAudioFromVideoBuilder(item), {
  5818. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5819. })
  5820. .onClick(() => {
  5821. this.isExtractAudio = !this.isExtractAudio
  5822. })
  5823. }
  5824. MenuItem({
  5825. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.phone')),
  5826. content: $r('app.string.set_ring')
  5827. })
  5828. .onClick(async () => {
  5829. await PermissionUtil.activatePermission(item.filePath)
  5830. // if(item.filePath.includes(this.packName)){
  5831. setRingTone(this.context, item.filePath,item.name)
  5832. // }else{
  5833. // ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限设置铃声')
  5834. // }
  5835. this.longItemFilePath = ''
  5836. })
  5837. MenuItem({
  5838. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  5839. content: $r('app.string.rename')
  5840. })
  5841. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  5842. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5843. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  5844. .onClick(() => {
  5845. this.showReNameDialog(item, index + '', filePath)
  5846. this.longItemFilePath = ''
  5847. })
  5848. MenuItem({
  5849. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  5850. content: $r('app.string.delete')
  5851. })
  5852. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  5853. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5854. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  5855. .onClick(() => {
  5856. this.selectedFiles.push(item)
  5857. this.showWarnIsDelete()
  5858. this.longItemFilePath = ''
  5859. })
  5860. MenuItem({
  5861. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  5862. content: $r('app.string.detail')
  5863. })
  5864. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  5865. height:'100%',
  5866. dragBar: true,
  5867. showClose: true,
  5868. blurStyle:BlurStyle.Thin,
  5869. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  5870. backgroundColor:Color.Transparent,
  5871. title: { title: '详情信息' }
  5872. })
  5873. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5874. .onClick(() => {
  5875. if(this.isGridMusic||this.twoFingerType==4){
  5876. this.longItemFilePathDetail = item.filePath
  5877. }else{
  5878. this.isShowDetail = !this.isShowDetail
  5879. }
  5880. })
  5881. MenuItem({
  5882. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  5883. content: $r('app.string.share')
  5884. })
  5885. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5886. .onClick(() => {
  5887. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  5888. this.longItemFilePath = ''
  5889. })
  5890. }
  5891. .font({ size: 14, weight: FontWeight.Normal })
  5892. }
  5893. .width(180)
  5894. }
  5895. .height('auto')
  5896. .enableScrollInteraction(true)
  5897. .scrollBar(this.isGridMusic?BarState.On:BarState.Off)
  5898. }
  5899. }
  5900. private listMaxScrollOffsetY: number = 0
  5901. @State selectedIndex: number = -1
  5902. setlistTwoFingers() {
  5903. this.pinchValue = this.scaleValue;
  5904. Logger.info('this.pinchValue = ' + this.pinchValue);
  5905. if (this.pinchValue >= 1) {
  5906. this.twoFingerType++
  5907. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  5908. if (this.twoFingerType > 3) {
  5909. this.twoFingerType = 1
  5910. this.isGridMusic = true
  5911. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5912. }
  5913. } else {
  5914. this.twoFingerType--
  5915. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  5916. if (this.twoFingerType < 1) {
  5917. this.twoFingerType = 4
  5918. this.columns = 1
  5919. }
  5920. }
  5921. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5922. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5923. this.pinchValue = 1;
  5924. this.scaleValue = 1;
  5925. }
  5926. @Builder
  5927. getList(){
  5928. Stack() {
  5929. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  5930. this.getListView()
  5931. }
  5932. .pullDownRatio(this.ratioL)
  5933. .pullToRefresh(true)
  5934. .refreshOffset(0)
  5935. .onOffsetChange((offset: number) => {
  5936. // 越接近最大距离,下拉跟手系数越小。
  5937. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  5938. })
  5939. .onStateChange((refreshStatus: RefreshStatus) => {
  5940. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  5941. })
  5942. .onRefreshing(async () => {
  5943. if(this.modeType==0){
  5944. this.getHistoryList(false)
  5945. this.asyncCurrentPathOnlyFile()
  5946. }else if(this.modeType == 1){
  5947. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  5948. }else if(this.modeType == 2){
  5949. workerInstance.postMessage({ code: 3, data: this.context });
  5950. }else if(this.modeType == 3){
  5951. workerInstance.postMessage({ code: 4, data: this.context });
  5952. }else if(this.modeType == 4){
  5953. this.doSongListTask()
  5954. }
  5955. console.log('onRefreshing test');
  5956. })
  5957. }
  5958. }
  5959. // 扫描当前目录下的文件,不扫描子目录
  5960. asyncCurrentPathOnlyFile(){
  5961. if(this.modeType==0){
  5962. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  5963. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  5964. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  5965. if(this.modeType==0){
  5966. setTimeout(()=>{
  5967. this.isRefreshing =false
  5968. this.deleteCache(this.currentPath)
  5969. this.getSortedFiles(this.currentPath)
  5970. },500)
  5971. }
  5972. }).catch((e:object)=>{
  5973. this.isRefreshing =false
  5974. console.info("onecold task1 catch e: " + e);
  5975. })
  5976. }
  5977. }
  5978. @Builder
  5979. getListView() {
  5980. List({ scroller: this.listScroller }) {
  5981. // ListItemGroup({ header: this.coverHeader() }) {
  5982. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5983. ListItem() {
  5984. Column() {
  5985. if (item.type === CommonConstants.TYPE_IS_DIR
  5986. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  5987. this.DirItem(item, index)
  5988. } else {
  5989. this.MusicItem(item, index)
  5990. }
  5991. }
  5992. .animation({ curve: Curve.Sharp, duration: 300 })
  5993. }
  5994. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.9, y: 0.9 })
  5995. .animation({ duration: 500 }),
  5996. TransitionEffect.scale({ x: 0, y: 0 })))
  5997. .clickEffect({ level: ClickEffectLevel.LIGHT })
  5998. .swipeAction((
  5999. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  6000. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  6001. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  6002. start:null,edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  6003. .onClick(() => {
  6004. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  6005. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  6006. this.handleFileSelection(item, !isChecked);
  6007. } else {
  6008. this.doPlay(item, index)
  6009. }
  6010. })
  6011. //拖动List关键代码开始
  6012. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  6013. .zIndex(this.dragItem === index ? 1 : 0)
  6014. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  6015. .gesture(
  6016. GestureGroup(GestureMode.Sequence,
  6017. LongPressGesture({ repeat: true })
  6018. .onAction((event?: GestureEvent) => {
  6019. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  6020. this.scaleItem = index
  6021. })
  6022. })
  6023. .onActionEnd(() => {
  6024. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  6025. this.scaleItem = -1
  6026. })
  6027. }),
  6028. PanGesture({ fingers: 1, direction: null, distance: 0 })
  6029. .onActionStart(() => {
  6030. this.dragItem = index // 记录当前拖动项索引
  6031. this.dragRefOffset = 0 // 重置偏移基准
  6032. })
  6033. .onActionUpdate((event: GestureEvent) => {
  6034. this.offsetY = event.offsetY - this.dragRefOffset;
  6035. this.neighborItem = -1;
  6036. let indexA = this.videoLocalList.indexOf(item);
  6037. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  6038. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  6039. let value: number = 0;
  6040. if (this.offsetY < 0) {
  6041. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  6042. this.neighborItem = indexA - 1;
  6043. this.neighborScale = 1 - value / 20;
  6044. } else if (this.offsetY > 0) {
  6045. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  6046. this.neighborItem = indexA + 1;
  6047. this.neighborScale = 1 - value / 20;
  6048. }
  6049. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  6050. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6051. this.offsetY -= this.ITEM_INTV;
  6052. this.dragRefOffset += this.ITEM_INTV;
  6053. this.itemMove(indexA, indexA + 1);
  6054. });
  6055. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  6056. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6057. this.offsetY += this.ITEM_INTV;
  6058. this.dragRefOffset -= this.ITEM_INTV;
  6059. this.itemMove(indexA, indexA - 1);
  6060. });
  6061. }
  6062. })
  6063. .onActionEnd((event: GestureEvent) => {
  6064. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6065. this.dragItem = -1
  6066. this.neighborItem = -1
  6067. })
  6068. animateTo({
  6069. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  6070. }, () => {
  6071. this.scaleItem = -1
  6072. })
  6073. })
  6074. )
  6075. .onCancel(() => {
  6076. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6077. this.dragItem = -1
  6078. this.neighborItem = -1
  6079. })
  6080. animateTo({
  6081. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  6082. }, () => {
  6083. this.scaleItem = -1
  6084. })
  6085. })
  6086. ) //拖动List关键代码结束
  6087. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  6088. // }
  6089. }
  6090. .onScrollStart(() => {
  6091. this.isScrolling = true
  6092. this.isShowAlphaBet = true
  6093. })
  6094. .onScrollIndex((start: number,center:number,end:number) => {
  6095. this.selectedIndex = start
  6096. if(start >= 0 && start < this.videoLocalList.length){
  6097. this.selectAlphaBetIndex = this.findAlphaBetIndex(this.videoLocalList[start])
  6098. }
  6099. })
  6100. .onScrollStop(() => {
  6101. if(this.isScrolling){
  6102. this.isScrolling = false
  6103. }
  6104. this.isShowAlphaBet = false
  6105. })
  6106. .scrollBar(BarState.Off)
  6107. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  6108. .gesture(PinchGesture({ fingers: 2 })
  6109. .onActionEnd((event: GestureEvent) => {
  6110. this.setlistTwoFingers()
  6111. })
  6112. .onActionUpdate(e => {
  6113. this.scaleValue = this.pinchValue * e.scale
  6114. })
  6115. .onActionStart(e => {
  6116. }))
  6117. .contentStartOffset(this.topSafeHeight + 55)
  6118. .scrollBar(BarState.Off)
  6119. .contentEndOffset(this.bottomBarHeight+this.bottomSafeHeight)
  6120. .cachedCount(10)
  6121. // .reuseId('list_item')
  6122. .borderRadius(20)
  6123. .layoutWeight(1)
  6124. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  6125. .lanes(
  6126. new BreakpointType<number>({
  6127. sm: 1,
  6128. md: 2,
  6129. lg: 2,
  6130. xl: 3,
  6131. xxl: 4
  6132. }).getValue(this.currentBreakpoint),
  6133. new BreakpointType<number>({
  6134. sm: 0,
  6135. md: 12,
  6136. lg: 12,
  6137. xl: 16,
  6138. xxl: 20
  6139. }).getValue(this.currentBreakpoint)
  6140. )
  6141. .onAreaChange((oldValue: Area, newValue: Area) => {
  6142. this.listArea = newValue
  6143. if (this.twoFingerType == 3) {
  6144. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  6145. } else if (this.twoFingerType == 2) {
  6146. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  6147. } else if (this.twoFingerType == 1) {
  6148. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  6149. }
  6150. })
  6151. .onScrollFrameBegin((offset: number) => {
  6152. // 获取当前滚动偏移量
  6153. if(this.autoHideTitle){
  6154. const currentOffsetY = this.listScroller.currentOffset().yOffset;
  6155. // 判断滚动方向
  6156. if (currentOffsetY > this.prevOffsetY) {
  6157. // console.log("onecold 向上滚动");
  6158. this.isShowTitleBar = false
  6159. } else if (currentOffsetY < this.prevOffsetY) {
  6160. // console.log("onecold 向下滚动");
  6161. this.isShowTitleBar = true
  6162. }
  6163. // 更新前一次偏移量
  6164. this.prevOffsetY = currentOffsetY;
  6165. }
  6166. return { offsetRemain: offset };
  6167. })
  6168. }
  6169. setBarHeightNormal() {
  6170. this.hideDone = false;
  6171. this.getUIContext().animateTo({
  6172. duration: 300
  6173. }, () => {
  6174. this.bottomBarHeight = 68 + 0;
  6175. this.topBarHeight = 50 + 0;
  6176. this.barOpacity = 1;
  6177. this.barBottomOpacity = 1
  6178. this.currentYOffset = 0;
  6179. this.isHiding = false;
  6180. });
  6181. }
  6182. setBarHeightHide(offset: number) {
  6183. if (offset > 0 && !this.hideDone) {
  6184. this.currentYOffset += offset;
  6185. if (this.currentYOffset <= 100) {
  6186. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  6187. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  6188. this.barOpacity = 1 - this.currentYOffset / 100;
  6189. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  6190. } else {
  6191. this.topBarHeight = 0;
  6192. this.bottomBarHeight = 0;
  6193. this.barBottomOpacity = 0
  6194. this.barOpacity = 0;
  6195. this.hideDone = true;
  6196. }
  6197. this.isHiding = true;
  6198. }
  6199. if (offset < 0 && this.isHiding) {
  6200. this.hideDone = false;
  6201. this.getUIContext().animateTo({
  6202. duration: 300
  6203. }, () => {
  6204. this.bottomBarHeight = 68 + 0;
  6205. this.topBarHeight = 50 + 0;
  6206. this.barOpacity = 1;
  6207. this.barBottomOpacity = 1
  6208. this.currentYOffset = 0;
  6209. this.isHiding = false;
  6210. });
  6211. }
  6212. }
  6213. //这个方法没隐藏bottomBar,只隐藏topbar
  6214. setBarHeightHide2(offset: number) {
  6215. if (offset > 0 && !this.hideDone) {
  6216. this.currentYOffset += offset;
  6217. if (this.currentYOffset <= 100) {
  6218. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  6219. this.barOpacity = 1 - this.currentYOffset / 100;
  6220. } else {
  6221. this.topBarHeight = 0;
  6222. this.barOpacity = 0;
  6223. this.hideDone = true;
  6224. }
  6225. this.isHiding = true;
  6226. }
  6227. if (offset < 0 && this.isHiding) {
  6228. this.hideDone = false;
  6229. this.getUIContext().animateTo({
  6230. duration: 300
  6231. }, () => {
  6232. this.topBarHeight = 50 + 0;
  6233. this.barOpacity = 1;
  6234. this.currentYOffset = 0;
  6235. this.isHiding = false;
  6236. });
  6237. }
  6238. }
  6239. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  6240. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  6241. switch (item.type) {
  6242. case CommonConstants.TYPE_IS_DIR:
  6243. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  6244. let offsetB = 0
  6245. if(this.twoFingerType==4){
  6246. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6247. let cur = this.waterScroller.currentOffset()
  6248. if (cur && typeof cur.yOffset === 'number') {
  6249. offsetB = cur.yOffset
  6250. }
  6251. }
  6252. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  6253. }else
  6254. if (this.isGridMusic) {
  6255. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6256. let cur = this.scroller.currentOffset()
  6257. if (cur && typeof cur.yOffset === 'number') {
  6258. offsetB = cur.yOffset
  6259. }
  6260. }
  6261. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  6262. } else {
  6263. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6264. let cur = this.listScroller.currentOffset()
  6265. if (cur && typeof cur.yOffset === 'number') {
  6266. offsetB = cur.yOffset
  6267. }
  6268. }
  6269. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  6270. }
  6271. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  6272. this.showVerifyDialog()
  6273. this.currentTitleName = '私密音频'
  6274. this.currentTitleCover = $r('app.media.alt')
  6275. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  6276. this.titleName = '最近播放'
  6277. this.currentTitleCover = $r('app.media.alt')
  6278. this.currentTitleName = '最近播放'
  6279. //加载动画效果
  6280. this.updateListData(this.historyList, true)
  6281. // this.videoLocalList = this.historyList
  6282. if (ArrayUtil.isEmpty(this.historyList)) {
  6283. ToastUtil.showToast('最近播放记录空空如也')
  6284. } else {
  6285. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  6286. }
  6287. this.isHistory = true
  6288. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  6289. this.titleName = '我的收藏'
  6290. this.currentTitleName = '我的收藏'
  6291. this.currentTitleCover = $r('app.media.alt')
  6292. //加载动画效果
  6293. this.updateListData(this.favList)
  6294. if (ArrayUtil.isEmpty(this.favList)) {
  6295. ToastUtil.showToast('无音乐收藏记录')
  6296. } else {
  6297. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  6298. }
  6299. this.isFavMusic = true
  6300. } else {
  6301. this.currentTitleName = item.name
  6302. this.currentPath = item.filePath
  6303. this.currentTitleCover = $r('app.media.alt')
  6304. this.getSortedFiles(this.currentPath)
  6305. }
  6306. //进入歌单的时候的滚动位置在顶部
  6307. if(this.twoFingerType==4){
  6308. setTimeout(() => {
  6309. this.waterScroller.scrollEdge(Edge.Top)
  6310. this.scroller.scrollEdge(Edge.Top)
  6311. }, 200)
  6312. }else{
  6313. if (this.isGridMusic) {
  6314. this.scroller.scrollToIndex(0,false)
  6315. }else{
  6316. this.listScroller.scrollToIndex(0,false)
  6317. }
  6318. }
  6319. this.rightTopImage = $r('sys.symbol.chevron_left')
  6320. break;
  6321. case CommonConstants.TYPE_IS_ARTIST:
  6322. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  6323. let offsetA = 0
  6324. if(this.twoFingerType==4){
  6325. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6326. let cur = this.waterScroller.currentOffset()
  6327. if (cur && typeof cur.yOffset === 'number') {
  6328. offsetA = cur.yOffset
  6329. }
  6330. }
  6331. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  6332. }else
  6333. if (this.isGridMusic) {
  6334. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6335. let cur = this.scroller.currentOffset()
  6336. if (cur && typeof cur.yOffset === 'number') {
  6337. offsetA = cur.yOffset
  6338. }
  6339. }
  6340. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  6341. } else {
  6342. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6343. let cur = this.listScroller.currentOffset()
  6344. if (cur && typeof cur.yOffset === 'number') {
  6345. offsetA = cur.yOffset
  6346. }
  6347. }
  6348. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  6349. }
  6350. let mList = this.artistMap.get(item.name)
  6351. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  6352. Utility.doSortListAscending(mList)
  6353. this.isCanBack = true
  6354. this.titleName = item.name
  6355. this.currentTitleName = '艺术家:' + item.name
  6356. if (item.pixelMapPath) {
  6357. this.currentTitleCover = item.pixelMapPath
  6358. }
  6359. this.updateListData(mList)
  6360. }
  6361. this.rightTopImage = $r('sys.symbol.chevron_left')
  6362. //进入歌单的时候的滚动位置在顶部
  6363. if(this.twoFingerType==4){
  6364. setTimeout(() => {
  6365. this.waterScroller.scrollEdge(Edge.Top)
  6366. this.scroller.scrollEdge(Edge.Top)
  6367. }, 380)
  6368. }else{
  6369. if (this.isGridMusic) {
  6370. this.scroller.scrollEdge(Edge.Top)
  6371. }else{
  6372. this.listScroller.scrollEdge(Edge.Top)
  6373. }
  6374. }
  6375. break;
  6376. case CommonConstants.TYPE_IS_ALBUM:
  6377. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  6378. let offset = 0
  6379. if(this.twoFingerType==4){
  6380. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6381. let cur = this.waterScroller.currentOffset()
  6382. if (cur && typeof cur.yOffset === 'number') {
  6383. offset = cur.yOffset
  6384. }
  6385. }
  6386. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  6387. }else
  6388. if (this.isGridMusic) {
  6389. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6390. let cur = this.scroller.currentOffset()
  6391. if (cur && typeof cur.yOffset === 'number') {
  6392. offset = cur.yOffset
  6393. }
  6394. }
  6395. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  6396. } else {
  6397. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6398. let cur = this.listScroller.currentOffset()
  6399. if (cur && typeof cur.yOffset === 'number') {
  6400. offset = cur.yOffset
  6401. }
  6402. }
  6403. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  6404. }
  6405. let albumList = this.albumMap.get(item.name)
  6406. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  6407. Utility.doSortListAscending(albumList)
  6408. this.isCanBack = true
  6409. this.titleName = item.name
  6410. this.currentTitleName = '专辑:' + item.name
  6411. if (item.pixelMapPath) {
  6412. this.currentTitleCover = item.pixelMapPath
  6413. }
  6414. this.updateListData(albumList)
  6415. this.mScrollMap.set(item.name, this.selectedIndex)
  6416. this.rightTopImage = $r('sys.symbol.chevron_left')
  6417. }
  6418. //进入歌单的时候的滚动位置在顶部
  6419. if(this.twoFingerType==4){
  6420. setTimeout(() => {
  6421. this.waterScroller.scrollEdge(Edge.Top)
  6422. this.scroller.scrollEdge(Edge.Top)
  6423. }, 380)
  6424. }else{
  6425. if (this.isGridMusic) {
  6426. this.scroller.scrollEdge(Edge.Top)
  6427. }else{
  6428. this.listScroller.scrollEdge(Edge.Top)
  6429. }
  6430. }
  6431. break;
  6432. case CommonConstants.TYPE_IS_CSJAD:
  6433. return
  6434. break;
  6435. case CommonConstants.TYPE_LOCAL:
  6436. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  6437. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  6438. const cueTracks:CueTrack[] = cueinfo.tracks
  6439. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  6440. if(ArrayUtil.isNotEmpty(cueTracks)){
  6441. this.showCueDialog(cueTracks,cueinfo)
  6442. }
  6443. // this.showCueSheet = !this.showCueSheet
  6444. return
  6445. }
  6446. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6447. this.stop();
  6448. }
  6449. if (isOpen) {
  6450. this.currentSong = item
  6451. if (index !== undefined) {
  6452. this.curIndex = index
  6453. }
  6454. this.songList = []
  6455. this.songList.push(item)
  6456. this.sonDataSource.pushArrayData(this.songList)
  6457. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  6458. this.currentSong = item
  6459. if (index !== undefined) {
  6460. this.curIndex = index
  6461. }
  6462. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  6463. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  6464. }else {
  6465. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  6466. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  6467. this.songList = globalVideoList
  6468. this.sonDataSource.pushArrayData(this.songList)
  6469. this.currentSong = globalVideoList[this.curIndex]
  6470. }
  6471. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  6472. this.videoUrl = this.currentSong.filePath
  6473. this.name = this.currentSong.name
  6474. this.cover = this.currentSong.pixelMapPath
  6475. this.artist = this.currentSong.artist
  6476. LogUtil.info('onecold this.currentSong.cover =' + this.currentSong.pixelMapPath)
  6477. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  6478. this.startPlayOrResumePlay()
  6479. break;
  6480. case CommonConstants.TYPE_WEBDAV:
  6481. case CommonConstants.TYPE_SMB:
  6482. case CommonConstants.TYPE_NAVIDROME:
  6483. case CommonConstants.TYPE_FTP:
  6484. case CommonConstants.TYPE_BAIDU:
  6485. case CommonConstants.TYPE_JELLYFIN:
  6486. case CommonConstants.TYPE_EMBY:
  6487. // 处理网络音频播放(WebDAV/SMB)
  6488. Logger.info(`heanup 处理云端音频播放: ${item.name}, URL: ${item.filePath}`)
  6489. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6490. this.stop();
  6491. }
  6492. if (isOpen) {
  6493. this.currentSong = item
  6494. if (index !== undefined) {
  6495. this.curIndex = index
  6496. }
  6497. this.songList = []
  6498. this.songList.push(item)
  6499. this.sonDataSource.pushArrayData(this.songList)
  6500. } else if (isFromSonPlayList) {
  6501. // 点击来自右下角的播放列表
  6502. this.currentSong = item
  6503. if (index !== undefined) {
  6504. this.curIndex = index
  6505. }
  6506. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  6507. Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  6508. } else {
  6509. // 从全局网络音频列表中查找
  6510. let globalVideoList = this.videoLocalList.filter(video => isRemoteCloudType(video.type)) as VideoItem[];
  6511. this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
  6512. if (this.curIndex === -1 && index !== undefined) {
  6513. this.curIndex = index;
  6514. }
  6515. this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
  6516. this.currentSong = this.songList[this.curIndex];
  6517. this.sonDataSource.pushArrayData(this.songList)
  6518. }
  6519. await this.hydrateRemoteSongFromDb(this.currentSong);
  6520. await this.hydrateRemoteSongFromDb(this.currentSong);
  6521. AppStorage.setOrCreate('currentSong', this.currentSong);
  6522. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  6523. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  6524. context: this.context,
  6525. autoParseMusicName: this.autoParseMusicName
  6526. });
  6527. Logger.info(TAG, `WebDAV URL同步构建完成(分支2): ${this.videoUrl}`);
  6528. this.name = this.currentSong.name
  6529. this.cover = this.currentSong.pixelMapPath
  6530. this.artist = this.currentSong.artist
  6531. Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 完整URL: ${this.videoUrl}`)
  6532. this.startPlayOrResumePlay()
  6533. break;
  6534. }
  6535. }
  6536. private cueComponentId: number = 0
  6537. //显示cue分轨列表对话框
  6538. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  6539. this.getUIContext().getPromptAction().openCustomDialog({
  6540. builder: () => {
  6541. this.cueComptentBuilder(cueTracks,cueinfo)
  6542. },
  6543. isModal:true,
  6544. showInSubWindow:false,
  6545. maskColor: Color.Transparent,
  6546. dialogTransition: // 设置弹窗内容显示的过渡效果
  6547. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  6548. .animation({ duration: 600, curve: Curve.Smooth }),
  6549. maskTransition: // 设置蒙层显示的过渡效果
  6550. TransitionEffect.opacity(0.5)
  6551. .animation({ duration: 600, curve: Curve.Smooth })
  6552. }).then((dialogId: number) => {
  6553. this.cueComponentId = dialogId
  6554. })
  6555. .catch((error: BusinessError) => {
  6556. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  6557. })
  6558. }
  6559. @Builder
  6560. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  6561. CueComptent({
  6562. title:cueinfo.title,
  6563. cueTracks:cueTracks,
  6564. isLongNameRoLL:this.isLongNameRoLL,
  6565. onCancel:()=>{
  6566. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  6567. },
  6568. onDoItemClick: async (item: CueTrack, index: number)=>{
  6569. //获取cueinfo对应的filePath
  6570. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  6571. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  6572. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  6573. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  6574. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  6575. if (this.currentSong){
  6576. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6577. this.stop();//播放之前先停止之前播放。
  6578. }
  6579. this.songList = globalVideoList
  6580. this.sonDataSource.pushArrayData(this.songList)
  6581. if (this.currentSong) {
  6582. try {
  6583. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  6584. context: this.context,
  6585. autoParseMusicName: this.autoParseMusicName
  6586. });
  6587. } catch (error) {
  6588. Logger.error(TAG, `CUE 点播构建播放地址失败: ${(error as Error).message}`);
  6589. this.videoUrl = this.currentSong.filePath;
  6590. }
  6591. }
  6592. this.name = item.title||this.currentSong.name
  6593. this.cover = this.currentSong.pixelMapPath
  6594. this.artist = item.performer||this.currentSong.artist
  6595. this.currentSong.name = this.name
  6596. this.currentSong.artist = this.artist
  6597. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  6598. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  6599. }
  6600. }
  6601. })
  6602. }
  6603. @State isFrontWhite: boolean = false
  6604. setShowPlayTrue(){
  6605. this.getUIContext()?.animateTo({
  6606. duration: 500,
  6607. curve: Curve.Friction
  6608. }, () => {
  6609. this.isShowPlay = true;
  6610. });
  6611. }
  6612. setShowPlayFalse(){
  6613. this.getUIContext()?.animateTo({
  6614. duration: 500,
  6615. curve: Curve.Friction
  6616. }, () => {
  6617. this.isShowPlay = false;
  6618. });
  6619. }
  6620. //打开播放页
  6621. showPlayerView() {
  6622. console.info('onecold showPlayerView this.songList'+ JSON.stringify(this.songList))
  6623. if (ArrayUtil.isNotEmpty(this.songList)) {
  6624. // this.setShowPlayTrue()
  6625. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  6626. this.initLyric(lyricPath);
  6627. this.startAutoHide();
  6628. } else {
  6629. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  6630. }
  6631. }
  6632. //打开播放列表
  6633. openPlayList(){
  6634. if (ArrayUtil.isNotEmpty(this.songList)) {
  6635. this.isShowSheet = !this.isShowSheet;
  6636. this.isFrontWhite = false
  6637. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  6638. this.scrollIndex()
  6639. } else {
  6640. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6641. }
  6642. }
  6643. scrollIndex(){
  6644. try {
  6645. setTimeout(() => {
  6646. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  6647. if(this.curIndex>60){
  6648. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  6649. }else{
  6650. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  6651. }
  6652. })
  6653. }, 123)
  6654. }catch (error) {
  6655. console.error(`onecold scrollIndex出错: ${error}`);
  6656. }
  6657. }
  6658. //播放列表布局
  6659. @Builder
  6660. PlayListSheet() {
  6661. Column() {
  6662. this.PlayList()
  6663. }
  6664. .width('100%')
  6665. .height('100%')
  6666. }
  6667. @State titleStr: string = ''
  6668. @State ablumStr: string = ''
  6669. @State artistStr: string = ''
  6670. @State lyricConStr: string = ''
  6671. @State currentEditItem: string = ''
  6672. @State yearStr: string = ''
  6673. @State trackStr: string = ''
  6674. @State genreStr: string = ''
  6675. @State imagePathStr: string = ''
  6676. @State albumArtistStr: string = ''
  6677. @State composerStr: string = ''
  6678. @State lyricistStr: string = ''
  6679. @State commentStr: string = ''
  6680. @State discStr: string = ''
  6681. doUpdateData() {
  6682. setTimeout(() => {
  6683. if (this.modeType === 0) {
  6684. this.deleteCache(this.currentPath)
  6685. this.getSortedFiles(this.currentPath)
  6686. }else if (this.modeType === 1){
  6687. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6688. }
  6689. }, 500)
  6690. }
  6691. doAllUpdateData() {
  6692. setTimeout(() => {
  6693. if (this.modeType === 0) {
  6694. this.deleteCache(this.currentPath)
  6695. this.getSortedFiles(this.currentPath)
  6696. }
  6697. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6698. workerInstance.postMessage({ code: 3, data: this.context });
  6699. workerInstance.postMessage({ code: 4, data: this.context });
  6700. }, 999)
  6701. }
  6702. //编辑信息
  6703. async doEdit(item: VideoItem) {
  6704. if (!item) {
  6705. return
  6706. }
  6707. if (StrUtil.isEmpty(this.titleStr)) {
  6708. ToastUtil.showToast('标题不能为空')
  6709. return
  6710. }
  6711. //内嵌音乐标签不能开启监听
  6712. // this.deletionWatcher?.stop();
  6713. this.loadingDialogId = DialogHelper.showLoadingDialog()
  6714. await PermissionUtil.activatePermission(item.filePath)
  6715. let tempOutPath = ''
  6716. // 如果不是 packName 包下的文件,则直接路径用this.currentPath
  6717. if(!item.filePath.toLowerCase().includes(this.packName)){
  6718. tempOutPath = this.currentPath + '/' + item.fileName
  6719. }
  6720. console.info('onecold tempOutPath ='+tempOutPath)
  6721. //用户更改了封面,那就内嵌下封面
  6722. if(StrUtil.isNotEmpty(this.imagePathStr)){
  6723. const resultCover:boolean = await changeMusicCover(this.context,
  6724. item.filePath,this.imagePathStr,true,tempOutPath);
  6725. this.imagePathStr = ''
  6726. if(resultCover){
  6727. ToastUtil.showToast('内嵌封面成功')
  6728. }
  6729. }
  6730. const metadata:FFMpegTags = {
  6731. title: this.titleStr,
  6732. artist: this.artistStr,
  6733. album: this.ablumStr,
  6734. TYER:this.yearStr,
  6735. genre:this.genreStr,
  6736. track:this.trackStr,
  6737. album_artist:this.albumArtistStr,
  6738. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  6739. COMPOSER:this.composerStr,
  6740. lyricist:this.lyricistStr,
  6741. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  6742. comment:this.commentStr,
  6743. disc:this.discStr,
  6744. };
  6745. let newInput = item.filePath
  6746. //内嵌标签歌路径如果不是包含包名,输入newInput要赋值tempOutPath,然后tempOutPath为空
  6747. if(!item.filePath.toLowerCase().includes(this.packName)&&FileUtil.accessSync(tempOutPath)){
  6748. newInput = tempOutPath
  6749. tempOutPath = ''
  6750. }
  6751. const isWav:boolean = newInput.toLowerCase().endsWith('.wav');
  6752. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  6753. const result:boolean = await repairAudioMetadata(
  6754. newInput,
  6755. this.lyricConStr,
  6756. metadata,
  6757. true,
  6758. tempOutPath
  6759. );
  6760. if (result||isWav) {
  6761. if(!item.filePath.includes(this.packName)){
  6762. //内嵌成功的歌路径如果不是包含包名,则要入库
  6763. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newInput,
  6764. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  6765. this.table.insert(newItem, (id: number) => {
  6766. //加入数据库
  6767. if(this.modeType==0){
  6768. this.deleteCache(this.currentPath)
  6769. this.getSortedFiles(this.currentPath)
  6770. }
  6771. });
  6772. }
  6773. const task = new taskpool.Task(
  6774. updateInfoDb,
  6775. this.context,
  6776. item.filePath,
  6777. this.titleStr,
  6778. this.artistStr,
  6779. this.ablumStr,
  6780. this.lyricConStr,
  6781. this.yearStr,this.genreStr,
  6782. this.trackStr,this.albumArtistStr,
  6783. this.composerStr, this.lyricistStr,
  6784. this.commentStr,this.discStr
  6785. );
  6786. taskpool.execute(task, taskpool.Priority.HIGH).then((result) => {
  6787. if (result) {
  6788. console.log(" onecold 编辑信息成功,数据库已同步");
  6789. if(isWav){
  6790. ToastUtil.showToast('wav格式有可能内嵌失败,但是编辑信息成功')
  6791. }else{
  6792. ToastUtil.showToast('内嵌音乐标签成功')
  6793. }
  6794. this.isShowMoreView = false
  6795. this.name = this.titleStr
  6796. this.syncEditedFields(item)
  6797. if (item.filePath == this.currentSong?.filePath) {
  6798. this.currentSong.name = this.titleStr
  6799. this.artist = this.artistStr
  6800. this.currentSong.artist = this.artistStr
  6801. this.currentSong.album = this.ablumStr
  6802. this.currentSong.year = this.yearStr
  6803. this.currentSong.genre = this.genreStr
  6804. this.currentSong.track = this.trackStr
  6805. this.currentSong.lyricContent = this.lyricConStr
  6806. this.currentSong.ALBUMARTIST = this.albumArtistStr
  6807. this.currentSong.COMPOSER = this.composerStr
  6808. this.currentSong.LYRICIST = this.lyricistStr
  6809. this.currentSong.COMMENT = this.commentStr
  6810. }
  6811. this.syncListsAfterEdit(item.filePath)
  6812. this.doUpateEditedFields(item)
  6813. //this.doUpdateData()
  6814. } else {
  6815. // ToastUtil.showToast('保存失败' + error?.toString())
  6816. console.error(" onecold 编辑信息数据库失败 ");
  6817. }
  6818. // 关闭进度条
  6819. DialogHelper.closeDialog(this.loadingDialogId)
  6820. }).catch((error: Error) => {
  6821. // 关闭进度条
  6822. DialogHelper.closeDialog(this.loadingDialogId)
  6823. console.error('onecold Subtitle sync failed:', error);
  6824. });
  6825. console.log(' onecold 元数据标签更新成功,');
  6826. } else {
  6827. // 关闭进度条
  6828. DialogHelper.closeDialog(this.loadingDialogId)
  6829. ToastUtil.showToast('内嵌音乐标签失败')
  6830. console.log('onecold 内嵌音乐标签失败');
  6831. }
  6832. this.longItemFilePath = ''
  6833. this.tempLyricContent = ''
  6834. this.isShowEdit = false
  6835. }
  6836. // 内嵌标签更新当前内嵌的Item
  6837. async doUpateEditedFields(item: VideoItem) {
  6838. // 找到当前项在 videoLocalList 中的索引
  6839. const index = this.videoLocalList.findIndex(video => video.filePath === item.filePath);
  6840. if (index !== -1) {
  6841. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  6842. const updatedItem = await this.table.queryVideoByFilePath(item.filePath)
  6843. // 只有当查询结果不为 null 时才更新列表
  6844. if (updatedItem !== null) {
  6845. // 更新 videoLocalList 中的项(通过创建新数组触发响应式更新)
  6846. this.videoLocalList = [
  6847. ...this.videoLocalList.slice(0, index),
  6848. updatedItem,
  6849. ...this.videoLocalList.slice(index + 1)
  6850. ];
  6851. // 同步更新 LazyDataSource
  6852. this.dataSource.pushArrayData(this.videoLocalList)
  6853. } else {
  6854. ToastUtil.showToast('未找到更新的数据');
  6855. }
  6856. }
  6857. DialogHelper.closeDialog(this.loadingDialogId)
  6858. }
  6859. @Builder
  6860. editSheet(item: VideoItem) {
  6861. Scroll() {
  6862. Column() {
  6863. this.editDetail(item)
  6864. }
  6865. }
  6866. .width('100%')
  6867. .height('100%')
  6868. }
  6869. @Builder
  6870. editDetail(item: VideoItem) {
  6871. Column() {
  6872. if (item) {
  6873. Row() {
  6874. Stack() {
  6875. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  6876. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  6877. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  6878. item.pixelMapPath)
  6879. .fillColor(this.themeColor)
  6880. .height(88)
  6881. .width(88)
  6882. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  6883. .borderRadius(12)
  6884. .clip(true)
  6885. .opacity(this.opacityItem)// 绑定透明度
  6886. .margin({ left: 25 })
  6887. }
  6888. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  6889. .onClick(async () => {
  6890. const imagePath:string | undefined = await this.goSelectImage(item);
  6891. if (imagePath) {
  6892. //用户更改过图片
  6893. this.imagePathStr = imagePath
  6894. }
  6895. })
  6896. .width('28%')
  6897. Row() {
  6898. Column() {
  6899. Text(item.name)
  6900. .fontSize(17)
  6901. .maxLines(1)
  6902. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6903. .animation({
  6904. duration: 555,
  6905. curve: 'Linear',
  6906. })
  6907. .fontColor(this.themeColor)
  6908. .margin({ left: 8 })
  6909. Row() {
  6910. Text(item.artist)
  6911. .fontSize(14)
  6912. .maxLines(1)
  6913. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6914. .padding({ top: 8 })
  6915. .fontColor(this.themeColor)
  6916. .margin({ left: 8 })
  6917. }
  6918. }
  6919. .height('100%')
  6920. .width(100)
  6921. .layoutWeight(1)
  6922. .justifyContent(FlexAlign.Center)
  6923. .alignItems(HorizontalAlign.Start)
  6924. Column() {
  6925. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6926. Row(){
  6927. SymbolGlyph($r('sys.symbol.picture'))
  6928. .fontSize(18)
  6929. .fontColor([Color.White])
  6930. Text('获取封面')
  6931. .margin({ left: 4 })
  6932. .fontSize(11)
  6933. .fontColor(Color.White)
  6934. .fontWeight(480)
  6935. .textAlign(TextAlign.Center)
  6936. }
  6937. .justifyContent(FlexAlign.Center)
  6938. }
  6939. .height(38)
  6940. .width(100)
  6941. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6942. .backgroundColor(this.themeColor)
  6943. .stateEffect(true)
  6944. .margin({ right: 35 })
  6945. .onClick(async () => {
  6946. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  6947. this.showTipsDialog();
  6948. return; // Return empty string when no API is configured
  6949. }
  6950. const imagePath:string | undefined = await this.doSearchCover(item,
  6951. this.titleStr,this.artistStr);
  6952. console.info('onecold imagePath = '+imagePath)
  6953. if (StrUtil.isNotEmpty(imagePath)) {
  6954. //用户更改过图片
  6955. this.imagePathStr = imagePath
  6956. ToastUtil.showToast('获取封面成功')
  6957. }else{
  6958. ToastUtil.showToast('获取封面失败,请重试')
  6959. }
  6960. })
  6961. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6962. Row(){
  6963. SymbolGlyph($r('sys.symbol.input_mode'))
  6964. .fontSize(18)
  6965. .fontColor([Color.White])
  6966. Text('获取歌词')
  6967. .margin({ left: 4 })
  6968. .fontSize(11)
  6969. .fontColor(Color.White)
  6970. .fontWeight(480)
  6971. .textAlign(TextAlign.Center)
  6972. }
  6973. .justifyContent(FlexAlign.Center)
  6974. }
  6975. .height(38)
  6976. .width(100)
  6977. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6978. .backgroundColor(this.themeColor)
  6979. .stateEffect(true)
  6980. .margin({ top: 9, right: 35 })
  6981. .onClick(async () => {
  6982. //判断有没有设置api
  6983. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  6984. if (StrUtil.isEmpty(apiUrl)) {
  6985. this.isLyricSetting = false
  6986. this.showTipsDialog()
  6987. return
  6988. }
  6989. let res: string | undefined = await getApiLyric(apiUrl,
  6990. this.titleStr, this.artistStr, false);
  6991. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  6992. this.lyricConStr = res;
  6993. ToastUtil.showToast('获取歌词成功')
  6994. }else{
  6995. ToastUtil.showToast('获取歌词失败,请重试')
  6996. }
  6997. })
  6998. }
  6999. .justifyContent(FlexAlign.Start)
  7000. }
  7001. .height('100%')
  7002. .justifyContent(FlexAlign.Start)
  7003. .layoutWeight(1)
  7004. }
  7005. .width('100%')
  7006. .height(98)
  7007. Row() {
  7008. Text('标题:')
  7009. .fontSize(14)
  7010. .fontColor($r('app.color.text_color'))
  7011. .margin({ left: 22 })
  7012. TextInput({ text: this.titleStr||item.name })
  7013. .height(40)
  7014. .maxLines(1)
  7015. .fontSize(14)
  7016. .layoutWeight(1)
  7017. .fontColor($r('app.color.text_color'))
  7018. .margin({ right: 15, left: 10 })
  7019. .onChange((val: string) => {
  7020. this.titleStr = val
  7021. })
  7022. Button('修复乱码',{ type: ButtonType.Capsule, stateEffect: true})
  7023. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7024. .backgroundColor(this.themeColor)
  7025. .fontSize(10)
  7026. .margin({ right: 20})
  7027. .onClick(async () => {
  7028. let hwTags = await extractHwMediaMetadata(item.filePath)
  7029. let artist = hwTags?.artist|| '';
  7030. let title = hwTags?.title|| '';
  7031. let album = hwTags?.album|| '';
  7032. console.info('onecold 乱码修正 artist='+artist);
  7033. console.info('onecold 乱码修正 title='+title);
  7034. console.info('onecold 乱码修正 album='+album);
  7035. this.titleStr = title;
  7036. this.artistStr = artist;
  7037. this.ablumStr = album;
  7038. })
  7039. }
  7040. .width('100%')
  7041. .margin({ top: 10, bottom: 10 })
  7042. .justifyContent(FlexAlign.Start)
  7043. Row() {
  7044. Text('艺术家:')
  7045. .fontSize(14)
  7046. .fontColor($r('app.color.text_color'))
  7047. .margin({ left: 22 })
  7048. TextInput({ text: this.artistStr||item.artist })
  7049. .height(40)
  7050. .maxLines(1)
  7051. .fontSize(14)
  7052. .layoutWeight(1)
  7053. .fontColor($r('app.color.text_color'))
  7054. .margin({ right: 20, left: 10 })
  7055. .onChange((val: string) => {
  7056. this.artistStr = val
  7057. })
  7058. }
  7059. .width('100%')
  7060. .margin({ top: 10, bottom: 10 })
  7061. .justifyContent(FlexAlign.Start)
  7062. Row() {
  7063. Text('专辑名:')
  7064. .fontSize(14)
  7065. .fontColor($r('app.color.text_color'))
  7066. .margin({ left: 22 })
  7067. TextInput({ text: this.ablumStr||item.album })
  7068. .height(40)
  7069. .maxLines(1)
  7070. .fontSize(14)
  7071. .layoutWeight(1)
  7072. .fontColor($r('app.color.text_color'))
  7073. .margin({ right: 20, left: 10 })
  7074. .onChange((val: string) => {
  7075. this.ablumStr = val
  7076. })
  7077. }
  7078. .width('100%')
  7079. .margin({ top: 10, bottom: 10 })
  7080. .justifyContent(FlexAlign.Start)
  7081. Row() {
  7082. Column(){
  7083. Column(){
  7084. Text('歌词:')
  7085. .fontSize(14)
  7086. .fontColor($r('app.color.text_color'))
  7087. .margin({ top:9,left: 22 })
  7088. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7089. SymbolGlyph($r('sys.symbol.trash_fill'))
  7090. .fontSize(25)
  7091. .alignSelf(ItemAlign.Center)
  7092. .margin({ left: 22,top:25})
  7093. }
  7094. .backgroundColor(Color.Transparent)
  7095. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7096. Visibility.None:Visibility.Visible)
  7097. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7098. .onClick(()=>{
  7099. this.lyricConStr = ''
  7100. this.lyricContent = ''
  7101. this.tempLyricContent = ''
  7102. })
  7103. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7104. SymbolGlyph($r('sys.symbol.plus'))
  7105. .fontSize(25)
  7106. .alignSelf(ItemAlign.Center)
  7107. .margin({ left: 22,top:25})
  7108. }
  7109. .backgroundColor(Color.Transparent)
  7110. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7111. .onClick( ()=>{
  7112. this.callFilePickerSelectFileForLyric()
  7113. })
  7114. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7115. SymbolGlyph($r('sys.symbol.traditional_square'))
  7116. .fontSize(25)
  7117. .alignSelf(ItemAlign.Center)
  7118. .margin({ left: 22,top:25})
  7119. }
  7120. .backgroundColor(Color.Transparent)
  7121. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7122. Visibility.None:Visibility.Visible)
  7123. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7124. .onClick( ()=>{
  7125. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  7126. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  7127. })
  7128. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7129. Image($r('app.media.jianti'))
  7130. .height(25)
  7131. .fillColor($r('app.color.text_color'))
  7132. .alignSelf(ItemAlign.Center)
  7133. .margin({ left: 22,top:25})
  7134. }
  7135. .backgroundColor(Color.Transparent)
  7136. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7137. Visibility.None:Visibility.Visible)
  7138. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7139. .onClick( ()=>{
  7140. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  7141. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  7142. })
  7143. }
  7144. .layoutWeight(1)
  7145. }
  7146. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  7147. this.tempLyricContent })
  7148. .type(TextAreaType.NORMAL)
  7149. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  7150. .fontSize(14)
  7151. .layoutWeight(1)
  7152. .fontColor($r('app.color.text_color'))
  7153. .margin({ right: 20, left: 10 })
  7154. .onChange((val: string) => {
  7155. this.lyricConStr = val
  7156. })
  7157. }
  7158. .width('100%')
  7159. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  7160. .margin({ top: 10, bottom: 10 })
  7161. .justifyContent(FlexAlign.Start)
  7162. Row() {
  7163. Text('年份:')
  7164. .fontSize(14)
  7165. .fontColor($r('app.color.text_color'))
  7166. .margin({ left: 22 })
  7167. TextInput({ text: item.year })
  7168. .height(40)
  7169. .maxLines(1)
  7170. .fontSize(14)
  7171. .type(InputType.Number)
  7172. .layoutWeight(1)
  7173. .fontColor($r('app.color.text_color'))
  7174. .margin({ right: 20, left: 10 })
  7175. .onChange((val: string) => {
  7176. this.yearStr = val
  7177. })
  7178. }
  7179. .width('100%')
  7180. .margin({ top: 10, bottom: 10 })
  7181. .justifyContent(FlexAlign.Start)
  7182. Row() {
  7183. Text('音轨号:')
  7184. .fontSize(14)
  7185. .fontColor($r('app.color.text_color'))
  7186. .margin({ left: 22 })
  7187. TextInput({ text:item.track=='未知'?'': item.track })
  7188. .height(40)
  7189. .maxLines(1)
  7190. .fontSize(14)
  7191. .type(InputType.Number)
  7192. .layoutWeight(1)
  7193. .fontColor($r('app.color.text_color'))
  7194. .margin({ right: 20, left: 10 })
  7195. .onChange((val: string) => {
  7196. this.trackStr = val
  7197. })
  7198. }
  7199. .width('100%')
  7200. .margin({ top: 10, bottom: 10 })
  7201. .justifyContent(FlexAlign.Start)
  7202. Row() {
  7203. Text('碟号:')
  7204. .fontSize(14)
  7205. .fontColor($r('app.color.text_color'))
  7206. .margin({ left: 22 })
  7207. TextInput({ text:item.disc })
  7208. .height(40)
  7209. .maxLines(1)
  7210. .fontSize(14)
  7211. .type(InputType.Number)
  7212. .layoutWeight(1)
  7213. .fontColor($r('app.color.text_color'))
  7214. .margin({ right: 20, left: 10 })
  7215. .onChange((val: string) => {
  7216. this.discStr = val
  7217. })
  7218. }
  7219. .width('100%')
  7220. .margin({ top: 10, bottom: 10 })
  7221. .justifyContent(FlexAlign.Start)
  7222. Row() {
  7223. Text('风格:')
  7224. .fontSize(14)
  7225. .fontColor($r('app.color.text_color'))
  7226. .margin({ left: 22 })
  7227. TextInput({ text: item.genre })
  7228. .height(40)
  7229. .maxLines(1)
  7230. .fontSize(14)
  7231. .layoutWeight(1)
  7232. .fontColor($r('app.color.text_color'))
  7233. .margin({ right: 20, left: 10 })
  7234. .onChange((val: string) => {
  7235. this.genreStr = val
  7236. })
  7237. }
  7238. .width('100%')
  7239. .margin({ top: 10, bottom: 10 })
  7240. .justifyContent(FlexAlign.Start)
  7241. Row() {
  7242. Text('专辑艺术家:')
  7243. .fontSize(14)
  7244. .fontColor($r('app.color.text_color'))
  7245. .margin({ left: 22 })
  7246. TextInput({ text: item.ALBUMARTIST })
  7247. .height(40)
  7248. .maxLines(1)
  7249. .fontSize(14)
  7250. .layoutWeight(1)
  7251. .fontColor($r('app.color.text_color'))
  7252. .margin({ right: 20, left: 10 })
  7253. .onChange((val: string) => {
  7254. this.albumArtistStr = val
  7255. })
  7256. }
  7257. .width('100%')
  7258. .margin({ top: 10, bottom: 10 })
  7259. .justifyContent(FlexAlign.Start)
  7260. Row() {
  7261. Text('作曲:')
  7262. .fontSize(14)
  7263. .fontColor($r('app.color.text_color'))
  7264. .margin({ left: 22 })
  7265. TextInput({ text: item.COMPOSER })
  7266. .height(40)
  7267. .maxLines(1)
  7268. .fontSize(14)
  7269. .layoutWeight(1)
  7270. .fontColor($r('app.color.text_color'))
  7271. .margin({ right: 20, left: 10 })
  7272. .onChange((val: string) => {
  7273. this.composerStr = val
  7274. })
  7275. }
  7276. .width('100%')
  7277. .margin({ top: 10, bottom: 10 })
  7278. .justifyContent(FlexAlign.Start)
  7279. Row() {
  7280. Text('作词:')
  7281. .fontSize(14)
  7282. .fontColor($r('app.color.text_color'))
  7283. .margin({ left: 22 })
  7284. TextInput({ text: item.LYRICIST })
  7285. .height(40)
  7286. .maxLines(1)
  7287. .fontSize(14)
  7288. .layoutWeight(1)
  7289. .fontColor($r('app.color.text_color'))
  7290. .margin({ right: 20, left: 10 })
  7291. .onChange((val: string) => {
  7292. this.lyricistStr = val
  7293. })
  7294. }
  7295. .width('100%')
  7296. .margin({ top: 10, bottom: 10 })
  7297. .justifyContent(FlexAlign.Start)
  7298. Row() {
  7299. Text('注释:')
  7300. .fontSize(14)
  7301. .fontColor($r('app.color.text_color'))
  7302. .margin({ left: 22 })
  7303. TextInput({ text: item.COMMENT })
  7304. .height(40)
  7305. .maxLines(1)
  7306. .fontSize(14)
  7307. .layoutWeight(1)
  7308. .fontColor($r('app.color.text_color'))
  7309. .margin({ right: 20, left: 10 })
  7310. .onChange((val: string) => {
  7311. this.commentStr = val
  7312. })
  7313. }
  7314. .width('100%')
  7315. .margin({ top: 10, bottom: 10 })
  7316. .justifyContent(FlexAlign.Start)
  7317. Row() {
  7318. Button('保存')
  7319. .fontColor(Color.White)
  7320. .layoutWeight(1)
  7321. .height(50)
  7322. .width(100)
  7323. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7324. .backgroundColor(this.themeColor)
  7325. .stateEffect(true)
  7326. .margin({ right: 20, bottom: 20 })
  7327. .onClick(async () => {
  7328. this.doEdit(item)
  7329. })
  7330. Button('取消')
  7331. .fontColor(Color.White)
  7332. .layoutWeight(1)
  7333. .height(50)
  7334. .width(100)
  7335. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7336. .backgroundColor(this.themeColor)
  7337. .stateEffect(true)
  7338. .margin({ left: 20, bottom: 20 })
  7339. .onClick(async () => {
  7340. if(this.isGridMusic){
  7341. this.longItemFilePath =''
  7342. }else{
  7343. this.isShowEdit = false
  7344. }
  7345. this.setEditStrEmpty()
  7346. if(this.isShowPlay){
  7347. this.isShowEdit = false
  7348. }
  7349. })
  7350. }
  7351. .margin({
  7352. left: 38,
  7353. right: 38,
  7354. top: 10,
  7355. bottom: 10
  7356. })
  7357. .width(250)
  7358. .height(60)
  7359. }
  7360. }
  7361. .margin({ bottom: 20 })
  7362. }
  7363. setEditStrEmpty(){
  7364. this.imagePathStr = ''
  7365. this.lyricConStr = ''
  7366. this.artistStr = ''
  7367. this.titleStr = ''
  7368. this.ablumStr = ''
  7369. this.genreStr = ''
  7370. this.yearStr = ''
  7371. this.trackStr = ''
  7372. this.albumArtistStr = ''
  7373. this.composerStr = ''
  7374. this.lyricistStr = ''
  7375. this.commentStr = ''
  7376. this.discStr = ''
  7377. }
  7378. initEditFields(item?: VideoItem) {
  7379. if (!item) {
  7380. this.setEditStrEmpty()
  7381. return
  7382. }
  7383. this.imagePathStr = ''
  7384. this.titleStr = item.name ?? ''
  7385. this.artistStr = item.artist ?? ''
  7386. this.ablumStr = item.album ?? ''
  7387. this.genreStr = item.genre ?? ''
  7388. this.yearStr = item.year ?? ''
  7389. this.trackStr = item.track ?? ''
  7390. this.albumArtistStr = item.ALBUMARTIST ?? ''
  7391. this.composerStr = item.COMPOSER ?? ''
  7392. this.lyricistStr = item.LYRICIST ?? ''
  7393. this.commentStr = item.COMMENT ?? ''
  7394. this.discStr = item.disc ?? ''
  7395. this.lyricConStr = item.lyricContent ?? ''
  7396. }
  7397. private syncEditedFields(target?: VideoItem) {
  7398. if (!target) {
  7399. return
  7400. }
  7401. target.name = this.titleStr
  7402. target.artist = this.artistStr
  7403. target.album = this.ablumStr
  7404. target.lyricContent = this.lyricConStr
  7405. target.year = this.yearStr
  7406. target.genre = this.genreStr
  7407. target.track = this.trackStr
  7408. target.ALBUMARTIST = this.albumArtistStr
  7409. target.COMPOSER = this.composerStr
  7410. target.LYRICIST = this.lyricistStr
  7411. target.COMMENT = this.commentStr
  7412. target.disc = this.discStr
  7413. }
  7414. private replaceItemInList(list: Array<VideoItem> | undefined, filePath: string,
  7415. apply?: (next: Array<VideoItem>) => void) {
  7416. if (!list || ArrayUtil.isEmpty(list)) {
  7417. return
  7418. }
  7419. const index = list.findIndex((video: VideoItem) => video.filePath === filePath)
  7420. if (index < 0) {
  7421. return
  7422. }
  7423. const nextList = [...list]
  7424. this.syncEditedFields(nextList[index])
  7425. apply?.(nextList)
  7426. }
  7427. private syncListsAfterEdit(filePath: string) {
  7428. this.replaceItemInList(this.videoLocalList, filePath, (next: Array<VideoItem>) => {
  7429. this.videoLocalList = next
  7430. this.dataSource.pushArrayData(next)
  7431. })
  7432. this.replaceItemInList(this.songList, filePath, (next: Array<VideoItem>) => {
  7433. this.songList = next
  7434. this.sonDataSource.pushArrayData(next)
  7435. })
  7436. this.replaceItemInList(this.favList, filePath, (next: Array<VideoItem>) => {
  7437. this.favList = next
  7438. })
  7439. this.replaceItemInList(this.historyList, filePath, (next: Array<VideoItem>) => {
  7440. this.historyList = next
  7441. })
  7442. this.replaceItemInList(this.currentSongList, filePath, (next: Array<VideoItem>) => {
  7443. this.currentSongList = next
  7444. })
  7445. this.replaceItemInList(this.mediaKuList, filePath, (next: Array<VideoItem>) => {
  7446. this.mediaKuList = next
  7447. })
  7448. this.replaceItemInList(this.filteredList, filePath, (next: Array<VideoItem>) => {
  7449. this.filteredList = next
  7450. })
  7451. this.replaceItemInList(this.artistList, filePath, (next: Array<VideoItem>) => {
  7452. this.artistList = next
  7453. })
  7454. this.replaceItemInList(this.albumList, filePath, (next: Array<VideoItem>) => {
  7455. this.albumList = next
  7456. })
  7457. this.listRefreshKey++
  7458. }
  7459. private refreshLazyListViews(mainListUpdated: boolean, playlistUpdated: boolean): void {
  7460. if (!mainListUpdated && !playlistUpdated) {
  7461. return;
  7462. }
  7463. this.listRefreshKey++;
  7464. if (mainListUpdated) {
  7465. this.dataSource.notifyDataReload();
  7466. }
  7467. if (playlistUpdated) {
  7468. this.sonDataSource.notifyDataReload();
  7469. }
  7470. }
  7471. @Builder
  7472. detailSheet(item:VideoItem) {
  7473. Scroll() {
  7474. Column() {
  7475. this.songDetail(item)
  7476. }
  7477. }
  7478. .width('100%')
  7479. .height('100%')
  7480. }
  7481. @Builder
  7482. songDetail(currentItem:VideoItem) {
  7483. Column() {
  7484. if (currentItem) {
  7485. Row() {
  7486. Stack() {
  7487. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.alt') :
  7488. currentItem.pixelMapPath)
  7489. .fillColor(this.themeColor)
  7490. .height(80)
  7491. .width(80)
  7492. .borderRadius(10)
  7493. .opacity(this.opacityItem)// 绑定透明度
  7494. .margin({ left: 22 })
  7495. }
  7496. Column() {
  7497. Column() {
  7498. Text(currentItem.name)
  7499. .fontSize(16)
  7500. .maxLines(1)
  7501. .animation({
  7502. duration: 555,
  7503. curve: 'Linear',
  7504. })
  7505. .fontColor($r('app.color.text_color'))
  7506. .margin({ left: 15 })
  7507. }
  7508. .height('100%')
  7509. .width('100%')
  7510. .justifyContent(FlexAlign.Center)
  7511. .alignItems(HorizontalAlign.Start)
  7512. }
  7513. .height('100%')
  7514. }
  7515. .width('100%')
  7516. .height(90)
  7517. .justifyContent(FlexAlign.SpaceBetween)
  7518. Row() {
  7519. Text('艺术家:')
  7520. .fontSize(14)
  7521. .fontColor($r('app.color.text_color'))
  7522. .margin({ left: 22 })
  7523. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  7524. .fontSize(14)
  7525. .fontColor($r('app.color.text_color'))
  7526. .margin({ left: 10 })
  7527. .layoutWeight(1)
  7528. }
  7529. .width('100%')
  7530. .margin({ top: 10, bottom: 10 })
  7531. .justifyContent(FlexAlign.Start)
  7532. Row() {
  7533. Text('专辑名:')
  7534. .fontSize(14)
  7535. .fontColor($r('app.color.text_color'))
  7536. .margin({ left: 22 })
  7537. Text(currentItem?.album ?currentItem.album : '未知专辑')
  7538. .fontSize(14)
  7539. .margin({ left: 10 })
  7540. .fontColor($r('app.color.text_color'))
  7541. .layoutWeight(1)
  7542. }
  7543. .width('100%')
  7544. .margin({ top: 10, bottom: 10 })
  7545. .justifyContent(FlexAlign.Start)
  7546. Row() {
  7547. Text('时长:')
  7548. .fontSize(14)
  7549. .fontColor($r('app.color.text_color'))
  7550. .margin({ left: 22 })
  7551. Text(StrUtil.isEmpty(currentItem.duration)?
  7552. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  7553. .fontSize(14)
  7554. .margin({ left: 10 })
  7555. .fontColor($r('app.color.text_color'))
  7556. .layoutWeight(1)
  7557. }
  7558. .width('100%')
  7559. .margin({ top: 10, bottom: 10 })
  7560. .justifyContent(FlexAlign.Start)
  7561. Row() {
  7562. Text('采样率:')
  7563. .fontSize(14)
  7564. .fontColor($r('app.color.text_color'))
  7565. .margin({ left: 22 })
  7566. Text(Utility.convertToKHz(currentItem.sampleRate))
  7567. .fontSize(14)
  7568. .margin({ left: 10 })
  7569. .fontColor($r('app.color.text_color'))
  7570. .layoutWeight(1)
  7571. }
  7572. .width('100%')
  7573. .margin({ top: 10, bottom: 10 })
  7574. .justifyContent(FlexAlign.Start)
  7575. Row() {
  7576. Text('比特率:')
  7577. .fontSize(14)
  7578. .fontColor($r('app.color.text_color'))
  7579. .margin({ left: 22 })
  7580. Text(currentItem.bit_rate)
  7581. .fontSize(14)
  7582. .margin({ left: 10 })
  7583. .fontColor($r('app.color.text_color'))
  7584. .layoutWeight(1)
  7585. }
  7586. .width('100%')
  7587. .margin({ top: 10, bottom: 10 })
  7588. .justifyContent(FlexAlign.Start)
  7589. Row() {
  7590. Text('位深:')
  7591. .fontSize(14)
  7592. .fontColor($r('app.color.text_color'))
  7593. .margin({ left: 22 })
  7594. Text(`${currentItem.bits_per_raw_sample} bits`)
  7595. .fontSize(14)
  7596. .margin({ left: 10 })
  7597. .fontColor($r('app.color.text_color'))
  7598. .layoutWeight(1)
  7599. }
  7600. .width('100%')
  7601. .margin({ top: 10, bottom: 10 })
  7602. .justifyContent(FlexAlign.Start)
  7603. Row() {
  7604. Text('声道:')
  7605. .fontSize(14)
  7606. .fontColor($r('app.color.text_color'))
  7607. .margin({ left: 22 })
  7608. Text(`${currentItem.channels}`)
  7609. .fontSize(14)
  7610. .margin({ left: 10 })
  7611. .fontColor($r('app.color.text_color'))
  7612. .layoutWeight(1)
  7613. }
  7614. .width('100%')
  7615. .margin({ top: 10, bottom: 10 })
  7616. .justifyContent(FlexAlign.Start)
  7617. Row() {
  7618. Text('声道布局:')
  7619. .fontSize(14)
  7620. .fontColor($r('app.color.text_color'))
  7621. .margin({ left: 22 })
  7622. Text(`${currentItem.channel_layout}`)
  7623. .fontSize(14)
  7624. .margin({ left: 10 })
  7625. .fontColor($r('app.color.text_color'))
  7626. .layoutWeight(1)
  7627. }
  7628. .width('100%')
  7629. .margin({ top: 10, bottom: 10 })
  7630. .justifyContent(FlexAlign.Start)
  7631. Row() {
  7632. Text('起始播放点:')
  7633. .fontSize(14)
  7634. .fontColor($r('app.color.text_color'))
  7635. .margin({ left: 22 })
  7636. Text(`${currentItem.start_time}`)
  7637. .fontSize(14)
  7638. .margin({ left: 10 })
  7639. .fontColor($r('app.color.text_color'))
  7640. .layoutWeight(1)
  7641. }
  7642. .width('100%')
  7643. .margin({ top: 10, bottom: 10 })
  7644. .justifyContent(FlexAlign.Start)
  7645. Row() {
  7646. Text('风格:')
  7647. .fontSize(14)
  7648. .fontColor($r('app.color.text_color'))
  7649. .margin({ left: 22 })
  7650. Text(currentItem.genre)
  7651. .fontSize(14)
  7652. .margin({ left: 10 })
  7653. .fontColor($r('app.color.text_color'))
  7654. .layoutWeight(1)
  7655. }
  7656. .width('100%')
  7657. .margin({ top: 10, bottom: 10 })
  7658. .justifyContent(FlexAlign.Start)
  7659. Row() {
  7660. Text('发行时间:')
  7661. .fontSize(14)
  7662. .fontColor($r('app.color.text_color'))
  7663. .margin({ left: 22 })
  7664. Text(currentItem.year)
  7665. .fontSize(14)
  7666. .margin({ left: 10 })
  7667. .fontColor($r('app.color.text_color'))
  7668. .layoutWeight(1)
  7669. }
  7670. .width('100%')
  7671. .margin({ top: 10, bottom: 10 })
  7672. .justifyContent(FlexAlign.Start)
  7673. Row() {
  7674. Text('质量评分:')
  7675. .fontSize(14)
  7676. .fontColor($r('app.color.text_color'))
  7677. .margin({ left: 22 })
  7678. Text(currentItem.probe_score+"")
  7679. .fontSize(14)
  7680. .margin({ left: 10 })
  7681. .fontColor($r('app.color.text_color'))
  7682. .layoutWeight(1)
  7683. }
  7684. .width('100%')
  7685. .margin({ top: 10, bottom: 10 })
  7686. .justifyContent(FlexAlign.Start)
  7687. Row() {
  7688. Text('音轨号:')
  7689. .fontSize(14)
  7690. .fontColor($r('app.color.text_color'))
  7691. .margin({ left: 22 })
  7692. Text(currentItem.track)
  7693. .fontSize(14)
  7694. .margin({ left: 10 })
  7695. .fontColor($r('app.color.text_color'))
  7696. .layoutWeight(1)
  7697. }
  7698. .width('100%')
  7699. .margin({ top: 10, bottom: 10 })
  7700. .justifyContent(FlexAlign.Start)
  7701. Row() {
  7702. Text('碟号:')
  7703. .fontSize(14)
  7704. .fontColor($r('app.color.text_color'))
  7705. .margin({ left: 22 })
  7706. Text(currentItem.disc)
  7707. .fontSize(14)
  7708. .margin({ left: 10 })
  7709. .fontColor($r('app.color.text_color'))
  7710. .layoutWeight(1)
  7711. }
  7712. .width('100%')
  7713. .margin({ top: 10, bottom: 10 })
  7714. .justifyContent(FlexAlign.Start)
  7715. Row() {
  7716. Text('专辑艺术家:')
  7717. .fontSize(14)
  7718. .fontColor($r('app.color.text_color'))
  7719. .margin({ left: 22 })
  7720. Text(currentItem.ALBUMARTIST)
  7721. .fontSize(14)
  7722. .margin({ left: 10 })
  7723. .fontColor($r('app.color.text_color'))
  7724. .layoutWeight(1)
  7725. }
  7726. .width('100%')
  7727. .margin({ top: 10, bottom: 10 })
  7728. .justifyContent(FlexAlign.Start)
  7729. Row() {
  7730. Text('作曲家:')
  7731. .fontSize(14)
  7732. .fontColor($r('app.color.text_color'))
  7733. .margin({ left: 22 })
  7734. Text(currentItem.COMPOSER)
  7735. .fontSize(14)
  7736. .margin({ left: 10 })
  7737. .fontColor($r('app.color.text_color'))
  7738. .layoutWeight(1)
  7739. }
  7740. .width('100%')
  7741. .margin({ top: 10, bottom: 10 })
  7742. .justifyContent(FlexAlign.Start)
  7743. Row() {
  7744. Text('作词家:')
  7745. .fontSize(14)
  7746. .fontColor($r('app.color.text_color'))
  7747. .margin({ left: 22 })
  7748. Text(currentItem.LYRICIST)
  7749. .fontSize(14)
  7750. .margin({ left: 10 })
  7751. .fontColor($r('app.color.text_color'))
  7752. .layoutWeight(1)
  7753. }
  7754. .width('100%')
  7755. .margin({ top: 10, bottom: 10 })
  7756. .justifyContent(FlexAlign.Start)
  7757. Row() {
  7758. Text('注释:')
  7759. .fontSize(14)
  7760. .fontColor($r('app.color.text_color'))
  7761. .margin({ left: 22 })
  7762. Text(currentItem.COMMENT)
  7763. .fontSize(14)
  7764. .margin({ left: 10 })
  7765. .fontColor($r('app.color.text_color'))
  7766. .layoutWeight(1)
  7767. }
  7768. .width('100%')
  7769. .margin({ top: 10, bottom: 10 })
  7770. .justifyContent(FlexAlign.Start)
  7771. Row() {
  7772. Text('格式:')
  7773. .fontSize(14)
  7774. .fontColor($r('app.color.text_color'))
  7775. .margin({ left: 22 })
  7776. Text(Utility.formatMimeType(currentItem.mimeType))
  7777. .fontSize(14)
  7778. .margin({ left: 10 })
  7779. .fontColor($r('app.color.text_color'))
  7780. .layoutWeight(1)
  7781. }
  7782. .width('100%')
  7783. .margin({ top: 10, bottom: 10 })
  7784. .justifyContent(FlexAlign.Start)
  7785. Row() {
  7786. Text('播放次数:')
  7787. .fontSize(14)
  7788. .fontColor($r('app.color.text_color'))
  7789. .margin({ left: 22 })
  7790. Text(currentItem.playCount?.toString())
  7791. .fontSize(14)
  7792. .margin({ left: 10 })
  7793. .fontColor($r('app.color.text_color'))
  7794. .layoutWeight(1)
  7795. }
  7796. .width('100%')
  7797. .margin({ top: 10, bottom: 10 })
  7798. .justifyContent(FlexAlign.Start)
  7799. Row() {
  7800. Text('流数量:')
  7801. .fontSize(14)
  7802. .fontColor($r('app.color.text_color'))
  7803. .margin({ left: 22 })
  7804. Text(currentItem.nb_streams?.toString())
  7805. .fontSize(14)
  7806. .margin({ left: 10 })
  7807. .fontColor($r('app.color.text_color'))
  7808. .layoutWeight(1)
  7809. }
  7810. .width('100%')
  7811. .margin({ top: 10, bottom: 10 })
  7812. .justifyContent(FlexAlign.Start)
  7813. Row() {
  7814. Text('文件大小:')
  7815. .fontSize(14)
  7816. .fontColor($r('app.color.text_color'))
  7817. .margin({ left: 22 })
  7818. Text(currentItem.size)
  7819. .fontSize(14)
  7820. .margin({ left: 10 })
  7821. .fontColor($r('app.color.text_color'))
  7822. .layoutWeight(1)
  7823. }
  7824. .width('100%')
  7825. .margin({ top: 10, bottom: 10 })
  7826. .justifyContent(FlexAlign.Start)
  7827. Row() {
  7828. Text('文件名:')
  7829. .fontSize(14)
  7830. .fontColor($r('app.color.text_color'))
  7831. .margin({ left: 22 })
  7832. Text(currentItem.fileName)
  7833. .fontSize(14)
  7834. .margin({ left: 10 })
  7835. .fontColor($r('app.color.text_color'))
  7836. .layoutWeight(1)
  7837. }
  7838. .width('100%')
  7839. .margin({ top: 10, bottom: 10 })
  7840. .justifyContent(FlexAlign.Start)
  7841. Row() {
  7842. Text('修改时间:')
  7843. .fontSize(14)
  7844. .fontColor($r('app.color.text_color'))
  7845. .margin({ left: 22 })
  7846. Text(currentItem.cTime)
  7847. .fontSize(14)
  7848. .margin({ left: 10 })
  7849. .fontColor($r('app.color.text_color'))
  7850. .layoutWeight(1)
  7851. }
  7852. .width('100%')
  7853. .margin({ top: 10, bottom: 10 })
  7854. .justifyContent(FlexAlign.Start)
  7855. Row() {
  7856. Text('存放目录:')
  7857. .fontSize(14)
  7858. .fontColor($r('app.color.text_color'))
  7859. .margin({ left: 22 })
  7860. Text(currentItem.filePath)
  7861. .fontSize(12)
  7862. .margin({ left: 10 })
  7863. .fontColor($r('app.color.text_color'))
  7864. .layoutWeight(1)
  7865. }
  7866. .margin({ top: 10, bottom: 10 })
  7867. .width('100%')
  7868. .justifyContent(FlexAlign.Start)
  7869. Row() {
  7870. Text('内嵌歌词:')
  7871. .fontSize(14)
  7872. .fontColor($r('app.color.text_color'))
  7873. .margin({ left: 22 })
  7874. Text(currentItem.lyricContent)
  7875. .fontSize(12)
  7876. .copyOption(CopyOptions.InApp)
  7877. .margin({ left: 10 })
  7878. .fontColor($r('app.color.text_color'))
  7879. .layoutWeight(1)
  7880. }
  7881. .margin({ top: 10, bottom: 10 })
  7882. .width('100%')
  7883. .justifyContent(FlexAlign.Start)
  7884. }
  7885. }
  7886. .margin({ bottom: 20 })
  7887. }
  7888. //定时关闭布局
  7889. @Builder
  7890. TimeCloseSheet() {
  7891. Scroll() {
  7892. Column() {
  7893. this.TimeClose()
  7894. }
  7895. }
  7896. .width('100%')
  7897. .height('100%')
  7898. }
  7899. //倒计时关闭音乐,退出App功能实现。
  7900. @State selectedMinutes: number = 0 // 0表示未开启
  7901. @State remainingSeconds: number = 0
  7902. // 预设时间选项
  7903. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  7904. private formatTime(seconds: number): string {
  7905. const mins = Math.floor(seconds / 60)
  7906. const secs = seconds % 60
  7907. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  7908. }
  7909. // 开始倒计时
  7910. private handleTimeSelect(minutes: number) {
  7911. if (minutes === this.selectedMinutes) {
  7912. this.stopCountdown();
  7913. this.selectedMinutes = 0;
  7914. return;
  7915. }
  7916. this.selectedMinutes = minutes;
  7917. this.remainingSeconds = minutes * 60;
  7918. this.startCountdown(); // 新增调用
  7919. }
  7920. @Builder
  7921. TimeClose() {
  7922. Column() {
  7923. // 倒计时显示区域
  7924. Text(this.selectedMinutes > 0 ?
  7925. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  7926. "定时关闭未开启")
  7927. .fontSize(17)
  7928. .fontColor($r('app.color.text_color'))
  7929. .margin({ top: 2, bottom: 8 });
  7930. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  7931. ForEach(this.presetTimes, (minutes: number, index: number) => {
  7932. // 单行时间选项容器
  7933. Row() {
  7934. // 文字描述区域
  7935. Text(this.getDisplayText(minutes))
  7936. .fontSize(15)
  7937. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  7938. $r('app.color.text_color'))// 选中态颜色变化
  7939. .textAlign(TextAlign.Start)
  7940. .layoutWeight(1); // 占据剩余空间
  7941. // 复选框样式的选择器
  7942. Row() {
  7943. if (minutes === this.selectedMinutes) {
  7944. // 选中状态 - 带勾号的圆形复选框
  7945. Row() {
  7946. // 使用系统内置的勾号图标
  7947. Image($r('sys.media.ohos_ic_public_ok'))
  7948. .width(14)
  7949. .height(14)
  7950. .fillColor(Color.White)
  7951. }
  7952. .width(24)
  7953. .height(24)
  7954. .borderRadius(12)
  7955. .backgroundColor(this.themeColor)
  7956. .justifyContent(FlexAlign.Center)
  7957. .alignItems(VerticalAlign.Center)
  7958. } else {
  7959. // 未选中状态的圆形边框
  7960. Row()
  7961. .width(24)
  7962. .height(24)
  7963. .borderRadius(12)
  7964. .border({
  7965. width: 2,
  7966. color: $r('app.color.text_color'),
  7967. style: BorderStyle.Solid
  7968. })
  7969. .backgroundColor(Color.Transparent)
  7970. }
  7971. }
  7972. .width(24)
  7973. .height(24)
  7974. .margin({ left: 20 })
  7975. .justifyContent(FlexAlign.Center)
  7976. .alignItems(VerticalAlign.Center)
  7977. }
  7978. .width('100%')
  7979. .padding({
  7980. top: 18,
  7981. bottom: 18,
  7982. left: 18,
  7983. right: 18
  7984. })
  7985. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  7986. $r('app.color.bottom_control_background')) // 选中背景高亮
  7987. .borderRadius(12)
  7988. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7989. .margin({ bottom: 18 })
  7990. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  7991. });
  7992. }
  7993. .width('100%')
  7994. .padding(16)
  7995. }
  7996. }
  7997. // 获取显示文本
  7998. private getDisplayText(minutes: number): string {
  7999. if (minutes === -1) {
  8000. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  8001. }
  8002. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  8003. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  8004. }
  8005. // 处理选择事件
  8006. private handleSelect(minutes: number): void {
  8007. if (minutes === -1) { // 自定义
  8008. // 弹出自定义时间对话框
  8009. DialogHelper.showTextInputDialog({
  8010. title: '自定义时间',
  8011. maskColor: Color.Transparent,
  8012. inputType: InputType.Number,
  8013. text: '',
  8014. onChange: (text) => {
  8015. console.error("onChange: " + text);
  8016. },
  8017. onAction: (action, dialogId, content) => {
  8018. if (action == DialogAction.TWO) {
  8019. const customMinutes = Number(content);
  8020. if (customMinutes > 0) {
  8021. this.handleTimeSelect(customMinutes); // 设置自定义时间
  8022. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  8023. }
  8024. }
  8025. }
  8026. });
  8027. } else {
  8028. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  8029. }
  8030. }
  8031. // 添加定时器引用
  8032. private timerId: number = -1;
  8033. // 启动/重置倒计时
  8034. private startCountdown() {
  8035. // 清除旧定时器
  8036. if (this.timerId !== -1) {
  8037. clearInterval(this.timerId);
  8038. }
  8039. // 创建新定时器
  8040. if (this.selectedMinutes > 0) {
  8041. this.timerId = setInterval(() => {
  8042. if (this.remainingSeconds === 15) {
  8043. this.showConfirmationDialog();
  8044. }
  8045. if (this.remainingSeconds > 0) {
  8046. this.remainingSeconds -= 1;
  8047. } else {
  8048. this.stopCountdown();
  8049. this.handleTimeout();
  8050. }
  8051. }, 1000);
  8052. }
  8053. }
  8054. // 15倒计时后再次提示显示确认是否关闭App对话框
  8055. private showConfirmationDialog() {
  8056. DialogHelper.showAlertDialog({
  8057. backgroundColor: $r('app.color.btn_green'),
  8058. title: '确认关闭',
  8059. maskColor: Color.Transparent,
  8060. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  8061. borderStyle: BorderStyle.Dashed,
  8062. primaryButton: '暂不关闭',
  8063. secondaryButton: '确定',
  8064. onAction: (action) => {
  8065. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  8066. this.stopCountdown();
  8067. this.selectedMinutes = 0
  8068. } else if (action == DialogAction.TWO) {
  8069. }
  8070. }
  8071. })
  8072. }
  8073. // 停止倒计时
  8074. private stopCountdown() {
  8075. if (this.timerId !== -1) {
  8076. clearInterval(this.timerId);
  8077. this.timerId = -1;
  8078. }
  8079. }
  8080. // 超时处理
  8081. private handleTimeout() {
  8082. // 执行播放器关闭逻辑
  8083. this.selectedMinutes = 0;
  8084. ToastUtil.showToast(" 定时关闭已完成");
  8085. this.stop(); // 假设存在的播放器实例
  8086. //退出APP
  8087. const mContext = getContext(this) as common.UIAbilityContext
  8088. mContext.terminateSelf();
  8089. AvSessionController.getInstance(true).unregisterSessionListener()
  8090. }
  8091. //倒计时关闭音乐,退出App功能实现结束。
  8092. //播放列表的拖动List 重新排序
  8093. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  8094. //左滑操作 移动文件 重命名 删除等操作
  8095. @Builder
  8096. sonButton(item: VideoItem, index: number, filePath: string) {
  8097. Row() {
  8098. //加入下一首播放
  8099. Button() {
  8100. Image($r('app.media.next_to_play'))
  8101. .fillColor(Color.White)
  8102. .width(20)
  8103. }
  8104. .width(40)
  8105. .height(40)
  8106. .type(ButtonType.Circle)
  8107. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8108. .backgroundColor(this.themeColor)
  8109. .margin(5)
  8110. .onClick(() => {
  8111. this.addToNextPlay(item);
  8112. })
  8113. Button() {
  8114. Image($r('app.media.close'))
  8115. .fillColor(Color.White)
  8116. .width(20)
  8117. }
  8118. .width(40)
  8119. .height(40)
  8120. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8121. .type(ButtonType.Circle)
  8122. .backgroundColor(this.themeColor)
  8123. .margin(5)
  8124. .onClick(() => {
  8125. this.songList.splice(Number(index), 1)
  8126. this.sonDataSource.pushArrayData(this.songList)
  8127. })
  8128. Button() {
  8129. Image($r('app.media.share2'))
  8130. .fillColor(Color.White)
  8131. .width(20)
  8132. }
  8133. .width(40)
  8134. .height(40)
  8135. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8136. .type(ButtonType.Circle)
  8137. .backgroundColor(this.themeColor)
  8138. .margin(5)
  8139. .onClick(() => {
  8140. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  8141. })
  8142. }
  8143. }
  8144. itemMoveSon(index: number, newIndex: number): void {
  8145. if (newIndex < 0 || newIndex >= this.songList.length) {
  8146. return;
  8147. }
  8148. let tmp = this.songList.splice(index, 1);
  8149. this.songList.splice(newIndex, 0, tmp[0]);
  8150. this.sonDataSource.pushArrayData(this.songList)
  8151. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  8152. if(this.modeType==4&&this.playlistTable){
  8153. updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
  8154. }
  8155. }
  8156. @Builder
  8157. PlayList() {
  8158. List({ scroller: this.playListScroller }) {
  8159. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  8160. ListItem() {
  8161. this.MusicItemSon(item, index)
  8162. }
  8163. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  8164. .animation({
  8165. duration: 666,
  8166. curve: 'ease-in-out' // 可选动画曲线
  8167. })
  8168. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 600 }),
  8169. TransitionEffect.scale({ x: 0, y: 0 })))
  8170. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  8171. //拖动List关键代码开始
  8172. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  8173. .zIndex(this.dragItem === index ? 1 : 0)
  8174. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  8175. .gesture(
  8176. GestureGroup(GestureMode.Sequence,
  8177. LongPressGesture({ repeat: true })
  8178. .onAction((event?: GestureEvent) => {
  8179. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  8180. this.scaleItem = index
  8181. })
  8182. })
  8183. .onActionEnd(() => {
  8184. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  8185. this.scaleItem = -1
  8186. })
  8187. }),
  8188. PanGesture({ fingers: 1, direction: null, distance: 0 })
  8189. .onActionStart(() => {
  8190. this.dragItem = index // 记录当前拖动项索引
  8191. this.dragRefOffset = 0 // 重置偏移基准
  8192. })
  8193. .onActionUpdate((event: GestureEvent) => {
  8194. this.offsetY = event.offsetY - this.dragRefOffset;
  8195. this.neighborItem = -1;
  8196. let indexA = this.songList.indexOf(item);
  8197. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  8198. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  8199. let value: number = 0;
  8200. if (this.offsetY < 0) {
  8201. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  8202. this.neighborItem = indexA - 1;
  8203. this.neighborScale = 1 - value / 20;
  8204. } else if (this.offsetY > 0) {
  8205. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  8206. this.neighborItem = indexA + 1;
  8207. this.neighborScale = 1 - value / 20;
  8208. }
  8209. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  8210. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8211. this.offsetY -= this.ITEM_INTV;
  8212. this.dragRefOffset += this.ITEM_INTV;
  8213. this.itemMoveSon(indexA, indexA + 1);
  8214. });
  8215. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  8216. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8217. this.offsetY += this.ITEM_INTV;
  8218. this.dragRefOffset -= this.ITEM_INTV;
  8219. this.itemMoveSon(indexA, indexA - 1);
  8220. });
  8221. }
  8222. })
  8223. .onActionEnd((event: GestureEvent) => {
  8224. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8225. this.dragItem = -1
  8226. this.neighborItem = -1
  8227. })
  8228. animateTo({
  8229. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  8230. }, () => {
  8231. this.scaleItem = -1
  8232. })
  8233. })
  8234. )
  8235. .onCancel(() => {
  8236. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8237. this.dragItem = -1
  8238. this.neighborItem = -1
  8239. })
  8240. animateTo({
  8241. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  8242. }, () => {
  8243. this.scaleItem = -1
  8244. })
  8245. })
  8246. ) //拖动List关键代码结束
  8247. .onClick(() => {
  8248. this.doPlay(item, index, true)
  8249. })
  8250. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  8251. }
  8252. .width('100%')
  8253. .height('100%')
  8254. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  8255. // .animation({ duration: 500, curve: Curve.Ease }))
  8256. .cachedCount(10)
  8257. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  8258. .gesture(PinchGesture({ fingers: 2 })
  8259. .onActionEnd((event: GestureEvent) => {
  8260. this.setSonListTwoFingers()
  8261. })
  8262. .onActionUpdate(e => {
  8263. this.scaleValue = this.pinchValue * e.scale
  8264. })
  8265. .onActionStart(e => {
  8266. }))
  8267. .padding({
  8268. bottom: 0
  8269. })
  8270. }
  8271. setSonListTwoFingers() {
  8272. this.pinchValue = this.scaleValue;
  8273. Logger.info('this.pinchValue = ' + this.pinchValue);
  8274. if (this.pinchValue >= 1) {
  8275. this.sonTwoFingerType++
  8276. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  8277. if (this.sonTwoFingerType > 3) {
  8278. this.sonTwoFingerType = 1
  8279. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  8280. }
  8281. } else {
  8282. this.sonTwoFingerType--
  8283. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  8284. if (this.sonTwoFingerType < 1) {
  8285. this.sonTwoFingerType = 1
  8286. }
  8287. }
  8288. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  8289. this.pinchValue = 1;
  8290. this.scaleValue = 1;
  8291. }
  8292. @State sonTwoFingerType:number = 3
  8293. @Builder
  8294. private MusicItemSon(item: VideoItem, index?: number) {
  8295. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8296. Row() {
  8297. Stack() {
  8298. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  8299. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  8300. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  8301. .alt($r('app.media.alt'))
  8302. .fillColor(this.themeColor)
  8303. .borderRadius(this.isCoverRectangle?11:'100%')
  8304. .clip(true)
  8305. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  8306. .draggable(false)// 禁止长按手势拖动
  8307. .autoResize(true) // 重采样,可减少内存占用
  8308. .margin({ left: 20 })
  8309. }
  8310. .width('15%')
  8311. Column() {
  8312. Column() {
  8313. Text(this.isShowFileName?item.fileName :item.name)
  8314. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  8315. .fontColor(this.curIndex === index ? this.themeColor :
  8316. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  8317. .maxLines(1)
  8318. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  8319. Row() {
  8320. Column(){
  8321. Text(item.md5Str?.includes('Lossless')?
  8322. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  8323. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  8324. .padding({ top: 3,right:6,left:6,bottom:3 })
  8325. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  8326. $r('app.color.text_color'))
  8327. .fontWeight(500)
  8328. .borderRadius(12)
  8329. .visibility(StrUtil.isEmpty(item.md5Str) ? Visibility.None : Visibility.Visible)
  8330. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  8331. .backgroundColor('#FFC107')
  8332. }
  8333. .padding({ top: 8 })
  8334. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  8335. item.artist + ' ' + item?.duration)
  8336. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  8337. .padding({ top: 8 })
  8338. .maxLines(1)
  8339. .fontColor(this.curIndex === index ? this.themeColor :
  8340. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  8341. .margin({ left: StrUtil.isEmpty(item.md5Str)? 12 :this.sonTwoFingerType == 3 ? 5 : 3 })
  8342. Blank()
  8343. Text(item.size)
  8344. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  8345. .padding({ top: 8 })
  8346. .maxLines(1)
  8347. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  8348. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  8349. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  8350. .margin({ left: 10 })
  8351. }
  8352. }
  8353. .height('100%')
  8354. .width('100%')
  8355. .justifyContent(FlexAlign.Center)
  8356. .alignItems(HorizontalAlign.Start)
  8357. }
  8358. .height('100%')
  8359. .width('65%')
  8360. Column() {
  8361. ImageAnimator()
  8362. .images(this.imagesF)// 动画数组
  8363. .duration(1000)// 持续
  8364. .state(this.animationState)// 动画状态
  8365. .fillMode(FillMode.Forwards)
  8366. .width(18)
  8367. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  8368. Visibility.None)
  8369. .height(18)
  8370. .iterations(-1) // 播放次数
  8371. }
  8372. .width('20%')
  8373. }
  8374. }
  8375. .backgroundColor(Color.Transparent)
  8376. .width('100%')
  8377. .reuseId('son_item')
  8378. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  8379. .shadow(this.scaleItem === index ? {
  8380. radius: 70,
  8381. color: '#15000000',
  8382. offsetX: 0,
  8383. offsetY: 0
  8384. } :
  8385. {
  8386. radius: 0,
  8387. color: '#15000000',
  8388. offsetX: 0,
  8389. offsetY: 0
  8390. })
  8391. .animation({ curve: Curve.Sharp, duration: 300 })
  8392. }
  8393. @Builder
  8394. MusicPlayBuilder() {
  8395. Column() {
  8396. this.IjkMusicPlayerView()
  8397. }
  8398. .transition(TransitionEffect.asymmetric(
  8399. TransitionEffect.opacity(1),
  8400. TransitionEffect.OPACITY
  8401. ))
  8402. .visualEffect(deviceInfo.sdkApiVersion>=20&&this.bgController?
  8403. new hdsEffect.HdsEffectBuilder()
  8404. .shaderEffect({
  8405. effectType: hdsEffect.EffectType.UV_BACKGROUND_FLOW_LIGHT,
  8406. animation: {
  8407. duration: 10000,
  8408. iterations: -1,
  8409. autoPlay: true,
  8410. onFinish: ()=> {
  8411. console.info('Succeeded in finishing');
  8412. }
  8413. },
  8414. controller: this.bgController,
  8415. })
  8416. .buildEffect():null)
  8417. .height('100%')
  8418. .width('100%')
  8419. .onDisAppear(() => {
  8420. this.translateY = 0;
  8421. })
  8422. .translate({ y: this.translateY })
  8423. .gesture(
  8424. PanGesture(this.panOption)
  8425. .onActionUpdate((event?: GestureEvent) => {
  8426. if (event) {
  8427. // 只允许向下滑动,向上滑动时限制为0
  8428. this.translateY = Math.max(0, event.offsetY);
  8429. this.getUIContext().animateTo({
  8430. duration: 500,
  8431. curve: Curve.Sharp
  8432. }, () => {
  8433. this.scaleValueImage = Math.min(1, Math.max(0.38, 1 - event.offsetY / 500));
  8434. console.info('onecold scaleValueImage:', this.scaleValueImage)
  8435. this.scaleValueText =Math.min(1, Math.max(0.6, 1 - event.offsetY / 700));
  8436. })
  8437. }
  8438. })
  8439. .onActionEnd((event?: GestureEvent) => {
  8440. // 使用更低的阈值和滑动速度判断
  8441. const minDistance = 300; // 最小滑动距离 100vp
  8442. const minVelocity = 500; // 最小滑动速度
  8443. // 获取滑动速度(如果可用)
  8444. const velocity = event?.velocityY || 0;
  8445. // 判断是否应该关闭:距离足够 或者 速度足够快
  8446. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  8447. if (shouldClose) {
  8448. // 添加关闭动画
  8449. this.getUIContext().animateTo({
  8450. duration: 600,
  8451. curve: Curve.Friction
  8452. }, () => {
  8453. this.isShowPlay = false;
  8454. this.scaleValueImage = 1
  8455. this.scaleValueText = 1
  8456. this.translateY = 0;
  8457. })
  8458. } else {
  8459. // 回弹动画
  8460. this.getUIContext().animateTo({
  8461. duration: 600,
  8462. curve: Curve.Friction
  8463. }, () => {
  8464. this.scaleValueImage = 1
  8465. this.scaleValueText = 1
  8466. this.translateY = 0;
  8467. })
  8468. }
  8469. })
  8470. )
  8471. }
  8472. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  8473. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  8474. HeightBreakpoint.HEIGHT_LG;
  8475. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  8476. @State topBarHeight: number = 50
  8477. @State barOpacity: number = 1
  8478. @State barBottomOpacity: number = 1
  8479. private hideDone: boolean = false;
  8480. @State currentYOffset: number = 0;
  8481. @State bottomBarHeight: number = 68;
  8482. private isHiding: boolean = false;
  8483. //是否是Pura X外屏,或者小屏幕
  8484. isPuraWP() {
  8485. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  8486. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  8487. }
  8488. //是否是Pura X外屏,或者小屏幕,手机横屏
  8489. /**
  8490. * 是否是Pura X外屏,或者小屏幕,手机横屏
  8491. * @returns
  8492. */
  8493. isCoverOpacity() {
  8494. if (this.isPuraWP()) {
  8495. return true
  8496. }
  8497. if (this.isPhoneLan()) {
  8498. return true
  8499. }
  8500. if (deviceInfo.marketName.includes('Pura X')
  8501. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  8502. return true
  8503. }
  8504. return false
  8505. }
  8506. //是不是手机横屏
  8507. isPhoneLan() {
  8508. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  8509. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  8510. logHiCarWindow(`isPhoneLan width=${this.windowWidth}`);
  8511. logHiCarWindow(`isPhoneLan height=${this.windowHeight}`);
  8512. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarStatus=${this.isHiCarStatus}`);
  8513. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, curDisplayIsHiCar=${this.curDisplayIsHiCar}`);
  8514. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall=${this.isHiCarSmall()}`);
  8515. if (this.isHiCarKuanBianPing()) {
  8516. return true
  8517. }
  8518. if (this.isHiCar()) {
  8519. return false
  8520. }
  8521. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8522. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  8523. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  8524. return true
  8525. }
  8526. return false
  8527. }
  8528. //是不是1920x720的hicar的屏幕分辨率
  8529. isHiCarKuanBianPing(){
  8530. // if(!this.isHiCar()){
  8531. // return false
  8532. // }
  8533. const hiCarAspectRatios: HiCarAspectRatio[] = [
  8534. { ratio: 1920 / 720, name: "1920x720" },
  8535. ];
  8536. const currentRatio: number = this.windowWidth / this.windowHeight;
  8537. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  8538. logHiCarWindow(`HiCarKuanBianPing currentRatio=${currentRatio}`)
  8539. for (const hiCarRatio of hiCarAspectRatios) {
  8540. logHiCarWindow(`HiCarKuanBianPing hiCarRatio=${hiCarRatio.ratio}`)
  8541. logHiCarWindow(`HiCarKuanBianPing diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  8542. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  8543. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  8544. //宽扁平的尺寸设置列表展示
  8545. this.twoFingerType ==3
  8546. this.isGridMusic = false
  8547. return true;
  8548. }
  8549. }
  8550. return false;
  8551. }
  8552. //是不是hicar的屏幕分辨率
  8553. isHiCarSmall() {
  8554. if(!this.isHiCar()){
  8555. return false
  8556. }
  8557. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  8558. {
  8559. this.columns = 6
  8560. return false
  8561. }
  8562. const hiCarAspectRatios: HiCarAspectRatio[] = [
  8563. { ratio: 800 / 480, name: "800x480" },
  8564. { ratio: 1280 / 720, name: "1280x720" },
  8565. { ratio: 1920 / 1080, name: "1920x1080" },
  8566. ];
  8567. const currentRatio: number = this.windowWidth / this.windowHeight;
  8568. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  8569. logHiCarWindow(`HiCarSmall currentRatio=${currentRatio}`)
  8570. for (const hiCarRatio of hiCarAspectRatios) {
  8571. logHiCarWindow(`HiCarSmall hiCarRatio=${hiCarRatio.ratio}`)
  8572. logHiCarWindow(`HiCarSmall diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  8573. logHiCarWindow(`HiCarSmall isHiCarStatus=${this.isHiCarStatus}`);
  8574. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  8575. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  8576. //宽扁平的尺寸设置列表展示
  8577. return true;
  8578. }
  8579. }
  8580. return false;
  8581. }
  8582. isHiCar() {
  8583. return this.curDisplayIsHiCar;
  8584. }
  8585. //是不是正常的手机竖屏
  8586. isPhonePortrait() {
  8587. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  8588. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  8589. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  8590. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8591. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  8592. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  8593. return true
  8594. }
  8595. return false
  8596. }
  8597. @State showSpeedDialog: boolean = false
  8598. @State longPressSpeed: number = 3 //长按默认倍数
  8599. @Builder
  8600. SpeedDialog() {
  8601. Stack() {
  8602. Column() {
  8603. Text('已切换至' + this.longPressSpeed + '倍速播放')
  8604. .fontColor(Color.White)
  8605. .visibility(Visibility.Hidden)
  8606. }
  8607. .backgroundColor(Color.Black)
  8608. .borderRadius(20)
  8609. .padding({
  8610. top: 10,
  8611. right: 20,
  8612. left: 15,
  8613. bottom: 20
  8614. })
  8615. .opacity(0.6)
  8616. Text('已切换至' + this.longPressSpeed + '倍速播放')
  8617. .fontColor(Color.White)
  8618. }
  8619. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  8620. .zIndex(5)
  8621. .margin({ top: 80 })
  8622. }
  8623. @Builder
  8624. IjkMusicPlayerView() {
  8625. Stack() {
  8626. if(canIUse("SystemCapability.UIDesign.HDSComponent.Core")
  8627. &&deviceInfo.sdkApiVersion>=20&&this.sceneBgController){
  8628. HdsVisualComponent()
  8629. .scene(HdsSceneType.DUAL_EDGE_FLOW_LIGHT_WITH_BACKGROUND_MASK, this.sceneBgController, () => {
  8630. console.info('Succeeded in finishing');
  8631. })
  8632. .width('100%')
  8633. .height('100%')
  8634. .visibility(this.isShowBgLiuGUANG?Visibility.Visible:Visibility.None)
  8635. }
  8636. Column() {
  8637. Column() {
  8638. //播放标题
  8639. Column() {
  8640. this.PlayTitle()
  8641. }
  8642. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  8643. .width('100%')
  8644. .margin({ top: 0 })
  8645. .height(PlayConstants.HEIGHT)
  8646. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  8647. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  8648. if (this.showSpeedDialog) {
  8649. this.SpeedDialog()
  8650. }
  8651. Stack() {
  8652. //手势拖动快进
  8653. Column()
  8654. .width(CommonConstants.FULL_PERCENT)
  8655. .height('100%')
  8656. .gesture(
  8657. GestureGroup(GestureMode.Parallel,
  8658. // 长按屏幕倍数播放
  8659. LongPressGesture({ repeat: true })
  8660. .onAction(() => {
  8661. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8662. this.showSpeedDialog = true;
  8663. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  8664. }
  8665. })
  8666. .onActionEnd(() => {
  8667. this.showSpeedDialog = false;
  8668. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  8669. }),
  8670. //双击屏幕暂停或者播放
  8671. TapGesture({ count: 2 })
  8672. .onAction((event: GestureEvent) => {
  8673. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8674. ToastUtil.showToast('已暂停')
  8675. }
  8676. console.info('onecold playOrPause 6693')
  8677. this.playOrPause()
  8678. })
  8679. )
  8680. )
  8681. }
  8682. .height('65%')
  8683. Swiper() {
  8684. this.CoverInfo()
  8685. this.PlayerLyrics()
  8686. }
  8687. .onChange((index: number) => {
  8688. this.currentSwiperIndex = index
  8689. })
  8690. .indicator(false)
  8691. .displayCount(new BreakpointType({
  8692. sm: 1,
  8693. md: 2,
  8694. lg: 2,
  8695. xl: 2,
  8696. xxl: 2
  8697. }).getValue(this.currentBreakpoint))
  8698. .clip(false)
  8699. .loop(false)
  8700. .autoPlay(false)
  8701. // .interval(8000)
  8702. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  8703. .height('100%')
  8704. .hitTestBehavior(HitTestMode.Transparent)
  8705. Image($r('app.media.icon_replay'))
  8706. .objectFit(ImageFit.Auto)
  8707. .width('120px')
  8708. .height('120px')
  8709. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  8710. .border({ width: 0 })
  8711. .visibility(Visibility.None)
  8712. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  8713. .onClick(() => {
  8714. console.info('onecold startPlayOrResumePlay 6744')
  8715. this.startPlayOrResumePlay();
  8716. })
  8717. }
  8718. .width(CommonConstants.FULL_PERCENT)
  8719. .height(CommonConstants.FULL_PERCENT)
  8720. .justifyContent(FlexAlign.End)
  8721. }
  8722. .justifyContent(FlexAlign.End)
  8723. .margin({ bottom: 8 })
  8724. }
  8725. .backgroundImage(!this.isMusicBGCover||StrUtil.isEmpty(this.cover)?null: this.cover)
  8726. .backgroundImageSize(this.isPuraWP()||!this.isMusicBGCover ? { width: '100%' } : { height: '150%', width: '100%' })
  8727. .animation({
  8728. duration: 666,
  8729. curve: 'ease-in-out' // 可选动画曲线
  8730. })
  8731. .backgroundBlurStyle((this.isPuraWP() && this.currentSwiperIndex === 0) ||!this.isMusicBGCover
  8732. ? BlurStyle.NONE :
  8733. BlurStyle.BACKGROUND_ULTRA_THICK)
  8734. .hitTestBehavior(HitTestMode.Transparent)
  8735. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  8736. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  8737. .onClick(() => {
  8738. if(this.isHiCar())
  8739. return
  8740. if(this.is_auto_hide_progress){
  8741. this.is_auto_hide_progress = false
  8742. }
  8743. this.startAutoHide()
  8744. })
  8745. }
  8746. @Consume progressValue: number ;
  8747. @State currentTime: string = "00:00";
  8748. @State totalTime: string = "00:00";
  8749. @State loadingVisible: Visibility = Visibility.None;
  8750. @State replayVisible: Visibility = Visibility.None;
  8751. @State slideEnable: boolean = false;
  8752. @State aspRatio: number = 0.5;
  8753. @State mContext: object | undefined = undefined;
  8754. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  8755. @State mFirst: boolean = true;
  8756. @State mDestroyPage: boolean = false;
  8757. @State playSpeed: number = 1;
  8758. @State oldSeconds: number = 0;
  8759. @State isSeekTo: boolean = false;
  8760. @State isCurrentTime: boolean = false;
  8761. @State videoWidth: string = '100%';
  8762. @State videoHeight: string = '100%';
  8763. @State initAspectRatio: number = 1;
  8764. @State videoAspectRatio: number = this.initAspectRatio;
  8765. @State videoUrl: string = '';
  8766. private last: number = 0;
  8767. @State videoParentAspectRatio: number = this.initAspectRatio;
  8768. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  8769. @Consume CONTROL_PlayStatus: number ;
  8770. @State PROGRESS_MAX_VALUE: number = 100;
  8771. @State updateProgressTimer: number = 0;
  8772. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  8773. @State name: string = '';
  8774. // @State loop: boolean = false;
  8775. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  8776. @State multiple: string = '1.0X';
  8777. xcomponentController: XComponentController = new XComponentController()
  8778. private panOptionBright: PanGestureOptions =
  8779. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  8780. private panOptionVolume: PanGestureOptions =
  8781. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  8782. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  8783. //手势的音量控制和亮度控制
  8784. private positionX: number = PlayConstants.POSITION_X;
  8785. private positionY: number = PlayConstants.POSITION_Y;
  8786. private windowClass: window.Window = globalThis.windowClass
  8787. @State volume: number = 0.5;
  8788. @State volumeSmall: boolean = false
  8789. @State autoParseMusicName: boolean = true
  8790. @State isShowFileName: boolean = false
  8791. @State isLongNameRoLL: boolean = true//长歌名滚动
  8792. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  8793. @State bright: number = PlayConstants.BRIGHT;
  8794. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  8795. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  8796. @State screenWidth: number = 0
  8797. @State screenHeight: number = 0
  8798. @State statusBarHeight: number = 0
  8799. @State isYesFull: boolean = false
  8800. private seekValue: number = 0
  8801. @State isVideoLock: boolean = false; // Whether the video playback is locked
  8802. eventHub = getContext().eventHub;
  8803. //投播组件
  8804. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  8805. private castController: avSession.AVCastController | undefined = undefined;
  8806. @State isCastPlaying: boolean = false;
  8807. @State currentTime2: number = 0;
  8808. @State currentStringTime: string = '00:00';
  8809. @State duration: number = 0;
  8810. @State isReady: boolean = false;
  8811. @State durationTime: number = 0;
  8812. @State durationStringTime: string = '00:00';
  8813. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  8814. // @State isPlaying: boolean = false;
  8815. private castSeek: boolean = false;
  8816. private castItem: avSession.AVQueueItem | undefined = undefined;
  8817. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  8818. @State rotateAngle2: number = -9
  8819. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  8820. @Consume cover: string | undefined ;
  8821. @State artist: string | undefined = ''
  8822. // 1.初始化controller
  8823. private lyricController: LyricController = new LyricController()
  8824. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  8825. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  8826. private parser = new LyricParser()
  8827. @State randomColor: string = 'rgb(0,0,0)'
  8828. @State randomShakenX: number = 0
  8829. @State randomShakenY: number = 0
  8830. @State lyricTextSize: number = 24
  8831. @State lyricContent: string = ''
  8832. @State isDebug: boolean = false
  8833. @State isHightLightCenter: boolean = true
  8834. /**
  8835. * 初始化歌词加载与展示逻辑
  8836. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  8837. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  8838. * @param isApi2 是否使用API2获取歌词(可选)
  8839. *
  8840. * 主要流程:
  8841. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  8842. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  8843. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  8844. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  8845. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  8846. * 6. 解析失败或读取失败时,清空歌词显示。
  8847. *
  8848. * 注意事项:
  8849. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  8850. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  8851. * - 歌词内容解析后通过lyricController驱动UI渲染。
  8852. */
  8853. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  8854. if (StrUtil.isEmpty(lyricPath)) {
  8855. return
  8856. }
  8857. this.initPipLyricSetting()
  8858. this.lyricControllerSingle
  8859. .setTextSize(15)
  8860. .setCacheSize(4)
  8861. .setTextColor("#FFFFFF")
  8862. .setHighlightColor(this.currentHighLightLyricColor)
  8863. .setHighlightScale(1.2)
  8864. .setEmptyHint("")
  8865. .setAlignMode('center')
  8866. .setAnimationDuration(500)
  8867. .setSingleLine(true)
  8868. this.lyricContent = ''
  8869. this.lyricController
  8870. .setTextSize(this.currentLyricSize)
  8871. .setCacheSize(4)
  8872. .setTextColor("#DDDDDD")
  8873. .setHighlightColor("#FFFFFF")
  8874. .setEmptyHint("")
  8875. .setAnimationDuration(1000)
  8876. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  8877. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  8878. this.setBlurDegree(this.blurDegree, false)
  8879. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  8880. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  8881. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  8882. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  8883. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  8884. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  8885. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  8886. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  8887. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  8888. this.lyricController.setTextWeight(this.lyricTextWeight)
  8889. this.showSingleLyric = false
  8890. this.timeOffset = 0
  8891. this.lyricController.setLyric(null)
  8892. this.lyricControllerSingle.setLyric(null)
  8893. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  8894. console.log("onecold lyricPath =" + lyricPath)
  8895. let neiqianLrc = ''
  8896. let lyContent = this.currentSong?.lyricContent
  8897. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  8898. neiqianLrc = lyContent
  8899. }
  8900. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast&&!isLocal&&!isLocal) {
  8901. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  8902. //赋值给this.lyricContent,播控中心才可以显示歌词
  8903. this.lyricContent = neiqianLrc
  8904. // 将文件内容按行分割成字符串数组
  8905. let lines = neiqianLrc.split('\n').map(line => line.trim());
  8906. // 3.解析歌词
  8907. let lyric = this.parser.parse(lines);
  8908. // 4.设置歌词
  8909. this.lyricController.setLyric(lyric);
  8910. this.lyricControllerXF.setLyric(lyric)
  8911. this.lyricControllerSingle.setLyric(lyric)
  8912. return
  8913. }
  8914. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  8915. && !Utility.isVideoByExtension(this.videoUrl))) {
  8916. if (this.currentSong !== undefined) {
  8917. // ToastUtil.showShort('正在为你搜索在线歌词!')
  8918. //判断是不是赞助会员,是会员的话才开启歌词功能
  8919. // if (!this.isDebug) {
  8920. // if (!Utility.isNoble()) {
  8921. // LogUtil.debug("onecold 不是赞助会员")
  8922. // return
  8923. // }
  8924. // if(!Utility.isPassInstallTime(33)){
  8925. // LogUtil.debug("onecold not pass time")
  8926. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  8927. // return
  8928. // }
  8929. // }
  8930. let artist = this.currentSong?.artist
  8931. if (artist === undefined) {
  8932. artist = ''
  8933. }
  8934. if (isApi2 === undefined) {
  8935. isApi2 = false
  8936. }
  8937. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  8938. // LogUtil.debug("onecold res =" + res)
  8939. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  8940. if (StrUtil.isNotEmpty(res)) {
  8941. this.lyricContent = res
  8942. let lines = res.split('\n').map(line => line.trim());
  8943. // 3.解析歌词
  8944. let lyric = this.parser.parse(lines);
  8945. // 4.设置歌词
  8946. this.lyricController.setLyric(lyric);
  8947. this.lyricControllerXF.setLyric(lyric)
  8948. this.lyricControllerSingle.setLyric(lyric)
  8949. this.showSingleLyric = true
  8950. // 4.保存歌词文件lyric到本地
  8951. //2025年8月28日歌词不再加密下载
  8952. this.saveDataToFile(res, lyricPath, false)
  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. } else {
  8962. this.lyricController.setLyric(null)
  8963. this.lyricControllerXF.setLyric(null)
  8964. this.lyricControllerSingle.setLyric(null)
  8965. if (isOnLineAndToast) {
  8966. ToastUtil.showShort('未获取到歌词!')
  8967. }
  8968. }
  8969. })
  8970. } else {
  8971. this.lyricController.setLyric(null)
  8972. this.lyricControllerXF.setLyric(null)
  8973. this.lyricControllerSingle.setLyric(null)
  8974. if (isOnLineAndToast) {
  8975. ToastUtil.showShort('未获取到歌词!')
  8976. }
  8977. }
  8978. return
  8979. }
  8980. try {
  8981. let isJiaMi = false;
  8982. let realLyricPath = lyricPath
  8983. if (FileUtil.accessSync(jiaMilyricPath)) {
  8984. isJiaMi = true
  8985. realLyricPath = jiaMilyricPath
  8986. console.info("onecold 找到加密本地歌词 ");
  8987. } else {
  8988. isJiaMi = false
  8989. realLyricPath = lyricPath
  8990. console.info("onecold 找到本地歌词 ");
  8991. }
  8992. // 3.读取文件内容并指定编码为 UTF-8
  8993. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  8994. const stat = await fileIo.stat(file.fd);
  8995. const arrayBuffer = new ArrayBuffer(stat.size);
  8996. fs.read(file.fd, arrayBuffer)
  8997. .then((readLen: number) => {
  8998. console.info("read file data succeed");
  8999. // let buf = buffer.from(arrayBuffer, 0, readLen);
  9000. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  9001. // 检查 buf 是否为空
  9002. if (buf.length === 0) {
  9003. throw new Error("Buffer is empty after reading the file");
  9004. }
  9005. try {
  9006. // 检测文件编码
  9007. // let detectedEncoding = chardet.detect(buf);
  9008. // console.info("onecoldT Detected encoding: " + detectedEncoding);
  9009. let detectedEncoding = this.detect(arrayBuffer)
  9010. console.info("onecoldT Detected encoding: " + detectedEncoding);
  9011. // 使用检测到的编码解码,解决中文乱码问题
  9012. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  9013. console.info("onecoldT Detected textDecoder: " + textDecoder);
  9014. let fileContent = textDecoder.decode(buf);
  9015. console.info(`onecoldT The content of file1: ${fileContent}`);
  9016. //解密
  9017. if (isJiaMi) {
  9018. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  9019. }
  9020. console.info(`onecold The content of file2: ${fileContent}`);
  9021. this.lyricContent = fileContent
  9022. if(isLocal){//编辑标签选择本地歌词需要赋值给this.lyricConStr
  9023. this.lyricConStr = fileContent
  9024. }
  9025. // 将文件内容按行分割成字符串数组
  9026. let lines = fileContent.split('\n').map(line => line.trim());
  9027. console.info(`onecold The content of file: ${fileContent}`);
  9028. // 3.解析歌词
  9029. let lyric = this.parser.parse(lines);
  9030. // 4.设置歌词
  9031. this.lyricController.setLyric(lyric);
  9032. this.lyricControllerXF.setLyric(lyric)
  9033. this.lyricControllerSingle.setLyric(lyric)
  9034. this.showSingleLyric = true
  9035. console.info(`The content of file: ${fileContent}`);
  9036. } catch (chardetError) {
  9037. console.error("chardet.detect failed with error: " + chardetError.message);
  9038. this.lyricController.setLyric(null);
  9039. this.lyricControllerXF.setLyric(null)
  9040. this.lyricControllerSingle.setLyric(null)
  9041. }
  9042. })
  9043. .catch((err: BusinessError) => {
  9044. this.lyricController.setLyric(null)
  9045. this.lyricControllerXF.setLyric(null)
  9046. this.lyricControllerSingle.setLyric(null)
  9047. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  9048. })
  9049. .catch((err: Error) => {
  9050. this.lyricController.setLyric(null)
  9051. this.lyricControllerXF.setLyric(null)
  9052. this.lyricControllerSingle.setLyric(null)
  9053. console.error("read file 2 data failed with error message: " + err.message);
  9054. })
  9055. .finally(() => {
  9056. fs.closeSync(file);
  9057. });
  9058. } catch (error) {
  9059. this.lyricController.setLyric(null)
  9060. this.lyricControllerSingle.setLyric(null)
  9061. this.lyricControllerXF.setLyric(null)
  9062. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  9063. }
  9064. }
  9065. detect(data: ArrayBuffer): string {
  9066. //创建检测对象
  9067. let detector: UniversalDetector = new UniversalDetector();
  9068. // 传入检测数据并实时判断编码格式
  9069. detector.handleData(data, 0, data.byteLength);
  9070. // 标记检测数据 读取结束
  9071. detector.dataEnd();
  9072. // 获取检测结果
  9073. let detected: string = detector.getDetectedCharset();
  9074. // 释放资源
  9075. detector.reset();
  9076. return detected;
  9077. }
  9078. //初始化悬浮歌词的自定义设置
  9079. initPipLyricSetting() {
  9080. this.lyricControllerXF
  9081. .setTextSize(this.currentLyricSize)
  9082. .setCacheSize(4)
  9083. .setTextColor("#DDDDDD")
  9084. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  9085. .setEmptyHint("")
  9086. .setAnimationDuration(1000)
  9087. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  9088. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  9089. this.setBlurDegree(this.blurDegreePip, true)
  9090. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  9091. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  9092. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  9093. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  9094. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  9095. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  9096. this.lyricControllerXF.setHightLightCenter(true)
  9097. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  9098. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  9099. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  9100. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  9101. if (this.pipBgIndex === 0) {
  9102. if (this.cover) {
  9103. this.pipBg = this.cover
  9104. } else {
  9105. this.pipBg = this.imageColor
  9106. }
  9107. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  9108. }
  9109. }
  9110. //根据item返回歌词内容
  9111. async getLyricContent(item: VideoItem): Promise<string> {
  9112. let neiqianLrc = ''
  9113. let lyContent = item?.lyricContent
  9114. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  9115. neiqianLrc = lyContent
  9116. return neiqianLrc
  9117. }
  9118. try {
  9119. //取数据库里面的歌词lyContent
  9120. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  9121. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  9122. console.log("onecold Lyrics:", lyricContent);
  9123. neiqianLrc = lyricContent
  9124. return neiqianLrc
  9125. }
  9126. } catch (error) {
  9127. console.error("Error fetching lyrics:", error);
  9128. }
  9129. try {
  9130. let filePath = item.filePath;
  9131. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  9132. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  9133. let isJiaMi = false;
  9134. let realLyricPath = lyricPath;
  9135. if (FileUtil.accessSync(jiaMilyricPath)) {
  9136. isJiaMi = true;
  9137. realLyricPath = jiaMilyricPath;
  9138. console.info("onecold 找到加密本地歌词");
  9139. } else {
  9140. console.info("onecold 找到本地歌词");
  9141. }
  9142. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  9143. const stat = await fileIo.stat(file.fd);
  9144. const arrayBuffer = new ArrayBuffer(stat.size);
  9145. const readLen = await fs.read(file.fd, arrayBuffer);
  9146. console.info("read file data succeed");
  9147. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  9148. if (buf.length === 0) {
  9149. throw new Error("Buffer is empty after reading the file");
  9150. }
  9151. // let detectedEncoding = chardet.detect(buf);
  9152. let detectedEncoding = this.detect(arrayBuffer)
  9153. console.info("Detected encoding: " + detectedEncoding);
  9154. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  9155. let fileContent = textDecoder.decode(buf);
  9156. console.info(`onecold The content of file1: ${fileContent}`);
  9157. if (isJiaMi) {
  9158. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  9159. }
  9160. console.info(`onecold The content of file2: ${fileContent}`);
  9161. fs.closeSync(file);
  9162. return fileContent;
  9163. } catch (error) {
  9164. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  9165. return '';
  9166. }
  9167. }
  9168. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  9169. if (StrUtil.isEmpty(filePath)) {
  9170. return
  9171. }
  9172. try {
  9173. //将content进行加密
  9174. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  9175. let lyricContent = ''
  9176. if (isJiaMi) {
  9177. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  9178. } else {
  9179. lyricContent = content
  9180. }
  9181. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  9182. // 清空文件内容
  9183. await fileIo.truncate(file.fd, 0);
  9184. await fileIo.write(file.fd, lyricContent);
  9185. await fileIo.close(file);
  9186. console.log('onecold lyric file Data saved successfully.');
  9187. } catch (error) {
  9188. console.error('onecold lyric file Failed to save data:', error);
  9189. }
  9190. }
  9191. // 定义开始旋转的方法
  9192. // 定时器用于一百毫秒执行一次旋转角度
  9193. @State timer: number = 0
  9194. @State rotateAngle: number = 0
  9195. //封面旋转动画
  9196. animationRoFun() {
  9197. if (this.isPlaying && !this.isCoverRectangle) {
  9198. this.timer = setInterval(() => {
  9199. this.rotateAngle += 1
  9200. }, 100)
  9201. this.startRotation()
  9202. } else {
  9203. clearInterval(this.timer)
  9204. this.stopRotation()
  9205. }
  9206. }
  9207. // 定义开始旋转的方法
  9208. startRotation() {
  9209. if (this.isPlaying) {
  9210. animateTo({
  9211. duration: 777,
  9212. iterations: 1,
  9213. curve: Curve.Linear
  9214. }, () => {
  9215. this.rotateAngle2 = -9
  9216. })
  9217. }
  9218. }
  9219. // 回调,暂停和播放按钮回调,下一首和上一首
  9220. playChange() {
  9221. // if(this.isCoverRectangle){
  9222. // return
  9223. // }
  9224. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  9225. this.setIsPlaying(true)
  9226. this.animationState = AnimationStatus.Running
  9227. } else {
  9228. this.setIsPlaying(false)
  9229. this.animationState = AnimationStatus.Paused
  9230. }
  9231. AppStorage.setOrCreate('animationState', this.animationState);
  9232. }
  9233. // 定义停止旋转的方法
  9234. stopRotation() {
  9235. if (this.isCoverRectangle) {
  9236. this.rotateAngle = 0
  9237. } else {
  9238. //唱针以左上角为点选择逆时针40度
  9239. animateTo({
  9240. duration: 1000,
  9241. curve: Curve.Linear,
  9242. iterations: 1,
  9243. }, () => {
  9244. this.rotateAngle2 = -45;
  9245. });
  9246. }
  9247. }
  9248. @Builder
  9249. private LyricsTopItem() {
  9250. Row() {
  9251. Stack() {
  9252. Image(this.cover)
  9253. .height(58)
  9254. .width(58)
  9255. .clip(true)
  9256. .sourceSize({width:38, height:38})
  9257. .alt($r('app.media.alt'))
  9258. .borderRadius(8)
  9259. .clickEffect({ level: ClickEffectLevel.HEAVY })
  9260. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  9261. .shadow({
  9262. radius: 22,
  9263. type: ShadowType.BLUR,
  9264. color: 'on_primary'
  9265. })
  9266. }
  9267. .width('18%')
  9268. Column() {
  9269. Column() {
  9270. Text(this.name)
  9271. .fontSize(16)
  9272. .maxLines(1)
  9273. .fontWeight(FontWeight.Bolder)
  9274. .fontColor(Color.White)
  9275. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  9276. Row() {
  9277. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  9278. .fontSize(13)
  9279. .fontWeight(FontWeight.Bolder)
  9280. .padding({ top: 8 })
  9281. .fontColor(Color.White)
  9282. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  9283. Blank()
  9284. }
  9285. }
  9286. .height('100%')
  9287. .width('100%')
  9288. .justifyContent(FlexAlign.Center)
  9289. .alignItems(HorizontalAlign.Start)
  9290. }
  9291. .height('100%')
  9292. .width('65%')
  9293. Column() {
  9294. Image($r('app.media.lyric'))
  9295. .width(28)
  9296. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9297. .margin({ right: 30 })
  9298. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9299. .onClick(() => {
  9300. this.isLyricSetting = !this.isLyricSetting;
  9301. })
  9302. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  9303. height: '99%',
  9304. dragBar: true,
  9305. preferType: SheetType.CENTER,
  9306. showClose: true,
  9307. blurStyle: BlurStyle.Thin,
  9308. backgroundColor: Color.Transparent,
  9309. title: { title: $r('app.string.lyric_setting') }
  9310. })
  9311. }
  9312. .width('18%')
  9313. }
  9314. .width('82%')
  9315. .height(58)
  9316. .justifyContent(FlexAlign.SpaceBetween)
  9317. }
  9318. //歌词显示
  9319. @Builder
  9320. PlayerLyrics() {
  9321. Column() {
  9322. Column() {
  9323. this.LyricsTopItem()
  9324. }
  9325. .height(this.isPuraWP() ? 15 : 58)
  9326. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  9327. Visibility.None : Visibility.Visible)
  9328. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  9329. .width("100%")
  9330. Column() {
  9331. LyricView2({
  9332. controller: this.lyricController,
  9333. enableSeek: true,
  9334. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  9335. seekLineColor: "#80ffffff", // 滑动定位线颜色
  9336. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  9337. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  9338. if (!this.isPlaying) {
  9339. console.info('onecold startPlayOrResumePlay 7527')
  9340. this.startPlayOrResumePlay()
  9341. }
  9342. else {
  9343. this.isSeekTo = true;
  9344. this.mDestroyPage = false;
  9345. this.showLoadIng();
  9346. this.seekTo(position + "");
  9347. this.isSeekTo = false;
  9348. }
  9349. return true
  9350. }
  9351. })
  9352. .width("100%")
  9353. .layoutWeight(1)
  9354. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  9355. if (this.isPhoneLan()) {
  9356. Column() {
  9357. this.playProgressView()
  9358. // this.playCenterView()
  9359. }
  9360. .margin({ bottom: 30, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  9361. }
  9362. }
  9363. .position({
  9364. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  9365. (this.isPuraWP() ? 58 : 99)
  9366. })
  9367. .justifyContent(FlexAlign.Center)
  9368. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  9369. }
  9370. }
  9371. @Builder
  9372. SingleLyricView() {
  9373. Column() {
  9374. Column() {
  9375. LyricView2({
  9376. controller: this.lyricControllerSingle,
  9377. enableSeek: false,
  9378. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  9379. seekLineColor: "#80ffffff", // 滑动定位线颜色
  9380. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  9381. })
  9382. }
  9383. .height(66)
  9384. .margin({ bottom: 20 })
  9385. }
  9386. }
  9387. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  9388. @Builder
  9389. BottomControl() {
  9390. Column() {
  9391. this.TopPlayProgressView()
  9392. //播放 暂停,下一首,上一首
  9393. this.playCenterView()
  9394. if(!this.curDisplayIsHiCar){
  9395. //播放进度条
  9396. this.BottomView()
  9397. }
  9398. }
  9399. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  9400. }
  9401. //播放控制上一首 下一首 暂停和播放
  9402. @Builder
  9403. playCenterView(){
  9404. Row() {
  9405. Button({type:ButtonType.Circle,stateEffect:true}){
  9406. //更多功能
  9407. Image($r('app.media.menu'))
  9408. .width(24)
  9409. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9410. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  9411. height: '99%',
  9412. preferType:SheetType.CENTER,
  9413. dragBar: true,
  9414. showClose: true,
  9415. blurStyle: BlurStyle.Thin,
  9416. title: { title: $r('app.string.more') },
  9417. backgroundColor: Color.Transparent,
  9418. })
  9419. }
  9420. .height(45)
  9421. .width(45)
  9422. .margin({ left: 5 })
  9423. .backgroundColor(Color.Transparent)
  9424. .onClick(() => {
  9425. this.isShowMoreView = !this.isShowMoreView;
  9426. })
  9427. Button({type:ButtonType.Circle,stateEffect:true}){
  9428. Image($r('app.media.ic_previous'))
  9429. .width(33)
  9430. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9431. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9432. }
  9433. .height(45)
  9434. .width(45)
  9435. .onClick(async () => {
  9436. await this.playPrevious()
  9437. })
  9438. .backgroundColor(Color.Transparent)
  9439. Button({type:ButtonType.Circle,stateEffect:true}){
  9440. Column() {
  9441. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  9442. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  9443. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  9444. .width(this.isPhoneLan()?45:55)
  9445. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9446. .fillColor(Color.White)
  9447. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9448. }
  9449. }
  9450. .onClick(async () => {
  9451. this.playOrPause()
  9452. })
  9453. .backgroundColor(Color.Transparent)
  9454. .layoutWeight(1)
  9455. // PointLightButton({
  9456. // builder: () => {
  9457. // this.PlayOrPauseButton()
  9458. // },
  9459. // isPx: true,
  9460. // builderHeight: 60,
  9461. // builderWidth: 60,
  9462. // })
  9463. // .layoutWeight(1)
  9464. // .onClick(() =>{
  9465. // this.playOrPause()
  9466. // })
  9467. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9468. Image($r('app.media.ic_next'))
  9469. .width(33)
  9470. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9471. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9472. }
  9473. .height(45)
  9474. .width(45)
  9475. .backgroundColor(Color.Transparent)
  9476. .onClick(async () => {
  9477. await this.playNext();
  9478. })
  9479. if(this.curDisplayIsHiCar){
  9480. this.playModeButton()
  9481. }else{
  9482. this.fullButton()
  9483. }
  9484. }
  9485. .width('95%')
  9486. .margin({ bottom:this.isCoverOpacity()?0:15 })
  9487. .justifyContent(FlexAlign.SpaceEvenly)
  9488. }
  9489. @Builder
  9490. PlayOrPauseButton(){
  9491. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  9492. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  9493. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  9494. .width(this.isPhoneLan()?45:55)
  9495. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9496. .fillColor(Color.White)
  9497. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9498. }
  9499. @Builder
  9500. TopPlayProgressView(){
  9501. Column() {
  9502. Row(){
  9503. Stack(){
  9504. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  9505. .fontColor([Color.White])
  9506. .fontSize(21)
  9507. .effectStrategy(1)
  9508. Text(this.fastForwardSeconds)
  9509. .fontColor(Color.White)
  9510. .fontSize(10)
  9511. .fontWeight(FontWeight.Bold)
  9512. }
  9513. .padding({left:12,bottom:6})
  9514. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  9515. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9516. .onClick(()=>{
  9517. this.backForward()
  9518. })
  9519. Slider({
  9520. value: this.progressValue,
  9521. min: 0,
  9522. max: this.PROGRESS_MAX_VALUE,
  9523. step: 1,
  9524. style: SliderStyle.InSet
  9525. })
  9526. .height(20)
  9527. .blockColor('rgba(255,255,255,1)')
  9528. .trackColor('rgba(255,255,255,0.3)')
  9529. .selectedColor(Color.White)
  9530. .trackThickness(4)
  9531. .showSteps(false)
  9532. .showTips(true)
  9533. .layoutWeight(1)
  9534. .enabled(this.slideEnable)
  9535. .onChange((value: number, mode: SliderChangeMode) => {
  9536. // if (mode == 2) {
  9537. this.isSeekTo = true;
  9538. this.mDestroyPage = false;
  9539. this.showLoadIng();
  9540. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  9541. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  9542. this.seekTo(seekValue + "");
  9543. // this.setProgress()
  9544. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  9545. this.isSeekTo = false;
  9546. // }
  9547. })
  9548. Stack(){
  9549. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  9550. .fontColor([Color.White])
  9551. .fontSize(21)
  9552. .effectStrategy(1)
  9553. Text(this.fastForwardSeconds)
  9554. .fontColor(Color.White)
  9555. .fontSize(10)
  9556. .fontWeight(FontWeight.Bold)
  9557. }
  9558. .padding({right:10,bottom:6})
  9559. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  9560. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9561. .onClick(()=>{
  9562. this.fastForward()
  9563. })
  9564. }
  9565. .justifyContent(FlexAlign.Center)
  9566. .padding({left:20,right:20})
  9567. .width(this.isLandscape?'88%':'95%')
  9568. Row() {
  9569. Text(this.currentTime)
  9570. .fontSize(10)
  9571. .fontColor(Color.White)
  9572. .margin({left:25})
  9573. Blank()
  9574. Text(this.totalTime)
  9575. .fontSize(10)
  9576. .fontColor(Color.White)
  9577. .margin({right:25})
  9578. }
  9579. .width(this.isLandscape?'85%':'90%')
  9580. .height(10)
  9581. }
  9582. .width('100%')
  9583. .alignItems(HorizontalAlign.Center)
  9584. }
  9585. @Builder
  9586. playModeButton(){
  9587. Button({type:ButtonType.Circle,stateEffect:true}){
  9588. Column() {
  9589. if (this.playType === 0) {
  9590. Image($r('app.media.loop'))
  9591. .width(27)
  9592. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9593. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9594. } else if (this.playType === 1) {
  9595. Image($r('app.media.single'))
  9596. .width(27)
  9597. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9598. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9599. } else if (this.playType === 2) {
  9600. Image($r('app.media.normal_play'))
  9601. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9602. .width(27)
  9603. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9604. } else if (this.playType === 3) {
  9605. Image($r('app.media.random'))
  9606. .width(27)
  9607. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9608. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9609. }
  9610. }
  9611. }
  9612. .layoutWeight(1)
  9613. .margin({ left: 5 })
  9614. .height(45)
  9615. .width(45)
  9616. .backgroundColor(Color.Transparent)
  9617. .onClick(async () => {
  9618. this.setLoopMode()
  9619. })
  9620. }
  9621. //播放进度条
  9622. @Builder
  9623. BottomView(){
  9624. Row() {
  9625. this.playModeButton()
  9626. if(this.currentSong){
  9627. Button({type:ButtonType.Circle,stateEffect:true}){
  9628. Column() {
  9629. Image($r('app.media.rename2'))
  9630. .width(21)
  9631. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9632. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9633. }
  9634. }
  9635. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  9636. height: '99%',
  9637. dragBar: true,
  9638. showClose: true,
  9639. preferType: SheetType.BOTTOM,
  9640. title: { title: '编辑标签' }
  9641. })
  9642. .height(45)
  9643. .width(45)
  9644. .layoutWeight(1)
  9645. .backgroundColor(Color.Transparent)
  9646. .onClick(async () => {
  9647. this.initEditFields(this.currentSong)
  9648. this.tempLyricContent = this.lyricContent
  9649. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  9650. this.lyricConStr = this.tempLyricContent
  9651. }
  9652. this.isShowEdit = !this.isShowEdit;
  9653. })
  9654. }
  9655. Button({type:ButtonType.Circle,stateEffect:true}){
  9656. Column() {
  9657. Image($r('app.media.lyric'))
  9658. .width(26)
  9659. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9660. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9661. }
  9662. }
  9663. .height(45)
  9664. .width(45)
  9665. .layoutWeight(1)
  9666. .backgroundColor(Color.Transparent)
  9667. .onClick(async () => {
  9668. this.isLyricSetting = !this.isLyricSetting;
  9669. })
  9670. //播放列表
  9671. Button({type:ButtonType.Circle,stateEffect:true}){
  9672. Image($r('app.media.hm_playlist'))
  9673. .width(24)
  9674. .fillColor(Color.White)
  9675. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9676. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9677. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  9678. height: '95%',
  9679. dragBar: true,
  9680. showClose: true,
  9681. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9682. blurStyle: BlurStyle.Thin,
  9683. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  9684. title: {
  9685. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  9686. + `(${this.songList.length}首)`
  9687. }
  9688. })
  9689. }
  9690. .layoutWeight(1)
  9691. .height(45)
  9692. .width(45)
  9693. .backgroundColor(Color.Transparent)
  9694. .onClick(() => {
  9695. this.isShowSheetView = !this.isShowSheetView;
  9696. if(this.isPlayListBgGrass){
  9697. this.isFrontWhite = true
  9698. }else{
  9699. this.isFrontWhite = false
  9700. }
  9701. this.scrollIndex()
  9702. })
  9703. }
  9704. .width(this.isLandscape?'88%':'95%')
  9705. .justifyContent(FlexAlign.SpaceAround)
  9706. .height(30)
  9707. .animation({
  9708. duration: 666,
  9709. curve: 'ease-in-out' // 可选动画曲线
  9710. })
  9711. }
  9712. @Builder
  9713. fullButton(){
  9714. Button({type:ButtonType.Circle,stateEffect:true}){
  9715. Column() {
  9716. Image($r('app.media.full_4'))
  9717. .width(25)
  9718. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9719. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9720. }
  9721. }
  9722. .layoutWeight(1)
  9723. .backgroundColor(Color.Transparent)
  9724. .height(45)
  9725. .width(45)
  9726. .onClick(async () => {
  9727. if (this.isLandscape) {
  9728. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  9729. } else {
  9730. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  9731. }
  9732. })
  9733. }
  9734. //旧版本播放进度条
  9735. @Builder
  9736. playProgressView() {
  9737. Row() {
  9738. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9739. Column() {
  9740. if (this.playType === 0) {
  9741. Image($r('app.media.loop'))
  9742. .width($r('app.float.control_image_width'))
  9743. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9744. } else if (this.playType === 1) {
  9745. Image($r('app.media.single'))
  9746. .width($r('app.float.control_image_width'))
  9747. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9748. } else if (this.playType === 2) {
  9749. Image($r('app.media.normal_play'))
  9750. .width($r('app.float.control_image_width'))
  9751. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9752. } else if (this.playType === 3) {
  9753. Image($r('app.media.random'))
  9754. .width($r('app.float.control_image_width'))
  9755. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9756. }
  9757. }
  9758. }
  9759. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  9760. .animation({
  9761. duration: 666,
  9762. curve: 'ease-in-out' // 可选动画曲线
  9763. })
  9764. .backgroundColor(Color.Transparent)
  9765. .margin({ right: 10 })
  9766. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9767. .onClick(async () => {
  9768. this.setLoopMode()
  9769. })
  9770. Text(this.currentTime)
  9771. .fontSize($r('app.float.slider_font_size'))
  9772. .fontColor(Color.White)
  9773. .margin(3)
  9774. Slider({
  9775. value: this.progressValue,
  9776. min: 0,
  9777. max: this.PROGRESS_MAX_VALUE,
  9778. step: 1,
  9779. style: SliderStyle.OutSet
  9780. })
  9781. .width('600px')
  9782. .blockColor('rgba(255,255,255,1)')
  9783. .trackColor('rgba(255,255,255,0.3)')
  9784. .selectedColor(Color.White)
  9785. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  9786. .layoutWeight(1)
  9787. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  9788. .showSteps(false)
  9789. .showTips(true)
  9790. .enabled(this.slideEnable)
  9791. .onChange((value: number, mode: SliderChangeMode) => {
  9792. // if (mode == 2) {
  9793. this.isSeekTo = true;
  9794. this.mDestroyPage = false;
  9795. this.showLoadIng();
  9796. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  9797. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  9798. this.seekTo(seekValue + "");
  9799. // this.setProgress()
  9800. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  9801. this.isSeekTo = false;
  9802. // }
  9803. })
  9804. Text(this.totalTime)
  9805. .fontSize($r('app.float.slider_font_size'))
  9806. .fontColor(Color.White)
  9807. .margin(3)
  9808. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  9809. //播放列表
  9810. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9811. Image($r('app.media.hm_playlist'))
  9812. .width($r('app.float.control_image_width'))
  9813. .fillColor(Color.White)
  9814. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9815. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  9816. height: '95%',
  9817. dragBar: true,
  9818. showClose: true,
  9819. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9820. blurStyle: BlurStyle.Thin,
  9821. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  9822. title: {
  9823. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  9824. + `(${this.songList.length}首)`
  9825. }
  9826. })
  9827. }
  9828. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  9829. .animation({
  9830. duration: 666,
  9831. curve: 'ease-in-out' // 可选动画曲线
  9832. })
  9833. .backgroundColor(Color.Transparent)
  9834. .margin({ right: 20, left: 10 })
  9835. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9836. .onClick(() => {
  9837. this.isShowSheetView = !this.isShowSheetView;
  9838. if (this.isPlayListBgGrass) {
  9839. this.isFrontWhite = true
  9840. } else {
  9841. this.isFrontWhite = false
  9842. }
  9843. this.scrollIndex()
  9844. })
  9845. }
  9846. //x5的竖屏模式需要99%
  9847. .width(this.isPhonePortrait() ? '93.4%'
  9848. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  9849. .height(this.isPhoneLan() ? 25 : 33)
  9850. .animation({
  9851. duration: 666,
  9852. curve: 'ease-in-out' // 可选动画曲线
  9853. })
  9854. }
  9855. isBigScreen() {
  9856. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  9857. return true
  9858. }
  9859. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  9860. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  9861. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  9862. return false
  9863. } else {
  9864. return true
  9865. }
  9866. return false
  9867. }
  9868. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  9869. @State isCoverRectangle: boolean = false
  9870. // 添加控制缩放的状态变量
  9871. @State scaleValueImage: number = 1
  9872. @State scaleValueText: number = 1
  9873. @Builder
  9874. CoverInfo() {
  9875. Column() {
  9876. Stack() {
  9877. Column() {
  9878. //方形封面布局
  9879. if (this.isCoverRectangle) {
  9880. this.RectangleCoverView()
  9881. } else {
  9882. //圆形封面布局
  9883. this.CicleCoverView()
  9884. }
  9885. this.musicNameInfo(false)
  9886. if (this.isPhoneLan()) {
  9887. Text(this.name)
  9888. .fontSize(18)
  9889. .fontWeight(FontWeight.Bold)
  9890. .margin({ top: 13 })
  9891. .textOverflow({ overflow: TextOverflow.Ellipsis })
  9892. .maxLines(1)
  9893. .width('99%')
  9894. .textAlign(TextAlign.Center)
  9895. .fontColor(Color.White)
  9896. }
  9897. }
  9898. .width('100%')
  9899. Column({ space: 8 }) {
  9900. Text(this.name)
  9901. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  9902. .fontWeight(FontWeight.Bold)
  9903. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9904. .maxLines(1)
  9905. .width('85%')
  9906. .textAlign(TextAlign.Center)
  9907. .fontColor(Color.White)
  9908. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  9909. Text(this.artist)
  9910. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  9911. .fontColor(Color.White)
  9912. .fontWeight(FontWeight.Bold)
  9913. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  9914. }
  9915. .justifyContent(FlexAlign.Start)
  9916. .zIndex(1)
  9917. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  9918. }
  9919. .margin({
  9920. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  9921. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  9922. top: this.isCoverOpacity() ? 0 : 20
  9923. })
  9924. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  9925. this.SingleLyricView()
  9926. }
  9927. if (this.isPhoneLan()) {
  9928. Column() {
  9929. this.playCenterView()
  9930. // this.playProgressView()
  9931. }
  9932. .position({ left: 28, bottom: 38 })
  9933. } else {
  9934. this.BottomControl()
  9935. }
  9936. }
  9937. .width(CommonConstants.FULL_PERCENT)
  9938. .clip(true)
  9939. }
  9940. //方形封面布局
  9941. @Builder
  9942. RectangleCoverView(){
  9943. Stack({alignContent:Alignment.Center}){
  9944. Image(this.cover)
  9945. .height(this.isHiCar()?(px2vp(this.windowHeight)*0.43):
  9946. this.isCoverOpacity()?(px2vp(this.windowHeight)*0.54):'auto')
  9947. .width(this.isHiCar()||this.isCoverOpacity()?'auto':this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '88%')
  9948. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  9949. .alt($r('app.media.alt'))
  9950. .margin({ right: 8, left: 8, top: 8 })
  9951. .aspectRatio(1)
  9952. .geometryTransition('cover') // 绑定标识符
  9953. .opacity(this.opacityValueImage)
  9954. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  9955. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  9956. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  9957. .clip(true)
  9958. .rotate({
  9959. x: 0,
  9960. y: 0,
  9961. z: 1,
  9962. angle: this.rotateAngle
  9963. })
  9964. .shadow({
  9965. radius: 22,
  9966. type: ShadowType.BLUR,
  9967. color: 'on_primary'
  9968. })
  9969. .onClick(() => {
  9970. this.isMusicBGCover = !this.isMusicBGCover
  9971. })
  9972. }
  9973. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  9974. // 设置左下角为缩放中心点
  9975. centerX: '0%',
  9976. centerY: '100%' })
  9977. }
  9978. @Builder
  9979. CicleCoverView() {
  9980. //圆形封面布局
  9981. Stack({alignContent:Alignment.Center}) {
  9982. Image($r('app.media.ic_music_disc'))
  9983. .width(245)
  9984. .height(245)
  9985. .margin({ right: 20, left: 20 ,top:this.isCoverRectangle||this.isLandscape?0:50 })
  9986. .aspectRatio(1)
  9987. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  9988. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  9989. .borderRadius('100%')
  9990. .align(Alignment.Center)
  9991. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  9992. .rotate({
  9993. angle: this.rotateAngle,
  9994. centerX: "50%",
  9995. centerY: "50%",
  9996. })
  9997. .animation({
  9998. duration: 100,
  9999. curve: Curve.Linear
  10000. })
  10001. .shadow({
  10002. radius: 22,
  10003. type: ShadowType.BLUR,
  10004. color: 'on_primary'
  10005. })
  10006. Image(this.cover)
  10007. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  10008. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 168))
  10009. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  10010. .alt($r('app.media.alt'))
  10011. // .geometryTransition('cover') // 绑定标识符
  10012. .margin({ right: 20, left: 20,
  10013. top:this.isCoverRectangle||this.isLandscape?0:50})
  10014. .aspectRatio(1)
  10015. .opacity(this.opacityValueImage)
  10016. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  10017. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  10018. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  10019. .align(Alignment.Center)//
  10020. .clip(true)
  10021. .shadow({
  10022. radius: 22,
  10023. type: ShadowType.BLUR,
  10024. color: 'on_primary'
  10025. })
  10026. .rotate({
  10027. x: 0,
  10028. y: 0,
  10029. z: 1,
  10030. angle: this.rotateAngle
  10031. })
  10032. .onClick(() => {
  10033. this.isMusicBGCover = !this.isMusicBGCover
  10034. })
  10035. // 唱针以左上角为点选择逆时针40度
  10036. Image($r('app.media.ic_music_cover_hand'))
  10037. .height(130)
  10038. .margin({ bottom: 200, top: 0 })
  10039. // .position({ x: this.windowWidth/2, y: 0 })
  10040. .align(Alignment.Top)
  10041. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  10042. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  10043. .visibility(this.isHiCar()||this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  10044. }
  10045. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  10046. // 设置左下角为缩放中心点
  10047. centerX: '0%',
  10048. centerY: '100%' })
  10049. }
  10050. @Builder
  10051. private musicNameInfo(isHidden: boolean) {
  10052. Row(){
  10053. Column({ space: 8 }) {
  10054. Text(this.name)
  10055. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 20)
  10056. .fontWeight(FontWeight.Bold)
  10057. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  10058. .maxLines(1)
  10059. .width('99%')
  10060. .textAlign(TextAlign.Start)
  10061. .fontColor(Color.White)
  10062. Text(this.artist + ' ' + this.currentSong?.album)
  10063. .fontSize(this.isCoverOpacity() ? 12 : 15)
  10064. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  10065. .fontColor(Color.White)
  10066. .textAlign(TextAlign.Start)
  10067. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  10068. .width('99%')
  10069. .maxLines(1)
  10070. }
  10071. .zIndex(1)
  10072. .layoutWeight(1)
  10073. .margin({ left: 15 })
  10074. Blank()
  10075. Row(){
  10076. Button({type:ButtonType.Circle,stateEffect:true}){
  10077. //添加或取消收藏
  10078. SymbolGlyph(Utility.getIsFav(this.favList,this.currentSong)?
  10079. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'))
  10080. .fontSize(22)
  10081. .fontColor([Color.White])
  10082. .alignSelf(ItemAlign.Center)
  10083. // .width(24)
  10084. .clickEffect({level:ClickEffectLevel.MIDDLE})
  10085. .aspectRatio(CommonConstants.ASPECT_RATIO)
  10086. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  10087. .onClick(async () => {
  10088. if(this.currentSong){
  10089. this.doFav(this.currentSong)
  10090. }
  10091. })
  10092. }
  10093. .margin({ left: 8,right:8 })
  10094. .backgroundColor(Color.Transparent)
  10095. .width(45)
  10096. .height(45)
  10097. }
  10098. }
  10099. .width(this.isLandscape?'83%':'90%')
  10100. .scale({ x: this.scaleValueText, y: this.scaleValueText }) // 添加缩放效果
  10101. .margin({ top:this.isCoverRectangle?10: 0 })
  10102. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  10103. }
  10104. @Builder
  10105. private PlayTitle() {
  10106. Row() {
  10107. Row() {
  10108. Image($r('app.media.ic_back_down'))
  10109. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  10110. .hitTestBehavior(HitTestMode.Transparent)
  10111. Text(this.name + ' ' + this.artist)
  10112. .fontColor(Color.White)
  10113. .fontSize($r('app.float.title_font_size'))
  10114. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  10115. .maxLines(1)
  10116. .visibility(Visibility.None)
  10117. .margin({ left: 2, right: 30 })
  10118. }
  10119. .layoutWeight(1)
  10120. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10121. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  10122. .onClick(() => {
  10123. this.setShowPlayFalse()
  10124. })
  10125. Column() {
  10126. AVCastPicker({
  10127. normalColor: Color.White,
  10128. onStateChange: this.onStateVastChange
  10129. })
  10130. .width(24)
  10131. .height(24)
  10132. }
  10133. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  10134. }
  10135. .width(PlayConstants.ROW_WIDTH)
  10136. }
  10137. @Builder
  10138. lyricSettingSheet(isPip: boolean) {
  10139. Scroll() {
  10140. this.lyricSetting(isPip)
  10141. }
  10142. .width('100%')
  10143. .height('100%')
  10144. }
  10145. @Builder
  10146. lyricSetting(isPip: boolean) {
  10147. Column() {
  10148. // 时间调节模块
  10149. if (!isPip) {
  10150. this.BuildTimeControls()
  10151. }
  10152. // 字号控制模块
  10153. this.BuildFontControls(isPip)
  10154. }
  10155. }
  10156. // 歌词时间偏移状态
  10157. @State timeOffset: number = 0.0
  10158. @State currentLyricColor: string = '#FFFFFF'
  10159. @State currentLyricColorPip: string = '#FFFFFF'
  10160. @State currentHighLightLyricColor: string = '#FF4081'
  10161. @State currentHighLightLyricColorPip: string = '#FF4081'
  10162. // 歌词字号状态
  10163. @State currentLyricSize: number = 20
  10164. @State currentLyricSizePip: number = 20
  10165. // 高亮歌词放大倍数
  10166. @State currentHightLyricSize: number = 1.2
  10167. @State currentHightLyricSizePip: number = 1.2
  10168. @State currentLyricLineSpace: number = 10
  10169. @State currentLyricLineSpacePip: number = 10
  10170. @State currentLyricAlignMode: number = 1
  10171. @State currentLyricAlignModePip: number = 1
  10172. @State blurDegree: number = 2
  10173. @State blurDegreePip: number = 2
  10174. @State isShowSelectColor: boolean = false
  10175. @State isShowHLSelectColor: boolean = false
  10176. @State isShowPipBgSelectColor: boolean = false
  10177. @State pipLyWidth: number = 330
  10178. @State pipLyHeight: number = 120
  10179. // 构建颜色选择器
  10180. @Builder
  10181. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  10182. Row({ space: 10 }) {
  10183. HSBColorPicker({
  10184. color: '#FFFFFF',
  10185. radius: 8,
  10186. layout: HSBColorPickerLayout.COLUMN,
  10187. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  10188. '#fa7105'],
  10189. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  10190. this.changeLyricColor(value, isPip, isBGPip)
  10191. })
  10192. .height(250)
  10193. .layoutWeight(1)
  10194. .padding(25)
  10195. }
  10196. .width('66%')
  10197. }
  10198. @State isOpenPip: boolean = false
  10199. @State pipBgIndex: number = 0
  10200. // 构建字号控制器
  10201. @Builder
  10202. BuildFontControls(isPip: boolean) {
  10203. Column() {
  10204. if (isPip) {
  10205. Column() {
  10206. Row() {
  10207. Text('悬浮歌词')
  10208. .margin({ left: 18 })
  10209. .fontSize(15)
  10210. .fontColor(Color.White)
  10211. .fontWeight(480)
  10212. .layoutWeight(1)
  10213. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  10214. .selectedColor(this.themeColor)
  10215. .switchPointColor(Color.White)
  10216. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10217. .margin({ right: 18 })
  10218. .onChange((checked: boolean) => {
  10219. this.isOpenPip = checked;
  10220. if (this.isOpenPip) {
  10221. this.startPip()
  10222. } else {
  10223. this.stopPip()
  10224. }
  10225. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  10226. })
  10227. .width(50)
  10228. .height(30);
  10229. }
  10230. .height(55)
  10231. }
  10232. .backgroundColor(Color.Transparent)
  10233. .borderRadius(15)
  10234. .margin({
  10235. left: 30,
  10236. right: 30,
  10237. top: 0,
  10238. bottom: 20
  10239. })
  10240. .padding(0)
  10241. .border({
  10242. color: Color.White,
  10243. width: 1.8
  10244. })
  10245. }else{
  10246. Column() {
  10247. Row() {
  10248. Text('单行歌词')
  10249. .margin({ left: 18 })
  10250. .fontSize(15)
  10251. .fontColor(Color.White)
  10252. .fontWeight(480)
  10253. .layoutWeight(1)
  10254. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  10255. .selectedColor(this.themeColor)
  10256. .switchPointColor(Color.White)
  10257. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10258. .margin({ right: 18 })
  10259. .onChange((checked: boolean) => {
  10260. this.isShowSingleLineLyric = checked;
  10261. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  10262. })
  10263. .width(50)
  10264. .height(30);
  10265. }
  10266. .height(55)
  10267. }
  10268. .backgroundColor(Color.Transparent)
  10269. .borderRadius(15)
  10270. .margin({
  10271. left: 30,
  10272. right: 30,
  10273. top: 10,
  10274. bottom: 10
  10275. })
  10276. .padding(0)
  10277. .border({
  10278. color: Color.White,
  10279. width: 1.8
  10280. })
  10281. }
  10282. Row() {
  10283. Text(`歌词居中:`)
  10284. .fontSize(14)
  10285. .fontColor(Color.White)
  10286. .margin({ left: 2 })
  10287. Row() {
  10288. ForEach(['居中', '居左'], (size: string, index: number) => {
  10289. Button(size)
  10290. .width(60)
  10291. .height(28)
  10292. .fontSize(12)
  10293. .fontColor('#FFFFFF')
  10294. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  10295. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  10296. .border({
  10297. color: (!isPip && this.currentLyricAlignMode === index) ||
  10298. (isPip && this.currentLyricAlignModePip === index) ?
  10299. '#007DFF' : '#DDDDDD',
  10300. width: 1.8
  10301. })
  10302. .onClick(() => {
  10303. this.setLyricAlignMode(index, isPip)
  10304. })
  10305. .margin({ left: 10, right: 8 })
  10306. })
  10307. }
  10308. .width('76%')
  10309. Blank()
  10310. }
  10311. .margin({
  10312. top: 10,
  10313. bottom: 10,
  10314. right: 20,
  10315. left: 20
  10316. })
  10317. if (isPip) {
  10318. Row() {
  10319. Text(`悬浮背景:`)
  10320. .fontSize(14)
  10321. .fontColor(Color.White)
  10322. Select([
  10323. { value: CommonConstants.PIP_LYRIC_BG[0] },
  10324. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  10325. .font({ size: 13, weight: FontWeight.Medium })
  10326. .fontColor(Color.White)
  10327. .margin({ left: 10 })
  10328. .selected(this.pipBgIndex)
  10329. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  10330. .onSelect(async (_index: number, text?: string | undefined) => {
  10331. this.pipBgIndex = _index
  10332. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  10333. if (this.pipBgIndex === 0) {
  10334. if (this.cover) {
  10335. this.pipBg = this.cover
  10336. } else {
  10337. this.pipBg = this.imageColor
  10338. }
  10339. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  10340. } else {
  10341. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  10342. }
  10343. })
  10344. Column() {
  10345. }
  10346. .backgroundColor(this.pipBg)
  10347. .margin({ left: 10, right: 10 })
  10348. .borderRadius(20)
  10349. .height(28)
  10350. .width(28)
  10351. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10352. Row() {
  10353. SymbolGlyph($r('sys.symbol.paintbrush'))
  10354. .fontColor([Color.White])
  10355. .effectStrategy(1)
  10356. Text(`选择颜色`)
  10357. .fontSize(13)
  10358. .margin({ left: 10 })
  10359. .fontColor(Color.White)
  10360. }
  10361. }
  10362. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  10363. .backgroundColor(Color.Transparent)
  10364. .border({
  10365. color: '#FFFFFF',
  10366. radius: 20,
  10367. width: 1.8
  10368. })
  10369. .height(36)
  10370. .width(110)
  10371. .onClick(() => {
  10372. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  10373. })
  10374. .bindPopup(this.isShowPipBgSelectColor, {
  10375. builder: this.SelectColor(false, isPip, true),
  10376. placement: Placement.Top,
  10377. mask: { color: '#33000000' },
  10378. enableArrow: false, //是否显示箭头
  10379. showInSubWindow: false,
  10380. onStateChange: (e) => {
  10381. if (!e.isVisible) {
  10382. this.isShowPipBgSelectColor = false
  10383. }
  10384. }
  10385. })
  10386. }
  10387. .width('76%')
  10388. .margin({ bottom: 5, right: 45, left: 20 })
  10389. }
  10390. if (!isPip) {
  10391. Row() {
  10392. Text(`高亮居中:`)
  10393. .fontSize(14)
  10394. .fontColor(Color.White)
  10395. Column() {
  10396. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  10397. .selectedColor(this.themeColor)
  10398. .switchPointColor(Color.White)
  10399. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10400. .onChange((checked: boolean) => {
  10401. this.isHightLightCenter = checked;
  10402. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  10403. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  10404. })
  10405. .width(50)
  10406. .height(30)
  10407. .alignSelf(ItemAlign.Start)
  10408. .margin({ left: 12 })
  10409. Blank()
  10410. }
  10411. .width('76%')
  10412. }
  10413. .margin({
  10414. left: 20,
  10415. right: 15,
  10416. top: 10,
  10417. bottom: 10
  10418. })
  10419. }
  10420. Row() {
  10421. Text(`歌词颜色:`)
  10422. .fontSize(14)
  10423. .fontColor(Color.White)
  10424. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  10425. .fontSize(15)
  10426. .fontColor(Color.White)
  10427. .margin({ left: 12, right: 12 })
  10428. Column() {
  10429. }
  10430. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  10431. .margin({ right: 12 })
  10432. .borderRadius(20)
  10433. .height(28)
  10434. .width(28)
  10435. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10436. Row() {
  10437. SymbolGlyph($r('sys.symbol.paintbrush'))
  10438. .fontColor([Color.White])
  10439. .effectStrategy(1)
  10440. Text(`选择颜色`)
  10441. .fontSize(13)
  10442. .margin({ left: 10 })
  10443. .fontColor(Color.White)
  10444. }
  10445. }
  10446. .backgroundColor(Color.Transparent)
  10447. .border({
  10448. color: '#FFFFFF',
  10449. radius: 20,
  10450. width: 1.8
  10451. })
  10452. .height(36)
  10453. .width(110)
  10454. .onClick(() => {
  10455. this.isShowSelectColor = !this.isShowSelectColor
  10456. })
  10457. .bindPopup(this.isShowSelectColor, {
  10458. builder: this.SelectColor(false, isPip),
  10459. placement: Placement.Top,
  10460. mask: { color: '#33000000' },
  10461. enableArrow: false, //是否显示箭头
  10462. showInSubWindow: false,
  10463. onStateChange: (e) => {
  10464. if (!e.isVisible) {
  10465. this.isShowSelectColor = false
  10466. }
  10467. }
  10468. })
  10469. }
  10470. .width('76%')
  10471. .margin({
  10472. top: 10,
  10473. bottom: 10,
  10474. right: 45,
  10475. left: 20
  10476. })
  10477. Row() {
  10478. Text(`高亮颜色:`)
  10479. .fontSize(14)
  10480. .fontColor(Color.White)
  10481. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  10482. .fontSize(15)
  10483. .fontColor(Color.White)
  10484. .margin({ left: 12, right: 12 })
  10485. Column() {
  10486. }
  10487. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  10488. .margin({ right: 12 })
  10489. .borderRadius(20)
  10490. .height(28)
  10491. .width(28)
  10492. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10493. Row() {
  10494. SymbolGlyph($r('sys.symbol.paintbrush'))
  10495. .fontColor([Color.White])
  10496. .effectStrategy(1)
  10497. Text(`选择颜色`)
  10498. .fontSize(13)
  10499. .margin({ left: 10 })
  10500. .fontColor(Color.White)
  10501. }
  10502. }
  10503. .backgroundColor(Color.Transparent)
  10504. .border({
  10505. color: '#FFFFFF',
  10506. radius: 20,
  10507. width: 1.8
  10508. })
  10509. .height(36)
  10510. .width(110)
  10511. .onClick(() => {
  10512. this.isShowHLSelectColor = !this.isShowHLSelectColor
  10513. })
  10514. .bindPopup(this.isShowHLSelectColor, {
  10515. builder: this.SelectColor(true, isPip),
  10516. placement: Placement.Top,
  10517. mask: { color: '#33000000' },
  10518. enableArrow: false, //是否显示箭头
  10519. showInSubWindow: false,
  10520. onStateChange: (e) => {
  10521. if (!e.isVisible) {
  10522. this.isShowHLSelectColor = false
  10523. }
  10524. }
  10525. })
  10526. }
  10527. .width('76%')
  10528. .margin({
  10529. top: 10,
  10530. bottom: 10,
  10531. right: 45,
  10532. left: 20
  10533. })
  10534. if (isPip) {
  10535. Row() {
  10536. Text(`显示宽度:`)
  10537. .fontSize(14)
  10538. .fontColor(Color.White)
  10539. Slider({
  10540. value: this.pipLyWidth,
  10541. min: 10,
  10542. max: 800,
  10543. step: 1,
  10544. style: SliderStyle.OutSet
  10545. })
  10546. .blockColor(this.themeColor)
  10547. .trackColor($r('app.color.speed_text_color'))
  10548. .selectedColor(Color.White)
  10549. .trackThickness(6)
  10550. .onChange((value: number) => {
  10551. this.pipLyWidth = value
  10552. if (this.pipController) {
  10553. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10554. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  10555. }
  10556. })
  10557. .width('76%')
  10558. }
  10559. .margin({
  10560. left: 20,
  10561. right: 15,
  10562. top: 5,
  10563. bottom: 5
  10564. })
  10565. Row() {
  10566. Text(`显示高度:`)
  10567. .fontSize(14)
  10568. .fontColor(Color.White)
  10569. Slider({
  10570. value: this.pipLyHeight,
  10571. min: 10,
  10572. max: 1000,
  10573. step: 1,
  10574. style: SliderStyle.OutSet
  10575. })
  10576. .blockColor(this.themeColor)
  10577. .trackColor($r('app.color.speed_text_color'))
  10578. .selectedColor(Color.White)
  10579. .trackThickness(6)
  10580. .onChange((value: number) => {
  10581. this.pipLyHeight = value
  10582. if (this.pipController) {
  10583. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10584. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  10585. }
  10586. })
  10587. .width('76%')
  10588. }
  10589. .margin({
  10590. left: 20,
  10591. right: 15,
  10592. top: 5,
  10593. bottom: 5
  10594. })
  10595. }
  10596. Row() {
  10597. Text(`歌词字号:`)
  10598. .fontSize(14)
  10599. .fontColor(Color.White)
  10600. Slider({
  10601. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  10602. min: 12,
  10603. max: 30,
  10604. step: 0.1,
  10605. style: SliderStyle.OutSet
  10606. })
  10607. .blockColor(this.themeColor)
  10608. .trackColor($r('app.color.speed_text_color'))
  10609. .selectedColor(Color.White)
  10610. .trackThickness(6)
  10611. .onChange((value: number) => {
  10612. this.setLyricTextSize(value, isPip)
  10613. })
  10614. .width('76%')
  10615. }
  10616. .margin({
  10617. left: 20,
  10618. right: 15,
  10619. top: 5,
  10620. bottom: 5
  10621. })
  10622. Row() {
  10623. Text(`高亮倍数:`)
  10624. .fontSize(14)
  10625. .fontColor(Color.White)
  10626. Slider({
  10627. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  10628. min: 1,
  10629. max: 2,
  10630. step: 0.1,
  10631. style: SliderStyle.OutSet
  10632. })
  10633. .blockColor(this.themeColor)
  10634. .trackColor($r('app.color.speed_text_color'))
  10635. .selectedColor(Color.White)
  10636. .trackThickness(6)
  10637. .onChange((value: number) => {
  10638. this.setHighLyricTextSize(value, isPip)
  10639. })
  10640. .width('76%')
  10641. }
  10642. .margin({
  10643. left: 20,
  10644. right: 15,
  10645. top: 5,
  10646. bottom: 5
  10647. })
  10648. Row() {
  10649. Text(`歌词间隙:`)
  10650. .fontSize(14)
  10651. .fontColor(Color.White)
  10652. Slider({
  10653. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  10654. min: 0,
  10655. max: 100,
  10656. step: 1,
  10657. style: SliderStyle.OutSet
  10658. })
  10659. .blockColor(this.themeColor)
  10660. .trackColor($r('app.color.speed_text_color'))
  10661. .selectedColor(Color.White)
  10662. .trackThickness(6)
  10663. .onChange((value: number) => {
  10664. this.setLyricLineSpace(value, isPip)
  10665. })
  10666. .width('76%')
  10667. }
  10668. .margin({
  10669. left: 20,
  10670. right: 15,
  10671. top: 5,
  10672. bottom: 5
  10673. })
  10674. //取值间隔为100,默认为400,取值越大,字体越粗
  10675. Row() {
  10676. Text(`歌词字重:`)
  10677. .fontSize(14)
  10678. .fontColor(Color.White)
  10679. Slider({
  10680. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  10681. min: 100,
  10682. max: 900,
  10683. step: 100,
  10684. style: SliderStyle.OutSet
  10685. })
  10686. .blockColor(this.themeColor)
  10687. .trackColor($r('app.color.speed_text_color'))
  10688. .selectedColor(Color.White)
  10689. .trackThickness(6)
  10690. .onChange((value: number) => {
  10691. if (isPip) {
  10692. this.lyricTextWeightPip = value
  10693. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  10694. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  10695. } else {
  10696. this.lyricTextWeight = value
  10697. this.lyricController.setTextWeight(this.lyricTextWeight)
  10698. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  10699. }
  10700. })
  10701. .width('76%')
  10702. }
  10703. .margin({
  10704. left: 20,
  10705. right: 15,
  10706. top: 5,
  10707. bottom: 5
  10708. })
  10709. Row() {
  10710. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  10711. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  10712. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  10713. }
  10714. .justifyContent(FlexAlign.Center)
  10715. .margin({ top: 3, bottom: 10 })
  10716. }
  10717. }
  10718. private setBlurDegree(index: number, isPip: boolean) {
  10719. if (isPip) {
  10720. this.blurDegreePip = index
  10721. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  10722. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  10723. } else {
  10724. this.blurDegree = index
  10725. this.lyricController.setBlurDegree(this.blurDegree)
  10726. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  10727. }
  10728. }
  10729. private setLyricAlignMode(index: number, isPip: boolean) {
  10730. if (isPip) {
  10731. this.currentLyricAlignModePip = index
  10732. if (this.currentLyricAlignModePip === 1) {
  10733. this.lyricControllerXF.setAlignMode("left")
  10734. } else {
  10735. this.lyricControllerXF.setAlignMode("center")
  10736. }
  10737. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  10738. } else {
  10739. this.currentLyricAlignMode = index
  10740. if (this.currentLyricAlignMode === 1) {
  10741. this.lyricController.setAlignMode("left")
  10742. } else {
  10743. this.lyricController.setAlignMode("center")
  10744. }
  10745. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  10746. }
  10747. }
  10748. private setLyricTextSize(index: number, isPip: boolean) {
  10749. if (isPip) {
  10750. this.currentLyricSizePip = index
  10751. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  10752. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  10753. } else {
  10754. this.currentLyricSize = index
  10755. this.lyricController.setTextSize(this.currentLyricSize)
  10756. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  10757. }
  10758. }
  10759. private setHighLyricTextSize(scale: number, isPip: boolean) {
  10760. if (isPip) {
  10761. this.currentHightLyricSizePip = scale
  10762. this.lyricControllerXF
  10763. .setHighlightScale(this.currentHightLyricSizePip)
  10764. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  10765. } else {
  10766. this.currentHightLyricSize = scale
  10767. this.lyricController
  10768. .setHighlightScale(this.currentHightLyricSize)
  10769. PreferencesUtil.putSync('HighLyricTextSize', scale)
  10770. }
  10771. }
  10772. private setLyricLineSpace(index: number, isPip: boolean) {
  10773. if (isPip) {
  10774. this.currentLyricLineSpacePip = index
  10775. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  10776. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  10777. } else {
  10778. this.currentLyricLineSpace = index
  10779. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  10780. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  10781. }
  10782. }
  10783. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  10784. LogUtil.info('onecold isBG = ' + isBG)
  10785. if (isBG) { //如果是设置悬浮背景
  10786. this.pipBg = color
  10787. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  10788. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  10789. return
  10790. }
  10791. if (isPip) {
  10792. this.currentLyricColorPip = color
  10793. this.lyricControllerXF
  10794. .setTextColor(this.currentLyricColorPip)
  10795. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  10796. } else {
  10797. this.currentLyricColor = color
  10798. this.lyricController
  10799. .setTextColor(this.currentLyricColor)
  10800. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  10801. }
  10802. }
  10803. private changeLyricHightLightColor(color: string, isPip: boolean) {
  10804. if (isPip) {
  10805. this.currentHighLightLyricColorPip = color
  10806. this.lyricControllerXF
  10807. .setHighlightColor(this.currentHighLightLyricColorPip)
  10808. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  10809. } else {
  10810. this.currentHighLightLyricColor = color
  10811. this.lyricController
  10812. .setHighlightColor(this.currentHighLightLyricColor)
  10813. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  10814. }
  10815. }
  10816. // 构建时间控制器
  10817. @Builder
  10818. BuildTimeControls() {
  10819. Column() {
  10820. // 时间显示
  10821. Text(this.getTimeText())
  10822. .fontSize(18)
  10823. .fontColor(Color.White)
  10824. .margin({ bottom: 10 })
  10825. Row() {
  10826. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  10827. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  10828. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  10829. }
  10830. .justifyContent(FlexAlign.Center)
  10831. }
  10832. .margin({ top: 12, bottom: 8 })
  10833. }
  10834. // 精度按钮组件
  10835. @Builder
  10836. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  10837. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10838. Column() {
  10839. Image(icon)
  10840. .width(28)
  10841. .margin({ bottom: 5 })
  10842. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  10843. Text(label)
  10844. .fontSize(12)
  10845. .fontColor('#FFFFFF')
  10846. }
  10847. }
  10848. .backgroundColor(Color.Transparent)
  10849. .enabled(!this.isButtonDisabled(step))
  10850. .onClick(() => this.handlePrecisionAdjust(step))
  10851. .padding(5)
  10852. .width(66)
  10853. .height(66)
  10854. .margin({ left: 18, right: 18 })
  10855. .border({
  10856. color: '#FFFFFF',
  10857. width: 1.8
  10858. })
  10859. }
  10860. private handlePrecisionAdjust(step: number) {
  10861. if (step === 0) {
  10862. this.timeOffset = 0
  10863. return
  10864. }
  10865. // 精度处理:保留1位小数
  10866. const newOffset = Number((this.timeOffset + step).toFixed(5))
  10867. // 边界保护(±15.0秒)
  10868. if (newOffset < -30.0 || newOffset > 30.0) {
  10869. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  10870. return
  10871. }
  10872. // 状态更新
  10873. this.timeOffset = newOffset
  10874. }
  10875. // 按钮禁用逻辑
  10876. private isButtonDisabled(step: number): boolean {
  10877. const futureOffset = this.timeOffset + step
  10878. return (futureOffset < -30.0) || (futureOffset > 30.0)
  10879. }
  10880. // 时间显示文本升级
  10881. private getTimeText(): string {
  10882. const absValue = Math.abs(this.timeOffset)
  10883. return this.timeOffset === 0
  10884. ? '歌词时间已重置'
  10885. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  10886. }
  10887. // 导入 本地歌词 搜索歌词
  10888. @Builder
  10889. pushLyricButton(icon: Resource, step: number, label: string) {
  10890. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10891. Row() {
  10892. Image(icon)
  10893. .width(14)
  10894. .margin({ left: 13 })
  10895. Text(label)
  10896. .fontSize(12)
  10897. .margin({ left: 6 })
  10898. .fontColor('#FFFFFF')
  10899. }
  10900. }
  10901. .onClick(() => {
  10902. switch (step) {
  10903. case 0:
  10904. this.callFilePickerSelectFileForLyric()
  10905. break;
  10906. case 1:
  10907. //判断有没有设置api
  10908. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  10909. this.isLyricSetting = false
  10910. this.showTipsDialog()
  10911. return
  10912. }
  10913. if (StrUtil.isNotEmpty(this.videoUrl)) {
  10914. ToastUtil.showToast('正在获取')
  10915. this.isLyricSetting = false
  10916. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  10917. this.initLyric(lyricPath, true);
  10918. }
  10919. break;
  10920. }
  10921. })
  10922. .padding(5)
  10923. .width(110)
  10924. .backgroundColor(Color.Transparent)
  10925. .height(40)
  10926. .margin({ left: 6, right: 6 })
  10927. .border({
  10928. color: '#FFFFFF',
  10929. radius: 20,
  10930. width: 1.8
  10931. })
  10932. }
  10933. showVipDialog() {
  10934. DialogHelper.showCustomContentDialog({
  10935. dialogId: 'vip',
  10936. title: "友情提示",
  10937. autoCancel: false, //点击遮障层时,不关闭弹窗
  10938. backCancel: true, //点击返回键,不关闭弹窗
  10939. contentBuilder: () => {
  10940. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  10941. },
  10942. buttons: [],
  10943. })
  10944. }
  10945. //去赞助的自定义内容
  10946. @Builder
  10947. customVipBuilder(content: string) {
  10948. Column() {
  10949. Text(content)
  10950. .fontColor(Color.Gray)
  10951. .fontSize(16)
  10952. .alignSelf(ItemAlign.Start)
  10953. .margin({ bottom: 15 })
  10954. .fontSize(16)
  10955. Row() {
  10956. Button('取消')
  10957. .fontColor(Color.White)
  10958. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  10959. .height(50)
  10960. .layoutWeight(1)
  10961. .stateEffect(true)
  10962. .margin({ right: 6 })
  10963. .onClick(() => {
  10964. DialogHelper.closeDialog('vip'); //关闭弹框
  10965. })
  10966. Button('开通')
  10967. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  10968. .layoutWeight(1)
  10969. .height(50)
  10970. .backgroundColor(this.themeColor)
  10971. .stateEffect(true)
  10972. .margin({ left: 6 })
  10973. .onClick(() => {
  10974. DialogHelper.closeDialog('vip'); //关闭弹框
  10975. this.isShowPlay = false
  10976. this.mType = 1 //跳转到用户中心
  10977. // router.pushUrl({
  10978. // url: 'pages/VipPage'
  10979. // }, router.RouterMode.Single);
  10980. })
  10981. }
  10982. }
  10983. .width("100%")
  10984. .padding(10)
  10985. }
  10986. showTipsDialog() {
  10987. DialogHelper.showCustomContentDialog({
  10988. dialogId: 'tips',
  10989. title: "友情提示",
  10990. autoCancel: false, //点击遮障层时,不关闭弹窗
  10991. backCancel: true, //点击返回键,不关闭弹窗
  10992. contentBuilder: () => {
  10993. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  10994. },
  10995. buttons: [],
  10996. })
  10997. }
  10998. @Builder
  10999. customTipsBuilder(content: string) {
  11000. Column() {
  11001. Text(content)
  11002. .fontColor(Color.Gray)
  11003. .fontSize(16)
  11004. .alignSelf(ItemAlign.Start)
  11005. .margin({ bottom: 15 })
  11006. .fontSize(16)
  11007. Row() {
  11008. Button('取消')
  11009. .fontColor(Color.White)
  11010. .backgroundColor(this.themeColor)
  11011. .height(50)
  11012. .layoutWeight(1)
  11013. .stateEffect(true)
  11014. .margin({ right: 6 })
  11015. .onClick(() => {
  11016. DialogHelper.closeDialog('tips'); //关闭弹框
  11017. })
  11018. Button('跳转')
  11019. .fontColor(Color.White)//
  11020. .layoutWeight(1)
  11021. .height(50)
  11022. .backgroundColor(this.themeColor)
  11023. .stateEffect(true)
  11024. .margin({ left: 6 })
  11025. .onClick(() => {
  11026. DialogHelper.closeDialog('tips'); //关闭弹框
  11027. this.isShowEdit = false
  11028. this.longItemFilePath = ''
  11029. // if(this.isGridMusic&&!this.isShowPlay){
  11030. // this.longItemFilePath== ''
  11031. // }else{
  11032. // this.isShowEdit = false
  11033. // }
  11034. this.isShowMoreView = false;
  11035. this.isShowPlay = false
  11036. this.mType = 4
  11037. // router.pushUrl({
  11038. // url: 'pages/SettingPage'
  11039. // }, router.RouterMode.Single);
  11040. })
  11041. }
  11042. }
  11043. .width("100%")
  11044. .padding(10)
  11045. }
  11046. @Builder
  11047. PlayMoreSheet() {
  11048. Column() {
  11049. this.MoreList()
  11050. }
  11051. .width('100%')
  11052. .height('100%')
  11053. }
  11054. @Builder
  11055. MoreList() {
  11056. Scroll() {
  11057. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  11058. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  11059. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  11060. Row() {
  11061. if (more.id === 3&&this.currentSong) {
  11062. Image(more.image)
  11063. .width(24)
  11064. .height(24)
  11065. .margin({ left: 10, right: 10 })
  11066. Text(more.title)
  11067. .fontSize(16)
  11068. .fontColor(Color.White)
  11069. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  11070. height: '99%',
  11071. dragBar: true,
  11072. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11073. showClose: true,
  11074. blurStyle: BlurStyle.Thin,
  11075. backgroundColor: Color.Transparent,
  11076. title: { title: '歌曲信息' }
  11077. })
  11078. } else if (more.id === 15 && this.currentSong) { //编辑标签
  11079. Image(more.image)
  11080. .width(24)
  11081. .height(24)
  11082. .margin({ left: 10, right: 10 })
  11083. Text(more.title)
  11084. .fontSize(16)
  11085. .fontColor(Color.White)
  11086. } else if (more.id === 5) { //定时关闭
  11087. Image(more.image)
  11088. .width(24)
  11089. .height(24)
  11090. .margin({ left: 10, right: 10 })
  11091. Text(more.title)
  11092. .fontSize(16)
  11093. .fontColor(Color.White)
  11094. .onClick(() => {
  11095. this.doMore(more.id)
  11096. })
  11097. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  11098. height: this.isCoverOpacity() ? '95%' : '95%',
  11099. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11100. dragBar: true,
  11101. showClose: true,
  11102. title: { title: $r('app.string.time_close') }
  11103. })
  11104. } else if (more.id === 2) { //歌词设置
  11105. Image(more.image)
  11106. .width(24)
  11107. .height(24)
  11108. .margin({ left: 10, right: 10 })
  11109. Text(more.title)
  11110. .fontSize(16)
  11111. .fontColor(Color.White)
  11112. } else if (more.id === 16) { //悬浮歌词设置
  11113. Image(more.image)
  11114. .width(24)
  11115. .height(24)
  11116. .margin({ left: 10, right: 10 })
  11117. Text(more.title)
  11118. .fontSize(16)
  11119. .fontColor(Color.White)
  11120. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  11121. height: '99%',
  11122. dragBar: true,
  11123. preferType: SheetType.CENTER,
  11124. showClose: true,
  11125. blurStyle: BlurStyle.Thin,
  11126. backgroundColor: Color.Transparent,
  11127. title: { title: '悬浮歌词' }
  11128. })
  11129. } else if (more.id === 11) {
  11130. Image(more.image)
  11131. .width(24)
  11132. .height(24)
  11133. .margin({ left: 10, right: 10 })
  11134. Text(more.title)
  11135. .fontSize(16)
  11136. .fontColor(Color.White)
  11137. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  11138. height: this.isCoverOpacity() ? '95%' : '60%',
  11139. dragBar: true,
  11140. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11141. showClose: true,
  11142. blurStyle: BlurStyle.Thin,
  11143. backgroundColor: Color.Transparent,
  11144. title: { title: '跳过头尾' }
  11145. })
  11146. } else if (more.id === 12) { //投播
  11147. AVCastPicker({
  11148. customPicker: (): void => this.TPImageBuilder(more),
  11149. onStateChange: (state) => {
  11150. if (state == AVCastPickerState.STATE_APPEARING) {
  11151. console.log(' The picker starts showing.');
  11152. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  11153. console.log(' The picker finishes presenting.');
  11154. }
  11155. },
  11156. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  11157. sessionType: 'video'
  11158. })
  11159. .id('AVCastPicker')
  11160. } else {
  11161. Image(more.image)
  11162. .width(24)
  11163. .height(24)
  11164. .fillColor(Color.White)
  11165. .margin({ left: 10, right: 10 })
  11166. .onClick(() => {
  11167. this.doMore(more.id)
  11168. })
  11169. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  11170. .fontSize(16)
  11171. .fontColor(Color.White)
  11172. .onClick(() => {
  11173. this.doMore(more.id)
  11174. })
  11175. Select([//倍速
  11176. { value: '0.25x' },
  11177. { value: '0.5x' },
  11178. { value: '0.75x' },
  11179. { value: '1x' },
  11180. { value: '1.25x' },
  11181. { value: '1.5x' },
  11182. { value: '1.75x' },
  11183. { value: '2x' },
  11184. { value: '3x' }])
  11185. .font({ size: 16, weight: FontWeight.Medium })
  11186. .fontColor($r('sys.color.white'))
  11187. .margin({ left: 25 })
  11188. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  11189. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  11190. .value(Utility.optimizedFormat(this.playSpeed))
  11191. .onSelect(async (_index: number, text?: string | undefined) => {
  11192. let speed = parseFloat(text?.replace('x', '') || '1');
  11193. if (!CommonConstants.video_speed_list.includes(speed)) {
  11194. speed = 1;
  11195. }
  11196. this.playSpeed = speed
  11197. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  11198. })
  11199. Slider({
  11200. value: this.volume,
  11201. min: 0,
  11202. max: 1,
  11203. step: 0.1,
  11204. style: SliderStyle.OutSet
  11205. })
  11206. .margin({ left: 18, right: 8 })
  11207. .blockColor(this.themeColor)
  11208. .trackColor($r('app.color.speed_text_color'))
  11209. .selectedColor(Color.White)
  11210. .trackThickness(9)
  11211. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  11212. .onChange((value: number) => {
  11213. this.volume = value;
  11214. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  11215. PreferencesUtil.putSync('DefalutVolume',this.volume)
  11216. })
  11217. .layoutWeight(1)
  11218. Blank()
  11219. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  11220. .selectedColor(this.themeColor)
  11221. .switchPointColor(Color.White)
  11222. .margin({ right: 15 })
  11223. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11224. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  11225. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11226. if (more.id == 6) {
  11227. this.isMusicMemoryPlay = checked;
  11228. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  11229. if (this.isMusicMemoryPlay) {
  11230. ToastUtil.showToast('记忆播放已开启')
  11231. } else {
  11232. ToastUtil.showToast('记忆播放已关闭')
  11233. }
  11234. }
  11235. })
  11236. .width(48)
  11237. .height(24);
  11238. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  11239. .selectedColor(this.themeColor)
  11240. .switchPointColor(Color.White)
  11241. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11242. .margin({ right: 15 })
  11243. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  11244. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11245. if (more.id == 7) {
  11246. this.isMusicBGCover = checked;
  11247. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  11248. if (this.isMusicBGCover) {
  11249. ToastUtil.showToast('播放背景随音乐封面已开启')
  11250. } else {
  11251. ToastUtil.showToast('播放背景随音乐封面已关闭')
  11252. }
  11253. }
  11254. })
  11255. .width(48)
  11256. .height(24);
  11257. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  11258. .selectedColor(this.themeColor)
  11259. .switchPointColor(Color.White)
  11260. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11261. .margin({ right: 15 })
  11262. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  11263. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11264. if (more.id == 8) {
  11265. this.isSavePlayMode = checked;
  11266. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  11267. if (this.isSavePlayMode) {
  11268. ToastUtil.showToast('保存播放模式已开启')
  11269. } else {
  11270. ToastUtil.showToast('保存播放模式已关闭')
  11271. }
  11272. }
  11273. })
  11274. .width(48)
  11275. .height(24);
  11276. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  11277. .selectedColor(this.themeColor)
  11278. .switchPointColor(Color.White)
  11279. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11280. .margin({ right: 15 })
  11281. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  11282. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11283. if (more.id == 13) {
  11284. this.isCoverRectangle = checked;
  11285. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  11286. if (this.isCoverRectangle) {
  11287. ToastUtil.showToast('封面方形已开启')
  11288. this.animationRoFun()
  11289. } else {
  11290. ToastUtil.showToast('封面圆形已开启')
  11291. this.animationRoFun()
  11292. }
  11293. }
  11294. })
  11295. .width(48)
  11296. .height(24);
  11297. Toggle({ type: ToggleType.Switch, isOn: this.isShowBgLiuGUANG })
  11298. .selectedColor(this.themeColor)
  11299. .switchPointColor(Color.White)
  11300. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11301. .margin({ right: 15 })
  11302. .visibility(more.id == 21 ? Visibility.Visible : Visibility.None)
  11303. .onChange((checked: boolean) => { // 是否开启背景流光效果
  11304. if (more.id == 21) {
  11305. this.isShowBgLiuGUANG = checked;
  11306. PreferencesUtil.putSync('isShowBgLiuGUANG',this.isShowBgLiuGUANG)
  11307. }
  11308. })
  11309. .width(48)
  11310. .height(24);
  11311. }
  11312. }
  11313. .width('100%')
  11314. .height(45)
  11315. .padding(15)
  11316. .backgroundColor(Color.Transparent)
  11317. .borderRadius(12)
  11318. .margin({ bottom: 6 })
  11319. }
  11320. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  11321. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  11322. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  11323. .backgroundColor(Color.Transparent)
  11324. .onClick(() => {
  11325. this.doMore(more.id)
  11326. })
  11327. });
  11328. }
  11329. .width('100%')
  11330. .padding(16)
  11331. }.margin({ bottom: 18 })
  11332. }
  11333. @Builder
  11334. TPImageBuilder(more: MoreItem): void {
  11335. Row() {
  11336. Image($r('app.media.tuoping'))
  11337. .width(22)
  11338. .height(22)
  11339. .margin({ left: 10, right: 10 })
  11340. Text(more.title)
  11341. .fontSize(16)
  11342. .fontColor(Color.White)
  11343. }
  11344. .width('100%')
  11345. .layoutWeight(1)
  11346. .alignItems(VerticalAlign.Center)
  11347. .justifyContent(FlexAlign.Start)
  11348. }
  11349. private moreItems: MoreItem[] = [
  11350. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  11351. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  11352. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  11353. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  11354. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  11355. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  11356. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  11357. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  11358. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  11359. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  11360. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  11361. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  11362. { id: 4, image: $r('app.media.share2'), title: '分享' },
  11363. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  11364. // { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  11365. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  11366. { id : 21, image: $r('app.media.kp_music'), title: '开启背景流光' },
  11367. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  11368. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  11369. ];
  11370. @State isShowBgLiuGUANG: boolean = false;
  11371. @State isShowMoreView: boolean = false;
  11372. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  11373. @State isShowTimeCloseMore: boolean = false
  11374. @State isShowDetailMore: boolean = false
  11375. @State isMusicBGCover: boolean = true
  11376. @State isSavePlayMode: boolean = true
  11377. @State isLyricSetting: boolean = false
  11378. @State isJumpSetting: boolean = false
  11379. @State isShowEdit: boolean = false
  11380. @State showPipLyric: boolean = false
  11381. async setRingTone() {
  11382. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  11383. return
  11384. }
  11385. // 确定后的逻辑
  11386. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  11387. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  11388. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  11389. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  11390. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  11391. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  11392. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  11393. , this.videoUrl, this.name).then(res => {
  11394. LogUtil.info('onecold setFlag :' + res);
  11395. });
  11396. }
  11397. doMore(moreId: number) {
  11398. switch (moreId) {
  11399. case 2: //歌词
  11400. this.isLyricSetting = !this.isLyricSetting;
  11401. this.isShowMoreView = false
  11402. break;
  11403. case 3: //详情
  11404. this.isShowDetailMore = !this.isShowDetailMore;
  11405. break;
  11406. case 4: //分享
  11407. if (this.currentSong !== undefined) {
  11408. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  11409. }
  11410. this.isShowMoreView = false
  11411. break;
  11412. case 5: //定时关闭
  11413. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  11414. break;
  11415. case 10: //设为铃声
  11416. this.setRingTone()
  11417. this.isShowMoreView = false
  11418. break;
  11419. case 11: //跳过头尾
  11420. this.isJumpSetting = !this.isJumpSetting;
  11421. break;
  11422. case 13: //倍速
  11423. break;
  11424. case 14: //搜索封面
  11425. if (this.currentSong !== undefined) {
  11426. this.doSearchCover(this.currentSong)
  11427. }
  11428. this.isShowMoreView = false
  11429. break;
  11430. case 15: //编辑标签
  11431. this.initEditFields(this.currentSong)
  11432. this.tempLyricContent = this.lyricContent
  11433. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  11434. this.lyricConStr = this.tempLyricContent
  11435. }
  11436. this.isShowEdit = !this.isShowEdit;
  11437. break;
  11438. case 16: //悬浮歌词
  11439. this.showPipLyric = !this.showPipLyric;
  11440. break;
  11441. case 17: //横屏模式
  11442. if (this.isLandscape) {
  11443. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  11444. } else {
  11445. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  11446. }
  11447. this.isShowMoreView = false
  11448. break;
  11449. case 20://AB循环
  11450. this.isABSheet = !this.isABSheet
  11451. break;
  11452. }
  11453. }
  11454. //AB循环
  11455. @State isOpenAB:boolean = false
  11456. @State jumpATime:number = 0
  11457. @State jumpBTime:number = 0
  11458. @State isABSheet:boolean = false
  11459. @Builder
  11460. ABLoopSheet() {
  11461. ABLoopComptent({
  11462. jumpATime:this.jumpATime,
  11463. jumpBTime:this.jumpBTime,
  11464. onClickAItem: async ()=>{
  11465. if(this.mIjkMediaPlayer){
  11466. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  11467. }
  11468. },
  11469. onClickBItem: async ()=>{
  11470. if(this.mIjkMediaPlayer){
  11471. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  11472. if(this.jumpBTime<=this.jumpATime){
  11473. ToastUtil.showToast('设置B点时间不能小于A点时间')
  11474. this.jumpBTime = 0
  11475. }
  11476. }
  11477. },
  11478. onCancleButtonClick: async ()=>{
  11479. this.isOpenAB = false
  11480. this.isABSheet = false
  11481. },
  11482. onStartButtonClick: async ()=>{
  11483. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  11484. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  11485. return
  11486. }
  11487. this.isABSheet = false
  11488. this.startABLoop()
  11489. },
  11490. })
  11491. }
  11492. //开始AB循环
  11493. startABLoop(){
  11494. if(this.mIjkMediaPlayer){
  11495. this.seekTo(this.jumpATime+'')
  11496. this.isOpenAB = true
  11497. }
  11498. }
  11499. /**
  11500. * 切换横竖屏
  11501. *
  11502. */
  11503. setOrientation(orientation: number) {
  11504. this.windowClass.setPreferredOrientation(orientation).then(() => {
  11505. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  11506. }).catch((err: BusinessError) => {
  11507. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  11508. });
  11509. }
  11510. /**
  11511. * 画中画功能(悬浮歌词功能)
  11512. *
  11513. */
  11514. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  11515. pipController?: PiPWindow.PiPController;
  11516. navigationId: string = '';
  11517. @State curState: string = '';
  11518. @State curError: ResourceStr = '';
  11519. @State pipBg: string = '#E8E8E8'
  11520. @State buttonAction: string = '';
  11521. //开启画中画功能
  11522. async startPip() {
  11523. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  11524. if (!this.pipController) {
  11525. await this.createPipController();
  11526. }
  11527. if (!this.pipController) {
  11528. Logger.info(`[${TAG}] pipController create error`);
  11529. return;
  11530. }
  11531. await this.pipController.startPiP();
  11532. }
  11533. async stopPip() {
  11534. if (!this.pipController) {
  11535. Logger.info(`[${TAG}] pipController is not exist`);
  11536. return;
  11537. }
  11538. this.isOpenPip = false
  11539. await this.pipController.stopPiP();
  11540. }
  11541. async createPipController() {
  11542. this.pipController = await PiPWindow.create({
  11543. context: getContext(this),
  11544. componentController: this.xcomponentController,
  11545. navigationId: this.navigationId,
  11546. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  11547. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  11548. customUIController: this.nodeController,
  11549. });
  11550. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  11551. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  11552. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  11553. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  11554. this.onStateChange(state, reason);
  11555. });
  11556. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  11557. this.onActionEvent(event, status);
  11558. });
  11559. }
  11560. destroyPipController() {
  11561. if (!this.pipController) {
  11562. return;
  11563. }
  11564. this.pipController.off('stateChange');
  11565. this.pipController.off('controlPanelActionEvent');
  11566. this.pipController = undefined;
  11567. }
  11568. onStateChange(state: PiPWindow.PiPState, reason: string) {
  11569. switch (state) {
  11570. case PiPWindow.PiPState.ABOUT_TO_START:
  11571. this.curState = 'ABOUT_TO_START';
  11572. this.curError = $r('app.string.current_error_hint');
  11573. break;
  11574. case PiPWindow.PiPState.STARTED:
  11575. this.curState = 'STARTED';
  11576. this.curError = $r('app.string.current_error_hint');
  11577. break;
  11578. case PiPWindow.PiPState.ABOUT_TO_STOP:
  11579. this.curState = 'ABOUT_TO_STOP';
  11580. this.curError = $r('app.string.current_error_hint');
  11581. break;
  11582. case PiPWindow.PiPState.STOPPED:
  11583. this.curState = 'STOPPED';
  11584. this.curError = $r('app.string.current_error_hint');
  11585. this.stopPip()
  11586. this.destroyPipController()
  11587. break;
  11588. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  11589. this.curState = 'ABOUT_TO_RESTORE';
  11590. this.curError = $r('app.string.current_error_hint');
  11591. break;
  11592. case PiPWindow.PiPState.ERROR:
  11593. this.curState = 'ERROR';
  11594. this.curError = reason;
  11595. break;
  11596. default:
  11597. break;
  11598. }
  11599. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  11600. }
  11601. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  11602. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  11603. switch (event) {
  11604. case 'playbackStateChanged':
  11605. if (status === 0) {
  11606. this.pause();
  11607. } else {
  11608. console.info('onecold startPlayOrResumePlay 9869')
  11609. this.startPlayOrResumePlay();
  11610. }
  11611. break;
  11612. case 'nextVideo':
  11613. // 切换到下一个视频
  11614. this.playNext().catch(() => {
  11615. Logger.error('heanup onActionEvent playNext', `播放下一首失败`);
  11616. });
  11617. break;
  11618. case 'previousVideo':
  11619. // 切换到上一个视频
  11620. this.playPrevious().catch(() => {
  11621. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败`);
  11622. });
  11623. break;
  11624. case 'previousVideo':
  11625. // 切换到上一个视频
  11626. this.playPrevious().catch(() => {
  11627. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败:`);
  11628. });
  11629. break;
  11630. default:
  11631. }
  11632. this.buttonAction = event + `-status:${status}`;
  11633. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  11634. }
  11635. /**
  11636. * 画中画功能(悬浮歌词功能)结束
  11637. *
  11638. */
  11639. async doSearchCover(item: VideoItem,title?:string,artist?:string): Promise<string> {
  11640. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  11641. this.isShowMoreView = false;
  11642. this.showTipsDialog();
  11643. return ''; // Return empty string when no API is configured
  11644. }
  11645. if (!item) {
  11646. return ''; // Return empty string if item is undefined
  11647. }
  11648. const titleS = title||item?.name || '';
  11649. const artistS = artist||item?.artist || ''; // Use empty string if artist is missing
  11650. return this.searchCover(item, titleS, artistS); // Await is not needed here as we return the promise directly
  11651. }
  11652. /**
  11653. *api搜索封面
  11654. *item,根据title和artist
  11655. */
  11656. searchCover(item: VideoItem, title: string, artist: string): Promise<string> {
  11657. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  11658. LogUtil.debug("onecold res =" + res);
  11659. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  11660. if (item.filePath == this.currentSong?.filePath) {
  11661. this.cover = res;
  11662. if (this.currentSong) {
  11663. this.currentSong.pixelMapPath = res;
  11664. }
  11665. }
  11666. // Update pixel map path but always return res regardless of success
  11667. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  11668. if (success) {
  11669. this.doUpdateData();
  11670. console.log("onecold 更新音乐封面成功,数据库已同步");
  11671. } else {
  11672. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  11673. }
  11674. // Note: We don't resolve/reject here because we already returned res
  11675. });
  11676. LogUtil.debug("onecold this.cover =" + this.cover);
  11677. }
  11678. return res; // Always return res regardless of updatePixelMapPath result
  11679. });
  11680. }
  11681. @State jumpTopTime: number = 0
  11682. @State jumpEndTime: number = 0
  11683. @State isOpenJump: boolean = false
  11684. @Builder
  11685. JumpTopEndSheet() {
  11686. Scroll() {
  11687. Column() {
  11688. Column() {
  11689. Text('仅对本播放列表有效')
  11690. .fontSize(16)
  11691. .fontColor($r('app.color.text_color'))
  11692. // 跳过头尾
  11693. Column() {
  11694. Row() {
  11695. Text('跳过片头:')
  11696. .fontSize(16)
  11697. .fontColor($r('app.color.text_color'))
  11698. Text(this.jumpTopTime + 's')
  11699. .fontSize(16)
  11700. .fontColor($r('app.color.text_color'))
  11701. }
  11702. .margin({ bottom: 5 })
  11703. Row() {
  11704. Slider({
  11705. value: this.jumpTopTime,
  11706. min: 0,
  11707. max: 120,
  11708. step: 1,
  11709. style: SliderStyle.OutSet
  11710. })
  11711. .blockColor(this.themeColor)
  11712. .trackColor($r('app.color.speed_text_color'))
  11713. .selectedColor(Color.White)
  11714. .trackThickness(8)
  11715. .onChange((value: number) => {
  11716. this.jumpTopTime = value;
  11717. })
  11718. .width('85%')
  11719. }
  11720. .alignItems(VerticalAlign.Top)
  11721. }
  11722. .margin({ top: 10, bottom: 10 })
  11723. // 跳过头尾
  11724. Column() {
  11725. Row() {
  11726. Text('跳过片尾:')
  11727. .fontSize(16)
  11728. .fontColor($r('app.color.text_color'))
  11729. Text(this.jumpEndTime + 's')
  11730. .fontSize(16)
  11731. .fontColor($r('app.color.text_color'))
  11732. }
  11733. .margin({ bottom: 5 })
  11734. Row() {
  11735. Slider({
  11736. value: this.jumpEndTime,
  11737. min: 0,
  11738. max: 120,
  11739. step: 1,
  11740. style: SliderStyle.OutSet
  11741. })
  11742. .blockColor(this.themeColor)
  11743. .trackColor($r('app.color.speed_text_color'))
  11744. .selectedColor(Color.White)
  11745. .trackThickness(8)
  11746. .onChange((value: number) => {
  11747. this.jumpEndTime = value;
  11748. })
  11749. .width('85%')
  11750. }
  11751. .alignItems(VerticalAlign.Top)
  11752. }
  11753. .margin({ top: 10, bottom: 10 })
  11754. Row() {
  11755. Button('保存设置')
  11756. .fontColor(Color.White)
  11757. .layoutWeight(1)
  11758. .height(40)
  11759. .width(80)
  11760. .backgroundColor(this.themeColor)
  11761. .stateEffect(true)
  11762. .margin({ left: 0, bottom: 20 })
  11763. .onClick(async () => {
  11764. if (!Utility.isNoble()) {
  11765. this.isJumpSetting = false
  11766. this.isShowMoreView = false
  11767. this.showVipDialog()
  11768. return
  11769. }
  11770. if (this.currentSong === undefined) {
  11771. return
  11772. }
  11773. if (this.modeType === 0) {
  11774. let parentPath = FileUtil.getParentPath(this.videoUrl)
  11775. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  11776. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  11777. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  11778. } else if (this.modeType === 1) { //媒体库
  11779. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  11780. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  11781. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  11782. } else if (this.modeType === 2) { //艺术家
  11783. if (this.currentSong?.artist) {
  11784. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  11785. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  11786. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  11787. }
  11788. } else if (this.modeType === 3) { //专辑
  11789. if (this.currentSong?.album) {
  11790. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  11791. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  11792. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  11793. }
  11794. }
  11795. ToastUtil.showShort("保存成功")
  11796. this.isJumpSetting = false
  11797. })
  11798. }
  11799. .margin({
  11800. left: 38,
  11801. right: 38,
  11802. top: 10,
  11803. bottom: 10
  11804. })
  11805. .width(120)
  11806. .height(50)
  11807. }
  11808. }
  11809. }
  11810. .width('100%')
  11811. .height('100%')
  11812. }
  11813. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  11814. private onStateVastChange(state: AVCastPickerState) {
  11815. if (state == AVCastPickerState.STATE_APPEARING) {
  11816. console.log('The picker starts showing.');
  11817. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  11818. console.log('The picker finishes presenting.');
  11819. }
  11820. }
  11821. private showSelectLyric() {
  11822. DialogHelper.showActionSheetDialog({
  11823. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  11824. // sheets: ["本地歌词", "搜索歌词"],
  11825. sheets: [
  11826. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  11827. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  11828. ],
  11829. maskColor: Color.Transparent,
  11830. backgroundColor: $r('app.color.bg_card'),
  11831. transition: AnimationHelper.transitionInDown(666),
  11832. onAction: (index) => {
  11833. switch (index) {
  11834. case 0:
  11835. this.callFilePickerSelectFileForLyric()
  11836. break;
  11837. case 1:
  11838. if (StrUtil.isNotEmpty(this.videoUrl)) {
  11839. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  11840. this.initLyric(lyricPath);
  11841. }
  11842. break;
  11843. }
  11844. }
  11845. })
  11846. }
  11847. // 拉起picker选择文件管理器
  11848. async callFilePickerSelectFileForLyric(): Promise<void> {
  11849. try {
  11850. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  11851. DocumentSelectOptions.maxSelectNumber = 1
  11852. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  11853. let documentPicker = new picker.DocumentViewPicker();
  11854. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  11855. Logger.info(TAG,
  11856. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  11857. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  11858. this.saveVideoDatasLyric(DocumentSelectResult)
  11859. }
  11860. }).catch((err: BusinessError) => {
  11861. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  11862. });
  11863. } catch (err) {
  11864. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  11865. }
  11866. }
  11867. async saveVideoDatasLyric(uris: string[]) {
  11868. if (ArrayUtil.isEmpty(uris)) {
  11869. return
  11870. }
  11871. let newUris: string[] = [];
  11872. for (let i = 0; i < uris.length; i++) {
  11873. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  11874. Logger.info(TAG, 'filePath uri: ' + filePath);
  11875. newUris.push(filePath)
  11876. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  11877. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  11878. fileIo.copyFileSync(file.fd, file2.fd)
  11879. fileIo.closeSync(file);
  11880. fileIo.closeSync(file2);
  11881. this.initLyric(filePath,false,false,true)
  11882. }
  11883. }
  11884. private initDelayPlay(context: object) {
  11885. this.mContext = context;
  11886. }
  11887. startPipLyric() {
  11888. if (this.pipController) {
  11889. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  11890. PiPWindow.PiPControlStatus.PLAY);
  11891. }
  11892. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  11893. if (this.isOpenPip) {
  11894. this.startPip()
  11895. } else {
  11896. this.stopPip()
  11897. }
  11898. }
  11899. //startOffset 从cue分轨时间开始播
  11900. private startPlayOrResumePlay(startOffset?:number) {
  11901. //针对dsf文件高采样率,统一转wav播放
  11902. const sampleRate = this.currentSong?.sampleRate||0
  11903. if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  11904. console.info('onecold 采样率 ='+sampleRate)
  11905. let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  11906. console.info('onecold newDsfPath ='+newDsfPath)
  11907. if(!FileUtil.accessSync(newDsfPath)){
  11908. const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  11909. taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  11910. this.videoUrl = newDsfPath
  11911. this.startPlay(startOffset)
  11912. }).catch((e:object)=>{
  11913. console.info("task1 catch e: " + e);
  11914. })
  11915. }else{
  11916. this.videoUrl = newDsfPath
  11917. this.startPlay(startOffset)
  11918. }
  11919. }else{
  11920. this.startPlay(startOffset)
  11921. }
  11922. }
  11923. startPlay(startOffset?:number) {
  11924. this.startPipLyric()
  11925. this.mDestroyPage = false;
  11926. this.animationState = AnimationStatus.Running
  11927. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  11928. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  11929. this.stopProgressTask();
  11930. this.startProgressTask();
  11931. this.play(this.videoUrl.toString(),startOffset);
  11932. }
  11933. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  11934. this.mIjkMediaPlayer.start();
  11935. this.setProgress()
  11936. this.CONTROL_PlayStatus = PlayStatus.PLAY
  11937. }
  11938. this.setIsPlaying(true)
  11939. this.updateSessionPlayState(true)
  11940. this.watchStatus();
  11941. this.updateLastPlayTimeStr(this.videoUrl)
  11942. }
  11943. updateLastPlayTimeStr(filePath: string) {
  11944. // 检查是否为网络音频(WebDAV),如果是则不更新本地数据库
  11945. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  11946. Logger.info(`heanup 检测到网络音频播放,跳过数据库更新: ${filePath}`)
  11947. return;
  11948. }
  11949. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  11950. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  11951. if (success) {
  11952. this.getHistoryList(false)
  11953. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  11954. } else {
  11955. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  11956. }
  11957. });
  11958. }
  11959. private completionNum(num: number): string | number {
  11960. if (num < 10) {
  11961. return '0' + num;
  11962. } else {
  11963. return num;
  11964. }
  11965. }
  11966. private stringForTime(timeMs: number): string {
  11967. let totalSeconds: number | string = (timeMs / 1000);
  11968. let newSeconds: number | string = totalSeconds % 60;
  11969. let minutes: number | string = (totalSeconds / 60) % 60;
  11970. let hours: number | string = totalSeconds / 3600;
  11971. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  11972. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  11973. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  11974. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  11975. if (this.isCurrentTime) {
  11976. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  11977. this.oldSeconds = newSeconds
  11978. } else {
  11979. newSeconds = this.oldSeconds
  11980. }
  11981. }
  11982. newSeconds = this.completionNum(newSeconds);
  11983. if (hours > 0) {
  11984. return hours + ":" + minutes + ":" + newSeconds;
  11985. } else {
  11986. return minutes + ":" + newSeconds;
  11987. }
  11988. }
  11989. private setProgress() {
  11990. let position = this.mIjkMediaPlayer.getCurrentPosition();
  11991. let duration = this.mIjkMediaPlayer.getDuration();
  11992. if (duration <= 0 && this.duration > 0) {
  11993. duration = this.duration;
  11994. }
  11995. let pos = 0;
  11996. if (duration > 0) {
  11997. this.slideEnable = true;
  11998. let curPercent = position / duration;
  11999. pos = curPercent * 100;
  12000. if (pos > this.PROGRESS_MAX_VALUE) {
  12001. this.progressValue = this.PROGRESS_MAX_VALUE
  12002. } else {
  12003. this.progressValue = pos;
  12004. }
  12005. }
  12006. // LogUtils.getInstance()
  12007. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  12008. this.totalTime = this.stringForTime(duration);
  12009. if (position > duration) {
  12010. position = duration;
  12011. }
  12012. this.isCurrentTime = true;
  12013. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  12014. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  12015. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  12016. this.currentTime = this.stringForTime(position);
  12017. this.isCurrentTime = false
  12018. if (this.mIjkMediaPlayer.isPlaying()) {
  12019. this.randomColor =
  12020. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  12021. //如果是开启AB循环
  12022. if(this.isOpenAB){
  12023. if(position >=this.jumpBTime){
  12024. this.seekTo(this.jumpATime+'')
  12025. return
  12026. }
  12027. }
  12028. // 判断是否播放到结束时间
  12029. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  12030. if (position >= duration - this.jumpEndTime * 1000) {
  12031. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  12032. this.CONTROL_PlayStatus = PlayStatus.INIT
  12033. this.startPlayOrResumePlay();
  12034. }else if (this.playType == 2) { //2:正常播放,单曲播完
  12035. this.showRePlay();
  12036. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  12037. this.progressValue = this.PROGRESS_MAX_VALUE;
  12038. this.slideEnable = false;
  12039. this.stop();
  12040. // ToastUtil.showToast('开始重新播放')
  12041. }else{
  12042. this.playNext().catch(() => {
  12043. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  12044. });
  12045. }
  12046. }
  12047. }
  12048. } else {
  12049. this.randomColor = 'rbg(0,0,0)'
  12050. }
  12051. }
  12052. private startProgressTask() {
  12053. let that = this;
  12054. this.updateProgressTimer = setInterval(() => {
  12055. //LogUtils.getInstance().LOGI("startProgressTask");
  12056. if (!that.mDestroyPage) {
  12057. that.setProgress();
  12058. }
  12059. }, 300);
  12060. }
  12061. private stopProgressTask() {
  12062. LogUtils.getInstance().LOGI("stopProgressTask");
  12063. clearInterval(this.updateProgressTimer);
  12064. }
  12065. private showLoadIng() {
  12066. this.loadingVisible = Visibility.Visible;
  12067. this.replayVisible = Visibility.None;
  12068. }
  12069. private hideLoadIng() {
  12070. this.loadingVisible = Visibility.None;
  12071. this.replayVisible = Visibility.None;
  12072. }
  12073. private showRePlay() {
  12074. this.loadingVisible = Visibility.None;
  12075. this.replayVisible = Visibility.Visible;
  12076. }
  12077. private async play(url: string,startOffset?:number) {
  12078. this.isShowBgLiuGUANG = PreferencesUtil.getBooleanSync('isShowBgLiuGUANG', false)
  12079. console.info('onecold this.url 1= '+url)
  12080. if(!url.toLowerCase().startsWith('http')){
  12081. let hasPermission = await PermissionUtil.activatePermission(url)
  12082. console.info('onecold this.hasPermission 1= '+hasPermission)
  12083. if(!url.includes(this.packName)){
  12084. const file = fs.openSync(url)
  12085. this.videoUrl = file.path
  12086. url= this.videoUrl
  12087. }
  12088. console.info('onecold this.hasPermission 1= '+hasPermission)
  12089. console.info('onecold this.videoUrl 1= '+this.videoUrl)
  12090. }
  12091. let that = this;
  12092. that.showLoadIng();
  12093. this.isOpenAB = false
  12094. //设置XComponent回调的context
  12095. if (!!this.mContext) {
  12096. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  12097. }
  12098. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  12099. this.mIjkMediaPlayer.reset();
  12100. }
  12101. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  12102. //设置debug模式
  12103. this.mIjkMediaPlayer.setDebug(false);
  12104. //初始化配置
  12105. this.mIjkMediaPlayer.native_setup();
  12106. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  12107. if(this.volumeSmall){
  12108. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  12109. this.mIjkMediaPlayer.setVolume('1', '1');
  12110. }else{
  12111. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  12112. }
  12113. }else{
  12114. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  12115. }
  12116. //设置视频源
  12117. Logger.info(TAG, `IjkPlayer setDataSource url=${url}`);
  12118. this.mIjkMediaPlayer.setDataSource(url);
  12119. // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
  12120. const headers = new Map<string, string>();
  12121. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  12122. headers.set("Accept", "*/*");
  12123. if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
  12124. &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
  12125. //如果封面为空,则搜索封面
  12126. this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
  12127. }
  12128. // 如果是WebDAV网络音频,使用webdav_account_id获取认证信息(等待完成后再设置一次性头部)
  12129. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type)) {
  12130. Logger.info(`heanup WebDAV歌曲认证 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
  12131. if (this.currentSong.webdav_account_id) {
  12132. try {
  12133. const webdavManager = RemoteDriveManager.getInstance();
  12134. const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  12135. if (webDavHeaders && webDavHeaders.size > 0) {
  12136. webDavHeaders.forEach((value, key) => headers.set(key, value));
  12137. Logger.info(`heanup 成功通过webdav_account_id获取并合并WebDAV认证头`);
  12138. } else {
  12139. Logger.warn(`heanup 通过webdav_account_id获取认证头失败,播放可能无法继续`);
  12140. }
  12141. } catch (error) {
  12142. const err = error as Error;
  12143. Logger.error(`heanup 获取WebDAV认证头时出错: ${err.message}`);
  12144. }
  12145. } else {
  12146. Logger.error(`heanup WebDAV歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法进行认证`);
  12147. }
  12148. }
  12149. // 统一设置带认证的请求头
  12150. // 百度类型也需要特殊请求头
  12151. if (this.currentSong && isBaiduType(this.currentSong.type)) {
  12152. try {
  12153. const webdavManager = RemoteDriveManager.getInstance();
  12154. const baiduHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  12155. baiduHeaders.forEach((value, key) => headers.set(key, value));
  12156. const headerSnapshot: Record<string, string> = {};
  12157. headers.forEach((value, key) => headerSnapshot[key] = value);
  12158. Logger.info(TAG, `Baidu播放请求头: ${JSON.stringify(headerSnapshot)}`);
  12159. } catch (error) {
  12160. Logger.error(`heanup 构建百度请求头失败: ${(error as Error).message}`);
  12161. }
  12162. }
  12163. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  12164. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type)) {
  12165. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  12166. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  12167. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  12168. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  12169. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  12170. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  12171. // 缓冲和播放优化设置
  12172. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  12173. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  12174. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1"); // 预加载启动
  12175. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  12176. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  12177. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  12178. // 网络相关设置
  12179. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  12180. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  12181. // 重连设置
  12182. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  12183. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  12184. } else if (this.currentSong && isBaiduType(this.currentSong.type)) {
  12185. console.log(`heanup 为百度网盘播放设置IjkPlayer选项`);
  12186. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "15000000");
  12187. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "15000000");
  12188. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1");
  12189. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "1");
  12190. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "2097152");
  12191. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "25");
  12192. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", BaiduConstants.USER_AGENT);
  12193. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", "3");
  12194. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http-detect-range-support", "1");
  12195. console.log(`heanup 百度网盘 IjkPlayer 选项设置完成`);
  12196. }
  12197. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  12198. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  12199. // }
  12200. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  12201. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  12202. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  12203. let bufferSize = 50 * 1024 ; // 默认缓冲区大小为1MB
  12204. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  12205. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  12206. //停止预读的最小帧数
  12207. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  12208. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  12209. // 设置其他缓冲相关选项
  12210. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  12211. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  12212. //启动预加载
  12213. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  12214. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  12215. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  12216. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  12217. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  12218. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  12219. // 因此需要播放器丢包,才不会累积延时
  12220. // 这个和第三个参数packet-buffering无关。
  12221. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  12222. // 无限制收流
  12223. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  12224. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  12225. // 屏幕常亮
  12226. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  12227. // 开启hls起播优化 默认是关闭的
  12228. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "fetch_first", "on");
  12229. // 设置超时
  12230. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  12231. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  12232. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  12233. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  12234. // 变速播放
  12235. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  12236. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  12237. let Speed = this.mIjkMediaPlayer.getSpeed()
  12238. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  12239. //是否开启循环播放
  12240. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  12241. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  12242. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  12243. if (height === 0) {
  12244. return;
  12245. }
  12246. const va = width / height;
  12247. const vpa = that.videoParentAspectRatio;
  12248. if (vpa > va) {
  12249. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  12250. } else {
  12251. that.videoWidth = '100%';
  12252. }
  12253. if (width && height) {
  12254. that.videoAspectRatio = width / height;
  12255. }
  12256. LogUtils.getInstance()
  12257. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  12258. that.hideLoadIng();
  12259. }
  12260. }
  12261. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  12262. let mOnPreparedListener: OnPreparedListener = {
  12263. onPrepared: async () => {
  12264. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  12265. try {
  12266. //保存碰一碰分享的当前的歌曲
  12267. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  12268. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  12269. await this.initLyric(lyricPath);
  12270. const applyDuration = (durationMs: number): void => {
  12271. if (durationMs <= 0) {
  12272. return;
  12273. }
  12274. this.duration = durationMs;
  12275. this.durationTime = Math.floor(durationMs / 1000);
  12276. this.durationStringTime = secondToTime(this.durationTime);
  12277. this.totalTime = this.stringForTime(durationMs);
  12278. if (this.currentSong) {
  12279. this.currentSong.duration = this.totalTime;
  12280. try {
  12281. this.avSessionController.setAVMetadataMusic(this.currentSong, durationMs, this.lyricContent);
  12282. } catch (metaError) {
  12283. Logger.warn(TAG, `heanup 首次播放写入AVSession失败: ${(metaError as Error).message}`);
  12284. }
  12285. }
  12286. };
  12287. const fetchBaiduM3u8Duration = async (url: string): Promise<number> => {
  12288. if (!url || !isBaiduType(this.currentSong?.type ?? -1)) {
  12289. return 0;
  12290. }
  12291. const httpRequest = http.createHttp();
  12292. try {
  12293. const response = await httpRequest.request(url, {
  12294. method: http.RequestMethod.GET,
  12295. connectTimeout: 8000,
  12296. readTimeout: 8000,
  12297. expectDataType: http.HttpDataType.STRING,
  12298. header: {
  12299. 'User-Agent': BaiduConstants.STREAMING_USER_AGENT,
  12300. 'Host': 'pan.baidu.com'
  12301. }
  12302. });
  12303. if (response.responseCode !== 200 || typeof response.result !== 'string') {
  12304. return 0;
  12305. }
  12306. const text = response.result;
  12307. if (text.indexOf('#EXTM3U') < 0) {
  12308. return 0;
  12309. }
  12310. const lines = text.split('\n');
  12311. let totalSeconds = 0;
  12312. for (let i = 0; i < lines.length; i++) {
  12313. const line = lines[i].trim();
  12314. if (line.startsWith('#EXTINF:')) {
  12315. const colonIndex = line.indexOf(':');
  12316. if (colonIndex < 0) {
  12317. continue;
  12318. }
  12319. const content = line.substring(colonIndex + 1);
  12320. const commaIndex = content.indexOf(',');
  12321. const numberPart = commaIndex >= 0 ? content.substring(0, commaIndex) : content;
  12322. const seconds = Number(numberPart);
  12323. if (!Number.isNaN(seconds) && seconds > 0) {
  12324. totalSeconds += seconds;
  12325. }
  12326. }
  12327. }
  12328. if (totalSeconds > 0) {
  12329. return Math.floor(totalSeconds * 1000);
  12330. }
  12331. return 0;
  12332. } catch (fetchError) {
  12333. Logger.warn(TAG, `heanup 解析百度M3U8时长失败: ${(fetchError as Error).message}`);
  12334. return 0;
  12335. } finally {
  12336. httpRequest.destroy();
  12337. }
  12338. };
  12339. const fetchDurationFallback = async (): Promise<void> => {
  12340. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  12341. if (durationMs > 0) {
  12342. Logger.info(TAG, `heanup 通过M3U8推导出时长: ${durationMs}ms`);
  12343. applyDuration(durationMs);
  12344. return;
  12345. }
  12346. Logger.warn(TAG, 'heanup 首次播放未拿到时长,保持未知');
  12347. };
  12348. const preparedDuration = this.mIjkMediaPlayer.getDuration();
  12349. console.info("onecold preparedDuration--" + preparedDuration)
  12350. if (preparedDuration > 0) {
  12351. applyDuration(preparedDuration);
  12352. } else {
  12353. fetchDurationFallback();
  12354. }
  12355. setTimeout(() => {
  12356. this.avSessionController.initAvSession(false);
  12357. if (this.duration > 0) {
  12358. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  12359. }
  12360. this.setAvSessionListener();
  12361. this.updateSessionPlayState(true)
  12362. this.setCurrentPlayMode()
  12363. if(startOffset&&startOffset>0){//cue分轨播放
  12364. this.seekTo(startOffset + "");
  12365. this.saveLastPlayList()
  12366. return
  12367. }
  12368. }, 500)
  12369. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12370. let timeoutPlay = 0
  12371. if (StrUtil.isNotEmpty(this.videoUrl) &&
  12372. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  12373. timeoutPlay = 1000
  12374. }
  12375. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  12376. if (this.modeType === 0) { //文件夹
  12377. let parentPath = FileUtil.getParentPath(this.videoUrl)
  12378. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  12379. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  12380. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  12381. } else if (this.modeType === 1) { //媒体库
  12382. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  12383. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  12384. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  12385. } else if (this.modeType === 2) { //艺术家
  12386. if (this.currentSong?.artist) {
  12387. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  12388. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  12389. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  12390. }
  12391. } else if (this.modeType === 3) { //专辑
  12392. if (this.currentSong?.album) {
  12393. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  12394. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  12395. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  12396. }
  12397. }
  12398. this.duration = this.mIjkMediaPlayer.getDuration()
  12399. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  12400. if (this.mIjkMediaPlayer != null) {
  12401. let jumpTopTimeMs = this.jumpTopTime*1000;
  12402. if (jumpTopTimeMs <= this.duration) {
  12403. // 调用 seekTo 方法,跳到指定时间
  12404. if(PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY,true)){
  12405. console.log('onecold jumpTopTime = '+jumpTopTimeMs);
  12406. const position:number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  12407. console.log('onecold position = '+position);
  12408. if (position > jumpTopTimeMs) {
  12409. jumpTopTimeMs = position
  12410. }
  12411. }
  12412. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12413. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  12414. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  12415. }
  12416. }, timeoutPlay)
  12417. } else {
  12418. // 提示用户无法跳过
  12419. ToastUtil.showToast('跳过时间超过视频时长');
  12420. }
  12421. }
  12422. } else {
  12423. this.jumpTopTime = 0
  12424. this.jumpEndTime = 0
  12425. // console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  12426. // console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  12427. // console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  12428. // PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  12429. //记忆播放(每一首都会记忆播放)
  12430. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  12431. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12432. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  12433. this.restorePlaybackPosition() //读取播放记忆功能
  12434. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  12435. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  12436. this.restorePlaybackPosition() //读取播放记忆功能
  12437. }
  12438. this.isFirstStartPlay = false
  12439. }, timeoutPlay)
  12440. } else {
  12441. this.isFirstStartPlay = false
  12442. }
  12443. }
  12444. this.saveLastPlayList()
  12445. } catch (error) {
  12446. let err: BusinessError = error as BusinessError;
  12447. console.error('onecold failed with err: ' + JSON.stringify(err));
  12448. }
  12449. }
  12450. }
  12451. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  12452. let mOnTimedTextListener: OnTimedTextListener = {
  12453. onTimedText: () => {
  12454. }
  12455. }
  12456. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  12457. let mOnCompletionListener: OnCompletionListener = {
  12458. onCompletion: () => {
  12459. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  12460. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  12461. // 异步调用playNext
  12462. this.playNext().catch(() => {
  12463. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  12464. });
  12465. } else if (this.playType == 1) { //1:单片重复播放
  12466. this.CONTROL_PlayStatus = PlayStatus.INIT
  12467. that.startPlayOrResumePlay();
  12468. } else if (this.playType == 2) { //2:正常播放,单曲播完
  12469. that.showRePlay();
  12470. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  12471. that.progressValue = this.PROGRESS_MAX_VALUE;
  12472. that.slideEnable = false;
  12473. that.stop();
  12474. // ToastUtil.showToast('开始重新播放')
  12475. } else if (this.playType == 3) { //3:随机播放
  12476. // 异步调用randomPlay
  12477. this.randomPlay().catch(() => {
  12478. Logger.error('heanup OnCompletionListener randomPlay', `随机播放失败`);
  12479. });
  12480. }
  12481. }
  12482. }
  12483. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  12484. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  12485. onBufferingUpdate: (percent: number) => {
  12486. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  12487. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  12488. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  12489. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  12490. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  12491. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  12492. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  12493. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  12494. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  12495. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  12496. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  12497. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  12498. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  12499. let Looping = this.mIjkMediaPlayer.isLooping()
  12500. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  12501. }
  12502. }
  12503. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  12504. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  12505. onSeekComplete: () => {
  12506. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  12507. console.info('onecold startPlayOrResumePlay 10643')
  12508. that.startPlayOrResumePlay();
  12509. }
  12510. }
  12511. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  12512. let mOnInfoListener: OnInfoListener = {
  12513. onInfo: (what: number, extra: number) => {
  12514. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  12515. that.hideLoadIng();
  12516. }
  12517. }
  12518. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  12519. let mOnErrorListener: OnErrorListener = {
  12520. onError: (what: number, extra: number) => {
  12521. this.stopProgressTask();
  12522. LogUtils.getInstance().LOGI("heanup OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  12523. LogUtils.getInstance().LOGI('heanup 播放错误,歌曲详情:' + JSON.stringify(this.currentSong))
  12524. // 检查是否为WebDAV播放错误
  12525. let isWebDavError = false;
  12526. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.currentSong.filePath) {
  12527. try {
  12528. const globalContext = GlobalContext.getContext();
  12529. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  12530. if (webDavAuthInfo) {
  12531. isWebDavError = true;
  12532. }
  12533. } catch (error) {
  12534. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  12535. }
  12536. }
  12537. if (isWebDavError) {
  12538. Logger.error(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  12539. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  12540. // this.currentWebDavAuthInfo = null;
  12541. Logger.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  12542. // 根据错误代码提供更具体的错误信息
  12543. let errorMessage = "WebDAV播放失败";
  12544. if (what === -1) { // 网络错误
  12545. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  12546. } else if (what === -1004) { // HTTP 404
  12547. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  12548. } else if (what === -1001) { // 超时
  12549. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  12550. } else if (what === -1003) { // 无法解析主机
  12551. errorMessage = "无法连接到WebDAV服务器";
  12552. }
  12553. ToastUtil.showToast(errorMessage);
  12554. } else {
  12555. if (StrUtil.isNotEmpty(this.videoUrl) &&
  12556. !this.videoUrl.startsWith('http://') &&
  12557. !this.videoUrl.startsWith('https://') &&
  12558. !FileUtil.accessSync(this.videoUrl)) {
  12559. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  12560. }
  12561. }
  12562. that.hideLoadIng();
  12563. }
  12564. }
  12565. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  12566. this.mIjkMediaPlayer.setMessageListener();
  12567. this.mIjkMediaPlayer.prepareAsync();
  12568. this.mIjkMediaPlayer.start();
  12569. }
  12570. //保存最后播放的那首歌和已经对应的播放列表
  12571. saveLastPlayList() {
  12572. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  12573. PreferencesUtil.putSync('LastMusicList', this.songList)
  12574. }
  12575. // 清空播放记录
  12576. clearVideoHistory() {
  12577. this.table.clearPlayHistory((success: boolean, error?: string) => {
  12578. if (success) {
  12579. this.historyList = [];
  12580. this.updateListData(this.historyList)
  12581. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  12582. ToastUtil.showToast('清空播放记录成功')
  12583. } else {
  12584. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  12585. }
  12586. });
  12587. }
  12588. public async setAvSessionListener() {
  12589. if (!this.avSessionController) {
  12590. return;
  12591. }
  12592. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  12593. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  12594. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  12595. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  12596. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  12597. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  12598. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  12599. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  12600. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  12601. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  12602. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  12603. }
  12604. setLoopMode() {
  12605. let itype = this.playType + 1
  12606. if (itype >= 4) {
  12607. this.playType = 0
  12608. ToastUtil.showToast('连续播放')
  12609. } else if (itype === 1) {
  12610. this.playType = 1
  12611. ToastUtil.showToast('单曲循环')
  12612. } else if (itype === 2) {
  12613. this.playType = 2
  12614. ToastUtil.showToast('单曲播完')
  12615. } else if (itype === 3) {
  12616. this.playType = 3
  12617. ToastUtil.showToast('随机播放')
  12618. } else if (itype === 0) {
  12619. this.playType = 0
  12620. ToastUtil.showToast('连续播放')
  12621. }
  12622. PreferencesUtil.putSync('musicPlayType', this.playType)
  12623. this.setCurrentPlayMode()
  12624. }
  12625. private sessionSetLoopModeCallback = (mode: number) => {
  12626. if (this.mIjkMediaPlayer != null) {
  12627. ToastUtil.showToast('当前播放模式:' + mode)
  12628. Logger.info('onecold 当前播放模式= ' + mode)
  12629. let hmPlayMode = mode + 1
  12630. if (hmPlayMode >= 4) {
  12631. hmPlayMode = 0
  12632. }
  12633. if (hmPlayMode === 1) {
  12634. this.playType = 1
  12635. ToastUtil.showToast('单曲循环')
  12636. } else if (hmPlayMode === 0) {
  12637. this.playType = 2
  12638. ToastUtil.showToast('单曲播完')
  12639. } else if (hmPlayMode === 3) {
  12640. this.playType = 3
  12641. ToastUtil.showToast('随机播放')
  12642. } else if (hmPlayMode === 2) {
  12643. this.playType = 0
  12644. ToastUtil.showToast('连续播放')
  12645. }
  12646. PreferencesUtil.putSync('musicPlayType', this.playType)
  12647. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  12648. let playBackState: avSession.AVPlaybackState = {
  12649. loopMode: hmPlayMode,
  12650. };
  12651. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  12652. console.info(`set setLoopMode AVPlaybackState successfully`);
  12653. }).catch((err: BusinessError) => {
  12654. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  12655. });
  12656. }
  12657. }
  12658. setCurrentPlayMode() {
  12659. if (!this.avSessionController) {
  12660. return;
  12661. }
  12662. let mLoopMode = 0
  12663. switch (this.playType) {
  12664. case 0:
  12665. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  12666. break;
  12667. case 1:
  12668. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  12669. break;
  12670. case 2:
  12671. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  12672. break;
  12673. case 3:
  12674. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  12675. break;
  12676. }
  12677. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  12678. let playBState: avSession.AVPlaybackState = {
  12679. loopMode: mLoopMode,
  12680. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  12681. };
  12682. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  12683. console.info(`set setLoopMode AVPlaybackState successfully`);
  12684. }).catch((err: BusinessError) => {
  12685. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  12686. });
  12687. }
  12688. private sessionToggleFavoriteCallback = (assetId: string) => {
  12689. if (this.mIjkMediaPlayer != null && this.currentSong) {
  12690. console.info(`on toggleFavorite `);
  12691. // 应用收到收藏命令,进行收藏处理。
  12692. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  12693. this.doFav(this.currentSong)
  12694. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  12695. let playbackState: avSession.AVPlaybackState = {
  12696. isFavorite: !this.isFac,
  12697. };
  12698. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  12699. console.info(`SetAVPlaybackState successfully`);
  12700. }).catch((err: BusinessError) => {
  12701. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  12702. });
  12703. }
  12704. }
  12705. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  12706. device: avSession.OutputDeviceInfo) => {
  12707. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  12708. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  12709. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  12710. await this.startCasting();
  12711. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  12712. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  12713. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  12714. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  12715. if (device) {
  12716. this.endCasting();
  12717. }
  12718. }
  12719. };
  12720. private async startCasting() {
  12721. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  12722. this.setPlaybackStateChangeListener();
  12723. this.pause();
  12724. this.initQueueItem();
  12725. this.prepare();
  12726. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  12727. refToIsCasting?.set(true);
  12728. this.castSeek = true;
  12729. this.isCastPlaying = true;
  12730. }
  12731. async changeCasting() {
  12732. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  12733. this.initQueueItem();
  12734. this.prepare();
  12735. this.setPlaybackStateChangeListener();
  12736. this.isCastPlaying = true;
  12737. this.castSeek = true;
  12738. }
  12739. public endCasting() {
  12740. this.avSessionController.getAvSession()?.stopCasting();
  12741. this.stopCast();
  12742. this.isCastPlaying = false;
  12743. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  12744. refToIsCasting?.set(false);
  12745. this.pause();
  12746. this.setIsPlaying(false);
  12747. // if (this.curIndex === this.curSource.index) {
  12748. // this.play
  12749. // this.seek(this.currentTime * 1000);
  12750. // this.setIsPlaying(true);
  12751. // } else {
  12752. // this.pauseVideo();
  12753. // this.setIsPlaying(false);
  12754. // }
  12755. }
  12756. public setIsPlaying(isPlayer: boolean) {
  12757. this.isPlaying = isPlayer;
  12758. // 发送播放状态变化事件给歌单详情页面
  12759. try {
  12760. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  12761. const currentFilePath = this.currentSong?.filePath || ''
  12762. const eventData: emitter.EventData = {
  12763. data: {
  12764. isPlaying: this.isPlaying,
  12765. curIndex: this.curIndex,
  12766. currentFilePath: currentFilePath
  12767. }
  12768. };
  12769. emitter.emit(eventPlaybackStatus, eventData)
  12770. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  12771. } catch (error) {
  12772. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  12773. }
  12774. }
  12775. private setPlaybackStateChangeListener(): void {
  12776. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  12777. this.castController?.on('endOfStream', this.reloadCasting);
  12778. this.castController?.on('playNext', this.playNextCallback);
  12779. this.castController?.on('playPrevious', this.playPreviousCallback);
  12780. }
  12781. private updateSessionPlayState(isPlay: boolean): void {
  12782. // if(!this.isBgPlayOpen)
  12783. // return
  12784. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  12785. this.setAVSessionPlayState({
  12786. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  12787. position: {
  12788. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  12789. updateTime: new Date().getTime()
  12790. }
  12791. });
  12792. }
  12793. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  12794. this.avSessionController.setAvSessionPlayState(playbackState)
  12795. }
  12796. private positionChange(position: number) {
  12797. this.currentTime2 = position / 1000;
  12798. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  12799. }
  12800. private playDurationChange(duration: number) {
  12801. this.duration = duration;
  12802. this.durationTime = Math.floor(this.duration / 1000);
  12803. this.durationStringTime = secondToTime((this.durationTime));
  12804. }
  12805. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  12806. const duration = playbackState?.extras?.duration;
  12807. if (typeof duration === 'number') {
  12808. this.playDurationChange(duration as number);
  12809. }
  12810. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  12811. this.positionChange(playbackState?.position?.elapsedTime);
  12812. }
  12813. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  12814. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  12815. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  12816. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  12817. this.isCastPlaying = false;
  12818. }
  12819. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  12820. this.isCastPlaying = true;
  12821. }
  12822. };
  12823. private reloadCasting = async () => {
  12824. let item = this.songList[this.curIndex];
  12825. let uri = fileUri.getUriFromPath(item.filePath);
  12826. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  12827. // description.startPosition = 0;
  12828. this.castItem = {
  12829. itemId: this.curIndex,
  12830. description: {
  12831. assetId: item.filePath,
  12832. title: item.name,
  12833. artist: '',
  12834. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  12835. // mediaUri: item.filePath,
  12836. fdSrc: {
  12837. fd: file.fd
  12838. },
  12839. // 该字段大写,音频'AUDIO',视频'VIDEO'
  12840. mediaType: 'VIDEO',
  12841. mediaSize: item.videoSize,
  12842. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  12843. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  12844. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  12845. duration: this.duration,
  12846. // albumCoverUri: 'https://www.example.jpeg',
  12847. // albumTitle: '《ExampleAlbum》',
  12848. appName: this.appName,
  12849. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  12850. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  12851. }
  12852. };
  12853. this.prepare();
  12854. this.isCastPlaying = true;
  12855. };
  12856. public playNextCallback = (): void => {
  12857. this.playNext().catch(() => {
  12858. Logger.error('heanup playNextCallback', `播放下一首失败`);
  12859. });
  12860. };
  12861. public playPreviousCallback = (): void => {
  12862. this.playPrevious().catch(() => {
  12863. Logger.error('heanup playNextCallback', `播放上一首失败`);
  12864. });
  12865. };
  12866. async prepare() {
  12867. await this.castController?.prepare(this.castItem);
  12868. await this.castController?.start(this.castItem);
  12869. }
  12870. public initQueueItem() {
  12871. let item = this.songList[this.curIndex];
  12872. let time = this.currentTime;
  12873. let uri = fileUri.getUriFromPath(item.filePath);
  12874. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  12875. this.castItem = {
  12876. itemId: this.curIndex,
  12877. description: {
  12878. assetId: item.filePath,
  12879. title: item.name,
  12880. artist: '',
  12881. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  12882. fdSrc: {
  12883. fd: file.fd
  12884. },
  12885. // 该字段大写,音频'AUDIO',视频'VIDEO'
  12886. mediaType: 'AUDIO',
  12887. mediaSize: item.videoSize,
  12888. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  12889. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  12890. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  12891. duration: this.duration,
  12892. // albumCoverUri: 'https://www.example.jpeg',
  12893. // albumTitle: '《ExampleAlbum》',
  12894. appName: this.appName,
  12895. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  12896. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  12897. }
  12898. };
  12899. }
  12900. async stopCast() {
  12901. try {
  12902. this.castController?.off('playbackStateChange');
  12903. this.castController?.off('endOfStream');
  12904. this.castController?.off('playNext');
  12905. this.castController?.off('playPrevious');
  12906. this.castController?.off('error');
  12907. } catch (error) {
  12908. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  12909. }
  12910. }
  12911. private sessionPlayCallback = (): void => {
  12912. this.playOrPause()
  12913. };
  12914. private sessionPauseCallback = (): void => {
  12915. this.pause()
  12916. };
  12917. private playOrPause() {
  12918. if (!this.debounce()) {
  12919. return;
  12920. }
  12921. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  12922. this.pause();
  12923. } else {
  12924. console.info('onecold startPlayOrResumePlay 11064')
  12925. this.startPlayOrResumePlay();
  12926. this.playChange()
  12927. }
  12928. }
  12929. private sessionPlayNextCallback = (): void => {
  12930. this.playNext().catch(() => {
  12931. Logger.error('heanup sessionPlayPreviousCallback', `播放下 一首失败`);
  12932. });
  12933. };
  12934. private sessionPlayPreviousCallback = (): void => {
  12935. this.playPrevious().catch(() => {
  12936. Logger.error('heanup sessionPlayPreviousCallback', `播放上一首失败`);
  12937. });
  12938. };
  12939. private sessionStopCallback = (): void => {
  12940. this.stop()
  12941. };
  12942. private sessionFastForwardCallback = (time?: number) => {
  12943. if (!time) {
  12944. return;
  12945. }
  12946. if (this.mIjkMediaPlayer != null) {
  12947. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12948. let seeTime = curPosition + time * 1000;
  12949. // 限制 seekValue 在合法范围内
  12950. if (seeTime < 0) {
  12951. seeTime = 0;
  12952. } else if (seeTime > this.duration) {
  12953. seeTime = this.duration;
  12954. }
  12955. Logger.info('onecold seeTime= ' + seeTime)
  12956. this.setSeekToActionProgress(seeTime)
  12957. this.seekTo(seeTime + "")
  12958. }
  12959. };
  12960. /**
  12961. * Gesture method onActionUpdate.
  12962. *
  12963. * @param event Gesture event.手势拖动设置快进和后退
  12964. */
  12965. private setSeekToActionProgress(position: number) {
  12966. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  12967. let duration = this.mIjkMediaPlayer.getDuration();
  12968. let pos = 0;
  12969. if (duration > 0) {
  12970. this.slideEnable = true;
  12971. let curPercent = position / duration;
  12972. pos = curPercent * 100;
  12973. if (pos > this.PROGRESS_MAX_VALUE) {
  12974. this.progressValue = this.PROGRESS_MAX_VALUE
  12975. } else {
  12976. this.progressValue = pos;
  12977. }
  12978. }
  12979. // LogUtils.getInstance()
  12980. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  12981. this.totalTime = this.stringForTime(duration);
  12982. if (position > duration) {
  12983. position = duration;
  12984. }
  12985. this.isCurrentTime = true;
  12986. this.currentTime = this.stringForTime(position);
  12987. this.isCurrentTime = false
  12988. }
  12989. private sessionRewindCallback = (time?: number) => {
  12990. if (!time) {
  12991. return;
  12992. }
  12993. if (this.mIjkMediaPlayer != null) {
  12994. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12995. let seeTime = curPosition - time * 1000;
  12996. // 限制 seekValue 在合法范围内
  12997. if (seeTime < 0) {
  12998. seeTime = 0;
  12999. } else if (seeTime > this.duration) {
  13000. seeTime = this.duration;
  13001. }
  13002. Logger.info('onecold seeTime= ' + seeTime)
  13003. this.setSeekToActionProgress(seeTime)
  13004. this.seekTo(seeTime + "")
  13005. }
  13006. };
  13007. private sessionSeekCallback = (seekTime: number) => {
  13008. if (this.mIjkMediaPlayer != null) {
  13009. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  13010. this.seekTo(seekTime + "")
  13011. }
  13012. };
  13013. private async getFileSize(filePath: string): Promise<number> {
  13014. try {
  13015. const stat = await fs.stat(filePath);
  13016. return stat.size;
  13017. } catch (err) {
  13018. console.error('Failed to get file size: ' + err.message);
  13019. return 0;
  13020. }
  13021. }
  13022. private pause() {
  13023. if (this.mIjkMediaPlayer.isPlaying()) {
  13024. this.savePlaybackPosition();
  13025. this.mIjkMediaPlayer.pause();
  13026. this.setProgress();
  13027. this.mDestroyPage = true;
  13028. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  13029. this.updateSessionPlayState(false)
  13030. this.playChange()
  13031. if (this.pipController) {
  13032. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  13033. PiPWindow.PiPControlStatus.PAUSE);
  13034. }
  13035. }
  13036. }
  13037. private stop() {
  13038. this.savePlaybackPosition();
  13039. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13040. this.mIjkMediaPlayer.stop();
  13041. this.mIjkMediaPlayer.release();
  13042. this.stopProgressTask();
  13043. this.updateSessionPlayState(false)
  13044. this.playChange()
  13045. this.watchStatus();
  13046. }
  13047. //保持记忆播放功能
  13048. private savePlaybackPosition() {
  13049. if (this.mIjkMediaPlayer != null) {
  13050. const position = this.mIjkMediaPlayer.getCurrentPosition();
  13051. // ToastUtil.showToast('保存记忆播放 = ' + position)
  13052. const duration = this.mIjkMediaPlayer.getDuration();
  13053. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  13054. // 如果播放位置接近视频末尾,则保存 position 为 0
  13055. const playbackPosition = (duration - position < threshold) ? 0 : position;
  13056. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  13057. }
  13058. }
  13059. //获取记忆播放功能
  13060. private restorePlaybackPosition() {
  13061. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  13062. // ToastUtil.showToast('position = ' + position)
  13063. if (this.mIjkMediaPlayer != null && position > 0) {
  13064. // ToastUtil.showToast('seekTo = ' + position)
  13065. this.seekTo(position + "");
  13066. }
  13067. }
  13068. private seekTo(value: string) {
  13069. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  13070. ToastUtil.showToast('wma格式不支持拖动快进。')
  13071. return
  13072. }
  13073. this.isSeekTo = true
  13074. this.mIjkMediaPlayer.seekTo(value);
  13075. console.info('onecold startPlayOrResumePlay 11227')
  13076. // this.startPlayOrResumePlay()
  13077. // 在这里恢复计时器状态
  13078. this.setProgress()
  13079. this.isSeekTo = false
  13080. }
  13081. // 添加到下一首播放
  13082. private addToNextPlay(song: VideoItem) {
  13083. if (!this.debounce()) {
  13084. return;
  13085. }
  13086. if (this.currentSong) {
  13087. if (this.currentSong === song) {
  13088. ToastUtil.showToast('当前已经在播放这首歌了!')
  13089. return
  13090. }
  13091. }
  13092. // 如果未开始播放或队列为空
  13093. if (this.curIndex === -1 || this.songList.length === 0) {
  13094. this.songList = [song];
  13095. this.curIndex = 0;
  13096. this.doPlay(song)
  13097. return;
  13098. }
  13099. // 插入到当前索引+1的位置
  13100. const insertPos = this.curIndex + 1;
  13101. this.songList.splice(insertPos, 0, song);
  13102. this.songList = [...this.songList]; // 触发状态更新
  13103. this.sonDataSource.pushArrayData(this.songList)
  13104. ToastUtil.showToast('已添加至下一首播放')
  13105. }
  13106. //后退10s,可再设置设置默认几秒
  13107. backForward() {
  13108. if(this.mIjkMediaPlayer){
  13109. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  13110. let value = pos - Number(this.fastForwardSeconds) * 1000;
  13111. this.seekTo(value+"");
  13112. }
  13113. }
  13114. //快进10s,可再设置设置默认几秒
  13115. fastForward() {
  13116. if(this.mIjkMediaPlayer){
  13117. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  13118. let value = pos + Number(this.fastForwardSeconds) * 1000;
  13119. this.seekTo(value+"");
  13120. }
  13121. }
  13122. //下一个
  13123. private async playNext() {
  13124. if (!this.debounce()) {
  13125. return;
  13126. }
  13127. if (this.playType == 3) { //3:随机播放
  13128. await this.randomPlay()
  13129. return;
  13130. }
  13131. if (ArrayUtil.isNotEmpty(this.songList)) {
  13132. if (this.curIndex == this.songList.length - 1) {
  13133. this.curIndex = 0;
  13134. } else {
  13135. this.curIndex++;
  13136. }
  13137. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13138. this.stop();
  13139. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  13140. this.currentSong = this.songList[this.curIndex];
  13141. Logger.info('heanup playNext', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  13142. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13143. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13144. context: this.context,
  13145. autoParseMusicName: this.autoParseMusicName
  13146. });
  13147. this.artist = this.songList[this.curIndex].artist
  13148. this.name = this.songList[this.curIndex].name
  13149. //this.cover = this.songList[this.curIndex].pixelMapPath
  13150. this.changeImageAnimation()
  13151. }
  13152. }
  13153. changeImageAnimation() {
  13154. if(this.openSkipSongAnimate){
  13155. // 第一步:淡出动画
  13156. this.getUIContext()?.animateTo({
  13157. duration: 500,
  13158. curve: Curve.EaseOut,
  13159. }, () => {
  13160. this.opacityValueImage = 0.1;
  13161. if(this.isCoverRectangle){
  13162. this.scaleValueImage = 0.88
  13163. }
  13164. });
  13165. // 第二步:切换图片后淡入
  13166. setTimeout(() => {
  13167. this.cover = this.songList[this.curIndex].pixelMapPath
  13168. this.getUIContext()?.animateTo({
  13169. duration: 500,
  13170. curve: Curve.EaseIn,
  13171. }, () => {
  13172. this.opacityValueImage = 1;
  13173. this.scaleValueImage = 1 // 图标恢复到原始大小
  13174. this.startPlayOrResumePlay()
  13175. });
  13176. }, 500);
  13177. }else{
  13178. this.cover = this.songList[this.curIndex].pixelMapPath
  13179. this.startPlayOrResumePlay()
  13180. }
  13181. }
  13182. // 存储已播放的歌曲索引
  13183. private playedIndices: Set<number> = new Set();
  13184. //随机播放
  13185. private async randomPlay() {
  13186. // if (!this.debounce()) {
  13187. // return;
  13188. // }
  13189. if (ArrayUtil.isNotEmpty(this.songList)) {
  13190. if (this.songList.length > 3) {
  13191. // 如果所有歌曲都播放过一次,清空已播放索引集合
  13192. if (this.playedIndices.size === this.songList.length) {
  13193. this.playedIndices.clear();
  13194. }
  13195. // 随机选择一个未播放的歌曲索引
  13196. let newIndex: number;
  13197. // 添加超时机制防止无限循环
  13198. let attempt = 0;
  13199. const maxAttempts = 100; // 根据需求调整
  13200. do {
  13201. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  13202. attempt++;
  13203. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  13204. if (attempt >= maxAttempts) {
  13205. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  13206. newIndex = Math.floor(Math.random() * this.songList.length);
  13207. }
  13208. this.curIndex = newIndex;
  13209. this.playedIndices.add(newIndex);
  13210. } else {
  13211. // 当歌曲数量小于或等于3时,直接播放下一首
  13212. if (this.curIndex == this.songList.length - 1) {
  13213. this.curIndex = 0;
  13214. } else {
  13215. this.curIndex++;
  13216. }
  13217. }
  13218. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13219. this.stop();
  13220. this.currentSong = this.songList[this.curIndex];
  13221. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13222. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13223. context: this.context,
  13224. autoParseMusicName: this.autoParseMusicName
  13225. });
  13226. this.name = this.songList[this.curIndex].name;
  13227. this.artist = this.songList[this.curIndex].artist
  13228. // this.cover = this.songList[this.curIndex].pixelMapPath
  13229. this.changeImageAnimation()
  13230. }
  13231. }
  13232. private async playIndex(index: number) {
  13233. if (!this.debounce()) {
  13234. return;
  13235. }
  13236. if (ArrayUtil.isNotEmpty(this.songList)) {
  13237. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13238. this.stop();
  13239. this.curIndex = index;
  13240. this.currentSong = this.songList[index];
  13241. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13242. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13243. context: this.context,
  13244. autoParseMusicName: this.autoParseMusicName
  13245. });
  13246. this.name = this.currentSong.name
  13247. this.artist = this.currentSong.artist
  13248. this.changeImageAnimation()
  13249. }
  13250. }
  13251. //上一个
  13252. private async playPrevious() {
  13253. if (!this.debounce()) {
  13254. return;
  13255. }
  13256. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  13257. this.randomModePlayFromHistory()
  13258. return;
  13259. }
  13260. if (this.curIndex == 0) {
  13261. this.curIndex = this.songList.length - 1;
  13262. } else {
  13263. this.curIndex--;
  13264. }
  13265. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13266. this.stop();
  13267. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  13268. this.currentSong = this.songList[this.curIndex];
  13269. Logger.info('heanup playPrevious', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  13270. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13271. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13272. context: this.context,
  13273. autoParseMusicName: this.autoParseMusicName
  13274. });
  13275. this.name = this.songList[this.curIndex].name
  13276. this.artist = this.songList[this.curIndex].artist
  13277. this.changeImageAnimation()
  13278. }
  13279. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  13280. private async randomModePlayFromHistory() {
  13281. if (this.historyList.length >= 2) {
  13282. // 播放历史记录的第二首
  13283. const prevSong = this.historyList[1];
  13284. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  13285. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13286. this.stop();
  13287. // 直接使用历史记录中的歌曲信息,历史记录中的数据应该是完整的
  13288. this.currentSong = prevSong;
  13289. Logger.info('heanup randomModePlayFromHistory', `直接使用历史歌曲信息: ${prevSong.name}, type: ${prevSong.type}`);
  13290. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13291. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13292. context: this.context,
  13293. autoParseMusicName: this.autoParseMusicName
  13294. });
  13295. this.cover = prevSong.pixelMapPath
  13296. this.artist = prevSong.artist
  13297. this.name = prevSong.name;
  13298. console.info('onecold startPlayOrResumePlay 11434')
  13299. this.startPlayOrResumePlay();
  13300. } else {
  13301. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  13302. if (this.curIndex === 0) {
  13303. this.curIndex = this.songList.length - 1;
  13304. } else {
  13305. this.curIndex--;
  13306. }
  13307. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13308. this.stop();
  13309. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  13310. this.currentSong = this.songList[this.curIndex];
  13311. Logger.info('heanup randomModePlayFromHistory', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  13312. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13313. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13314. context: this.context,
  13315. autoParseMusicName: this.autoParseMusicName
  13316. });
  13317. this.artist = this.songList[this.curIndex].artist
  13318. this.name = this.songList[this.curIndex].name;
  13319. this.changeImageAnimation()
  13320. }
  13321. }
  13322. debounce() {
  13323. const delay = 600;
  13324. let cur = new Date().getTime();
  13325. if (cur - this.last > delay) {
  13326. this.last = cur;
  13327. return true;
  13328. }
  13329. return false;
  13330. }
  13331. /**
  13332. * Sets whether the screen is a constant based on the playback status.
  13333. */
  13334. watchStatus() {
  13335. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  13336. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  13337. this.windowClass.setWindowKeepScreenOn(true);
  13338. } else {
  13339. this.windowClass.setWindowKeepScreenOn(false);
  13340. }
  13341. }
  13342. /**
  13343. * Volume gesture method onActionStart.
  13344. *
  13345. * @param event Gesture event.
  13346. */
  13347. private customDialogComponentIdMM: number = 0
  13348. @Builder
  13349. customDialogComponentMM() {
  13350. Column() {
  13351. Row() {
  13352. Blank()
  13353. Text('验证密码')
  13354. .fontSize(22)
  13355. .fontColor($r('app.color.pri_bg'))
  13356. .margin({ top: 18 })
  13357. Blank()
  13358. Image($r('app.media.close'))
  13359. .fillColor(Color.White)
  13360. .margin({ top: 18, right: 18 })
  13361. .width(20)
  13362. .onClick(() => {
  13363. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  13364. })
  13365. }
  13366. .width('100%') // 使Row占据整个宽度
  13367. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  13368. Verify({
  13369. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  13370. });
  13371. }.height('60%')
  13372. .backgroundColor($r('app.color.index_background'))
  13373. .justifyContent(FlexAlign.SpaceBetween)
  13374. }
  13375. private handleVerifyCompleted(isSuccess: boolean) {
  13376. if (isSuccess) {
  13377. console.log('验证成功');
  13378. // 在这里处理验证成功后的逻辑
  13379. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  13380. this.currentPath = this.lockPath
  13381. this.getSortedFiles(this.currentPath)
  13382. } else {
  13383. // console.log('验证失败');
  13384. ToastUtil.showToast('验证失败')
  13385. }
  13386. }
  13387. private showVerifyDialog() {
  13388. promptAction.openCustomDialog({
  13389. transition: TransitionEffect.asymmetric(
  13390. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  13391. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  13392. ,
  13393. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  13394. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  13395. ),
  13396. builder: () => {
  13397. this.customDialogComponentMM()
  13398. },
  13399. isModal: true,
  13400. autoCancel: true,
  13401. maskColor: Color.Transparent,
  13402. alignment: DialogAlignment.Bottom,
  13403. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  13404. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  13405. console.log("dialog onWillDismiss")
  13406. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  13407. dismissDialogAction.dismiss()
  13408. }
  13409. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  13410. dismissDialogAction.dismiss()
  13411. }
  13412. }
  13413. }).then((dialogId: number) => {
  13414. this.customDialogComponentIdMM = dialogId
  13415. })
  13416. }
  13417. //左滑操作 移动文件 重命名 删除等操作
  13418. @Builder
  13419. DeleteButton(item: VideoItem, index: number, filePath: string) {
  13420. Row() {
  13421. //加入收藏
  13422. Button() {
  13423. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  13424. .fillColor(Color.White)
  13425. .width(20)
  13426. }
  13427. .width(40)
  13428. .height(40)
  13429. .type(ButtonType.Circle)
  13430. .backgroundColor(this.themeColor)
  13431. .margin(5)
  13432. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13433. .onClick(() => {
  13434. if (item) {
  13435. this.doFav(item)
  13436. }
  13437. })
  13438. //加入下一首播放
  13439. Button() {
  13440. Image($r('app.media.next_to_play'))
  13441. .fillColor(Color.White)
  13442. .width(20)
  13443. }
  13444. .width(40)
  13445. .height(40)
  13446. .type(ButtonType.Circle)
  13447. .backgroundColor(this.themeColor)
  13448. .margin(5)
  13449. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13450. .onClick(() => {
  13451. this.addToNextPlay(item);
  13452. })
  13453. //复制文件
  13454. Button() {
  13455. Image($r('app.media.copy'))
  13456. .fillColor(Color.White)
  13457. .width(20)
  13458. }
  13459. .width(40)
  13460. .height(40)
  13461. .type(ButtonType.Circle)
  13462. .backgroundColor(this.themeColor)
  13463. .margin(5)
  13464. .id(filePath + 'copy')
  13465. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13466. .onClick(() => {
  13467. this.showCopyDialog(false, item, index, filePath + 'copy');
  13468. })
  13469. //移动文件
  13470. Button() {
  13471. Image($r('app.media.cut'))
  13472. .fillColor(Color.White)
  13473. .width(20)
  13474. }
  13475. .width(40)
  13476. .height(40)
  13477. .type(ButtonType.Circle)
  13478. .backgroundColor(this.themeColor)
  13479. .margin(5)
  13480. .id(filePath)
  13481. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13482. .onClick(() => {
  13483. this.showCutDialog(false, item, index, filePath);
  13484. })
  13485. Button() {
  13486. Image($r('app.media.cut_current'))
  13487. .fillColor(Color.White)
  13488. .width(20)
  13489. }
  13490. .width(40)
  13491. .height(40)
  13492. .type(ButtonType.Circle)
  13493. .backgroundColor(this.themeColor)
  13494. .margin(5)
  13495. .id(filePath + 'current')
  13496. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  13497. (this.isHasDir ? Visibility.Visible : Visibility.None))
  13498. .onClick(() => {
  13499. this.showCutDialog(true, item, index, filePath + 'current');
  13500. })
  13501. //重命名
  13502. Button() {
  13503. Image($r('app.media.rename2'))
  13504. .fillColor(Color.White)
  13505. .width(20)
  13506. }
  13507. .width(40)
  13508. .height(40)
  13509. .type(ButtonType.Circle)
  13510. .backgroundColor(this.themeColor)
  13511. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  13512. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  13513. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  13514. .margin(5)
  13515. .onClick(() => {
  13516. this.showReNameDialog(item, index + '', filePath)
  13517. })
  13518. Button() {
  13519. Image($r('app.media.delete2'))
  13520. .fillColor(Color.White)
  13521. .width(20)
  13522. }
  13523. .width(40)
  13524. .height(40)
  13525. .type(ButtonType.Circle)
  13526. .backgroundColor(this.themeColor)
  13527. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  13528. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  13529. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  13530. .margin(5)
  13531. .onClick(() => {
  13532. this.selectedFiles.push(item)
  13533. this.showWarnIsDelete()
  13534. // this.showWarnIsDeleteFile(item, index + '', filePath)
  13535. })
  13536. Button() {
  13537. Image($r('app.media.share2'))
  13538. .fillColor(Color.White)
  13539. .width(20)
  13540. }
  13541. .width(40)
  13542. .height(40)
  13543. .type(ButtonType.Circle)
  13544. .backgroundColor(this.themeColor)
  13545. .margin(5)
  13546. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13547. .onClick(() => {
  13548. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  13549. })
  13550. }
  13551. }
  13552. /**
  13553. * 穿山甲banner广告
  13554. */
  13555. // private declare bannerAd: CSJNativeExpressAd;
  13556. // @State private status: string = "未加载"
  13557. // @State private isShowAd: boolean = false
  13558. // private declare mAdSlot: AdSlot;
  13559. // private mBiddingAdm = '' //服务端bidding才需要设置
  13560. // private expressLoadAdListener: NativeExpressAdListener = {
  13561. // /**
  13562. // * 加载失败的回调
  13563. // *
  13564. // * @param code
  13565. // * @param message
  13566. // */
  13567. // onError: (code: number, message: string) => {
  13568. // console.error("加载广告失败,code=" + code + ",message=" + message);
  13569. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  13570. // },
  13571. //
  13572. // /**
  13573. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  13574. // *
  13575. // * @param ads 返回的广告列表
  13576. // */
  13577. //
  13578. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  13579. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  13580. // if (ads && ads.length > 0) {
  13581. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  13582. // ad.setExpressInteractionListener({
  13583. // /**
  13584. // *广告的点击回调
  13585. // * @param type 广告的交互类型
  13586. // */
  13587. // onAdClicked: (type: number) => {
  13588. // console.log("BannerExpressAdPage==onAdClicked......");
  13589. // },
  13590. //
  13591. // /**
  13592. // * 广告的展示回调 每个广告仅回调一次
  13593. // * @param type 广告的交互类型
  13594. // */
  13595. // onAdShow: (type: number) => {
  13596. // console.log("BannerExpressAdPage==onAdShow......");
  13597. // },
  13598. //
  13599. // /**
  13600. // * 模板渲染失败
  13601. // */
  13602. // onRenderFail: (code: number, msg: string) => {
  13603. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  13604. // },
  13605. //
  13606. // /**
  13607. // * 模板渲染成功
  13608. // * @param width 返回view的宽 单位 vp
  13609. // * @param height 返回view的高 单位 vp
  13610. // */
  13611. // onRenderSuccess: (width: number, height: number) => {
  13612. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  13613. // this.bannerAd = ad;
  13614. // this.status = "广告加载完成待展示";
  13615. //
  13616. // this.showBannerAd()
  13617. // }
  13618. // })
  13619. // //渲染广告
  13620. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  13621. // this.setDislikeCallback(ad); //设置dislike
  13622. // ad.render(this.getUIContext())
  13623. // this.status = "广告加载中...";
  13624. // });
  13625. // }
  13626. // }
  13627. // }
  13628. //
  13629. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  13630. // ad.setDislikeCallback({
  13631. // /**
  13632. // * dislike show
  13633. // */
  13634. // onShow: () => {
  13635. // console.log("BannerExpressAdPage==dislike......show");
  13636. // },
  13637. //
  13638. // /**
  13639. // * @param position 选择的位置
  13640. // * @param value 选择的内容
  13641. // * @param enforceRemove 是否强制关闭广告
  13642. // */
  13643. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  13644. // this.isShowAd = false;
  13645. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  13646. // ",enforce=" + enforceRemove);
  13647. // },
  13648. //
  13649. // /**
  13650. // * 点击取消
  13651. // */
  13652. // onCancel: () => {
  13653. // console.log("BannerExpressAdPage==dislike......onCancel");
  13654. // }
  13655. //
  13656. // })
  13657. // }
  13658. /**
  13659. * 加载Banner广告
  13660. */
  13661. loadBannerAd(rit: string) {
  13662. // if (Utility.isNoble()) {
  13663. // return
  13664. // }
  13665. // if (!Utility.isPassInstallTime(2)) {
  13666. // return
  13667. // }
  13668. // this.isShowAd = false;
  13669. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  13670. // this.mAdSlot = new AdSlotBuilder()
  13671. // .setCodeId(rit)
  13672. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  13673. // .setAdCount(1)
  13674. // .setBidAdm(this.mBiddingAdm)
  13675. // .build()
  13676. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  13677. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  13678. // this.status = "广告加载中..."
  13679. }
  13680. /**
  13681. * 展示Banner广告
  13682. */
  13683. // showBannerAd() {
  13684. // if (!this.bannerAd) {
  13685. // return
  13686. // }
  13687. // this.isShowAd = true
  13688. // this.status = "已展示"
  13689. // }
  13690. /**
  13691. * 穿山甲广告代码结束
  13692. */
  13693. /**
  13694. * 处理歌单播放请求
  13695. */
  13696. private async handlePlaylistPlayRequest(playlistId: string, playlistName:
  13697. string, songFilePaths: string[], startIndex: number,isJump: boolean) {
  13698. try {
  13699. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 歌曲数量: ${songFilePaths.length}, 开始索引: ${startIndex}`)
  13700. // 检查是否为WebDAV播放请求
  13701. if (playlistId === 'webdav-playlist') {
  13702. Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
  13703. // 从全局内存读取videoItems数据
  13704. const videoItems = getWebdavVideoItems();
  13705. const currentPlayIndex = getWebdavCurrentPlayIndex();
  13706. Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
  13707. if (videoItems && videoItems.length > 0) {
  13708. // 验证webdav_account_id设置情况
  13709. const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
  13710. Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
  13711. if(isJump){
  13712. this.setShowPlayTrue()//显示播放页
  13713. }
  13714. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName)
  13715. return
  13716. } else {
  13717. return
  13718. }
  13719. }
  13720. if (playlistId === 'navidrome-playlist') {
  13721. Logger.info(`heanup 检测到Navidrome播放请求,从内存读取videoItems`);
  13722. const videoItems = getNavidromeVideoItems();
  13723. const currentPlayIndex = getNavidromeCurrentPlayIndex();
  13724. Logger.info(`heanup Navidrome歌曲列表长度: ${videoItems.length}`);
  13725. if (videoItems && videoItems.length > 0) {
  13726. if(isJump){
  13727. this.setShowPlayTrue()//显示播放页
  13728. }
  13729. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName);
  13730. return;
  13731. } else {
  13732. Logger.warn('heanup Navidrome播放请求缺少歌曲数据');
  13733. return;
  13734. }
  13735. }
  13736. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  13737. const songMap: Map<number, VideoItem> = new Map()
  13738. let completedQueries = 0
  13739. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  13740. // 遍历所有文件路径,使用索引记录位置
  13741. for (let i = 0; i < songFilePaths.length; i++) {
  13742. const filePath = songFilePaths[i]
  13743. const index = i
  13744. // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  13745. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  13746. const queryPromise = this.table.queryVideoByFilePath(filePath)
  13747. // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  13748. queryPromise.then((videoItem) => {
  13749. completedQueries++
  13750. // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  13751. if (videoItem) {
  13752. // 使用索引作为key保存到Map中,保持原始顺序
  13753. songMap.set(index, videoItem)
  13754. // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  13755. } else {
  13756. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  13757. }
  13758. // 检查是否所有歌曲都已加载完成
  13759. if (completedQueries === songFilePaths.length) {
  13760. // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  13761. // 按照索引顺序重建歌曲数组
  13762. const songs: VideoItem[] = []
  13763. for (let j = 0; j < songFilePaths.length; j++) {
  13764. const song = songMap.get(j)
  13765. if (song) {
  13766. songs.push(song)
  13767. // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  13768. }
  13769. }
  13770. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  13771. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  13772. }
  13773. }).catch((error: Error) => {
  13774. completedQueries++
  13775. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  13776. // 即使出错也要检查是否完成所有查询
  13777. if (completedQueries === songFilePaths.length) {
  13778. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  13779. // 按照索引顺序重建歌曲数组
  13780. const songs: VideoItem[] = []
  13781. for (let j = 0; j < songFilePaths.length; j++) {
  13782. const song = songMap.get(j)
  13783. if (song) {
  13784. songs.push(song)
  13785. }
  13786. }
  13787. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  13788. }
  13789. })
  13790. }
  13791. } catch (error) {
  13792. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  13793. ToastUtil.showToast('播放失败')
  13794. }
  13795. }
  13796. /**
  13797. * 完成歌单加载并开始播放
  13798. */
  13799. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string) {
  13800. if (songs.length === 0) {
  13801. Logger.error('heanup 没有找到任何可播放的歌曲')
  13802. ToastUtil.showToast('没有找到可播放的歌曲')
  13803. return
  13804. }
  13805. this.songList = songs
  13806. this.sonDataSource.pushArrayData(songs)
  13807. this.sonDataSource.notifyDataReload()
  13808. this.curIndex = startIndex
  13809. if (songs[startIndex]) {
  13810. // 确保当前播放的歌曲也更新到存储
  13811. AppStorage.setOrCreate('currentSong', songs[startIndex])
  13812. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  13813. this.doPlay(songs[startIndex], startIndex, true)
  13814. }
  13815. PreferencesUtil.putSync('LastMusicList', this.songList)
  13816. // ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  13817. }
  13818. }
  13819. //视频气泡窗口的布局
  13820. @Builder
  13821. function customPopupBuilder(dataBu: BubbleBean) {
  13822. List() {
  13823. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  13824. ListItem() {
  13825. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13826. Row() {
  13827. Column() {
  13828. Image(dataBu.imageRes[index])
  13829. .height(28)
  13830. .fillColor(dataBu.color)
  13831. .alignSelf(ItemAlign.Center)
  13832. }
  13833. .width(32)
  13834. Text(item)
  13835. .padding({
  13836. top: 10,
  13837. bottom: 10,
  13838. right: 10,
  13839. left: 10
  13840. })
  13841. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  13842. .textAlign(TextAlign.Start)
  13843. .width("100%")
  13844. }
  13845. }
  13846. .backgroundColor($r('app.color.settings_background_main'))
  13847. .margin({ top: 6, bottom: 6 })
  13848. }
  13849. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  13850. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  13851. TransitionEffect.scale({ x: 0, y: 0 })))
  13852. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  13853. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  13854. .onClick(() => {
  13855. dataBu.onItemClick?.(index)
  13856. })
  13857. })
  13858. }
  13859. .scrollBar(BarState.Off)
  13860. .width(120)
  13861. .divider({
  13862. strokeWidth: 1,
  13863. color: "#22FFFFFF"
  13864. })
  13865. }
  13866. // Function to calculate a hash for the file list
  13867. function simpleHash(fileList: string[]): string {
  13868. let hash = 0;
  13869. const str = fileList.join(',');
  13870. for (let i = 0; i < str.length; i++) {
  13871. const char = str.charCodeAt(i);
  13872. hash = (hash << 5) - hash + char;
  13873. hash |= 0; // Convert to 32bit integer
  13874. }
  13875. return hash.toString();
  13876. }
  13877. interface MoreItem {
  13878. id: number;
  13879. image: Resource;
  13880. title: string;
  13881. }
  13882. //视频气泡窗口的布局
  13883. @Builder
  13884. function cutPopupBuilder(dataBu: BubbleBean) {
  13885. Column() {
  13886. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  13887. .padding({
  13888. top: 10,
  13889. bottom: 10,
  13890. right: 10,
  13891. left: 10
  13892. })
  13893. .textAlign(TextAlign.Start)
  13894. .width(160)
  13895. .fontWeight(666)
  13896. .fontSize(16)
  13897. List() {
  13898. ForEach(dataBu.data, (item: string, index: number) => {
  13899. ListItem() {
  13900. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13901. Row() {
  13902. Column() {
  13903. Image($r('app.media.music_group'))
  13904. .height(28)
  13905. .fillColor(dataBu.color)
  13906. .alignSelf(ItemAlign.Center)
  13907. }
  13908. .width(32)
  13909. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  13910. .padding({
  13911. top: 10,
  13912. bottom: 10,
  13913. right: 10,
  13914. left: 10
  13915. })
  13916. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  13917. .fontSize(15)
  13918. }
  13919. }
  13920. .backgroundColor(Color.Transparent)
  13921. .margin({ top: 7, bottom: 7 })
  13922. }
  13923. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  13924. .animation({ duration: 500 }),
  13925. TransitionEffect.scale({ x: 0, y: 0 })))
  13926. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  13927. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  13928. .onClick(() => {
  13929. dataBu.onItemClick?.(index)
  13930. })
  13931. })
  13932. }
  13933. .scrollBar(BarState.Off)
  13934. .width(150)
  13935. .divider({
  13936. strokeWidth: 1,
  13937. color: "#22FFFFFF"
  13938. })
  13939. }
  13940. .height(300)
  13941. .padding({
  13942. bottom: 30
  13943. })
  13944. }
  13945. function getFileDirName(filePath: string,rootPath:string): string{
  13946. if(filePath===rootPath){
  13947. return '首页'
  13948. }
  13949. let result = FileUtil.getFileName(filePath)
  13950. if(StrUtil.isEmpty(result))
  13951. return ''
  13952. if(result.startsWith('.'))
  13953. result = result.replace(/\./g, '')
  13954. return result
  13955. }
  13956. //只扫描当前目录下文件(不扫描子文件夹)的方法
  13957. @Concurrent
  13958. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  13959. const table: MediaTable = new MediaTable(context);
  13960. try {
  13961. // 直接获取当前目录下的文件列表
  13962. const files = FileUtil.listFileSync(dirPath);
  13963. await Promise.all(files.map(async (file) => {
  13964. const fPath = `${dirPath}/${file}`;
  13965. // 跳过目录,只处理文件
  13966. if (FileUtil.isDirectory(fPath)) {
  13967. return;
  13968. }
  13969. // 跳过特定格式文件
  13970. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  13971. return;
  13972. }
  13973. // 检查是否为媒体文件
  13974. if (Utility.isMeidaByExtension(fPath)) {
  13975. let mType = CommonConstants.TYPE_LOCAL;
  13976. if (fPath.includes(lockPath)) {
  13977. mType = CommonConstants.TYPE_LOCK;
  13978. }
  13979. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  13980. context, fPath, mType, true
  13981. );
  13982. table.insert(mediaItem, (id: number) => {
  13983. // 插入回调函数
  13984. }, cover_api);
  13985. }
  13986. }));
  13987. } catch (error) {
  13988. console.error(' 扫描当前目录失败:', error);
  13989. }
  13990. }
  13991. //内嵌标签后更新库
  13992. @Concurrent
  13993. async function updateInfoDb(
  13994. context: Context,
  13995. filePath: string,
  13996. titleStr: string,
  13997. artistStr: string,
  13998. albumStr: string,
  13999. lyricConStr: string,
  14000. yearStr: string,
  14001. genreStr: string,
  14002. trackStr: string,
  14003. albumArtistStr: string,
  14004. composerStr: string,
  14005. lyricistStr: string,
  14006. commentStr: string,
  14007. discStr: string,
  14008. ): Promise<boolean> {
  14009. const table: MediaTable = new MediaTable(context);
  14010. await new Promise<void>((resolve, reject) => {
  14011. table.getRdbStore(context, (err:Error) => {
  14012. err ? reject(err) : resolve();
  14013. });
  14014. });
  14015. return await new Promise<boolean>((resolve) => {
  14016. table.updateMediaInfo(filePath, titleStr, artistStr, albumStr, lyricConStr,
  14017. yearStr, genreStr, trackStr, albumArtistStr, composerStr, lyricistStr, commentStr, discStr,
  14018. (success: boolean, error?: string) => {
  14019. if (success) {
  14020. console.log("onecold 编辑信息成功,数据库已同步");
  14021. } else {
  14022. console.error("onecold 编辑信息数据库失败原因: " + error);
  14023. }
  14024. resolve(success);
  14025. });
  14026. });
  14027. }