LocalMusic.ets 541 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572
  1. import TitleBar from './TitleBar'
  2. import { curves, display, MenuModifier,PiPWindow, promptAction, router, SymbolGlyphModifier, window } from '@kit.ArkUI';
  3. import { VideoItem } from '../viewmodel/VideoItem';
  4. import { LengthMetrics, SegmentButton,SegmentButtonOptions } from '@kit.ArkUI';
  5. import { getWebdavVideoItems, getWebdavCurrentPlayIndex } from '../pages/WebDavMainPage';
  6. import { getNavidromeVideoItems, getNavidromeCurrentPlayIndex } from '../common/util/NavidromePlaylistStore';
  7. import {
  8. ButtonFancyModifier,
  9. ImageFancyModifier,
  10. ShadowModifier,
  11. SymbolGlyphFancyModifier } from '../common/util/AttributeModifierUtil'
  12. import {
  13. AppUtil,
  14. ArrayUtil,
  15. Base64Util,
  16. DateUtil,
  17. DeviceUtil,
  18. FileUtil,
  19. GlobalContext,
  20. LogUtil,
  21. MD5,
  22. PreferencesUtil,
  23. RandomUtil,
  24. StrUtil,
  25. ToastUtil
  26. } from '@pura/harmony-utils';
  27. import { imagePathToPixelMap } from '../common/util/CommUtils';
  28. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  29. import { CommonConstants } from '../common/constants/CommonConstants';
  30. import { BaiduConstants } from '../common/constants/BaiduConstants';
  31. import { EventConstants } from '../common/constants/EventConstants';
  32. import Logger from '../common/util/Logger';
  33. import { http } from '@kit.NetworkKit';
  34. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  35. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  36. import { BubbleBean } from '../viewmodel/BubbleBean';
  37. import { PopupPosition, XPopup } from '@chinalike/popup';
  38. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  39. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  40. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  41. import { MessageEvents, util, worker, ErrorEvent, JSON } from '@kit.ArkTS';
  42. import { Verify } from './Verify';
  43. import { taskpool } from '@kit.ArkTS';
  44. import { RotatingCover } from './RotatingCover';
  45. import { PlayConstants } from '../common/constants/PlayConstants';
  46. import { effectKit } from '@kit.ArkGraphics2D';
  47. import { ColorConversion } from '../common/util/ColorConversion';
  48. import { LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  49. import { AvSessionController } from '../controller/AvSessionController';
  50. import { repairAudioMetadata, convertDsfToWav, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  51. import { extractHwMediaMetadata, FFMpegTags,Utility } from '../common/util/Utility';
  52. import { TagsContentCover } from '../view/TagsContentCover';
  53. import {
  54. DeviceChangeReason,
  55. IjkMediaPlayer,
  56. InterruptEvent,
  57. InterruptHintType,
  58. LogUtils,
  59. OnBufferingUpdateListener,
  60. OnCompletionListener,
  61. OnErrorListener,
  62. OnInfoListener,
  63. OnPreparedListener,
  64. OnSeekCompleteListener,
  65. OnTimedTextListener,
  66. OnVideoSizeChangedListener
  67. } from '@ohos/ijkplayer';
  68. import { PlayStatus } from '../common/PlayStatus';
  69. import fs from '@ohos.file.fs';
  70. import { image } from '@kit.ImageKit';
  71. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  72. import { UniversalDetector } from '@ohos/juniversalchardet';
  73. import { SettingPage } from '../pages/SettingPage';
  74. import { secondToTime,getTransverterText } from '../common/util/CommUtils';
  75. import { CommonConstants2 } from '../common/util/CommonConstants2';
  76. import { hilog } from '@kit.PerformanceAnalysisKit';
  77. import { LazyDataSource } from '../common/util/LazyDataSource';
  78. import MediaTable from '../common/util/MediaTable';
  79. import FileDeletionWatcher from '../common/util/FileDeletionWatcher';
  80. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  81. import ImageUtils from '../common/util/ImageUtils';
  82. import { ringtone } from '@kit.RingtoneKit';
  83. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  84. import { resourceManager } from '@kit.LocalizationKit';
  85. import { deviceInfo } from '@kit.BasicServicesKit';
  86. import { RemoteCacheManager } from '../common/network/RemoteCacheManager';
  87. import '../common/network/RemoteCacheRegistry';
  88. import { RemoteCacheType, resolveCacheFilePath } from '../common/network/RemoteSongCache';
  89. import { findWebDavCacheIfExists, triggerWebDavCacheDownload } from '../common/network/WebDavFileCache';
  90. import { navidromeApi } from '../common/network/NavidromeApi';
  91. import { ServerLogUtil } from '../common/util/ServerLogUtil';
  92. import { ensureSmbFileStreaming, SmbStreamingMeta } from '../common/network/SmbFileCache';
  93. import { ensureBaiduFileCached } from '../common/network/BaiduFileCache';
  94. import FileManager from '../common/util/FileManager';
  95. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  96. import app from '@system.app';
  97. import { TextNodeController } from './PipLyricTextBuilder';
  98. import { IndexerView } from './IndexerView';
  99. import { KeyCode } from '@kit.InputKit';
  100. import { KnockController } from '../controller/KnockController';
  101. import { DeleteComptent } from '../view/DeleteComptent';
  102. import { ABLoopComptent } from '../view/ABLoopComptent';
  103. import { FixMessyView } from '../view/FixMessyView';
  104. import { parseCueFile,CueTrack,CueInfo } from '../common/util/CueUtils';
  105. import { CueComptent } from '../view/CueComptent';
  106. import PlaylistTable from '../common/util/PlaylistTable';
  107. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  108. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  109. import { convertPlaylistSongsToVideoItems, emptyView,updateAllSongsSortOrder } from '../pages/PlaylistDetailPage';
  110. import { Playlist, PlaylistSong } from '../viewmodel/Playlist';
  111. import { Song } from '../viewmodel/Song';
  112. import { SongType } from '../common/enums/SongType';
  113. import { RemoteDriveManager, WebDavAuthInfo as WebDavManagerAuthInfo,
  114. buildHttpHeadersWithWebDav,
  115. WebDavAuthItem} from '../common/util/RemoteDriveManager';
  116. import PermissionUtil from '../common/util/PermissionUtil'
  117. import { EditAudio, setRingTone } from './EditAudio';
  118. import { ExtractAccompaniment } from './ExtractAccompaniment';
  119. import { ExtractAudioFromVideo } from './ExtractAudioFromVideo';
  120. import { AudioFormatConverter } from './AudioFormatConverter';
  121. import { MergeAudio } from './MergeAudio';
  122. import { AIVoiceSeparation } from './AIVoiceSeparation';
  123. import { WebDavUrlUtil } from '../common/util/WebDavUrlUtil';
  124. import { ChangeTone } from './ChangeTone';
  125. import {
  126. hdsEffect,
  127. HdsVisualComponent,
  128. HdsSceneController,
  129. HdsSceneType,
  130. HdsVisualComponentAttribute,
  131. } from '@kit.UIDesignKit';
  132. import { GlobalAlphabetIndexerModifier } from '../Styels/GlobalStyles'
  133. import { getFirstLetter } from '../Constants';
  134. import { audio } from '@kit.AudioKit';
  135. const TAG = 'LocalMusic';
  136. const HICAR_LOG_TAG = 'HiCarWindow';
  137. function logHiCarWindow(message: string): void {
  138. void ServerLogUtil.info(HICAR_LOG_TAG, message);
  139. }
  140. /**
  141. * 歌单播放事件数据
  142. */
  143. interface PlaylistEventData {
  144. playlistId: string;
  145. playlistName: string;
  146. songCount: number;
  147. startIndex: number;
  148. songFilePaths: string[];
  149. isJump: boolean;
  150. webDavAuthInfo?: WebDavAuthItem; // 新增WebDAV认证信息
  151. }
  152. const DEFAULT_INDEX =
  153. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  154. 'X', 'Y', 'Z']
  155. //排序类型
  156. function getTypeOrder(type: number) {
  157. switch (type) {
  158. case CommonConstants.TYPE_IS_DIR:
  159. return 1; // First
  160. case CommonConstants.TYPE_IS_CSJAD:
  161. return 2; // Middle
  162. case CommonConstants.TYPE_LOCAL:
  163. return 3; // Last
  164. case CommonConstants.TYPE_WEBDAV:
  165. case CommonConstants.TYPE_SMB:
  166. case CommonConstants.TYPE_NAVIDROME:
  167. case CommonConstants.TYPE_FTP:
  168. case CommonConstants.TYPE_BAIDU:
  169. return 3;
  170. default:
  171. return 4; // Unknown types, if any, go last
  172. }
  173. }
  174. function isWebDavType(type: number): boolean {
  175. return type === CommonConstants.TYPE_WEBDAV;
  176. }
  177. function isSmbType(type: number): boolean {
  178. return type === CommonConstants.TYPE_SMB;
  179. }
  180. function isNavidromeType(type: number): boolean {
  181. return type === CommonConstants.TYPE_NAVIDROME;
  182. }
  183. function isFtpType(type: number): boolean {
  184. return type === CommonConstants.TYPE_FTP;
  185. }
  186. function isBaiduType(type: number): boolean {
  187. return type === CommonConstants.TYPE_BAIDU;
  188. }
  189. function isRemoteCloudType(type: number): boolean {
  190. return isWebDavType(type) || isSmbType(type) || isNavidromeType(type) || isFtpType(type) || isBaiduType(type);
  191. }
  192. function getShareNameFromFilePath(filePath?: string): string | undefined {
  193. if (!filePath) {
  194. return undefined;
  195. }
  196. const match = filePath.match(/^smb:\/\/[^/]+\/([^/]+)/i);
  197. return match && match[1] ? match[1] : undefined;
  198. }
  199. function removeSharePrefixFromPath(path: string, primaryShare?: string, secondaryShare?: string): string {
  200. const uniqueShares: string[] = [];
  201. [primaryShare, secondaryShare].forEach((name?: string) => {
  202. const cleaned = name ? name.replace(/^\/+|\/+$/g, '') : '';
  203. if (cleaned.length > 0 && !uniqueShares.some(item => item.toLowerCase() === cleaned.toLowerCase())) {
  204. uniqueShares.push(cleaned);
  205. }
  206. });
  207. if (uniqueShares.length === 0) {
  208. return path;
  209. }
  210. let result = path;
  211. for (let i = 0; i < uniqueShares.length; i++) {
  212. const share = uniqueShares[i];
  213. const lowerPath = result.toLowerCase();
  214. const lowerShare = share.toLowerCase();
  215. if (lowerPath === lowerShare) {
  216. result = '';
  217. break;
  218. }
  219. const prefix = `${lowerShare}/`;
  220. if (lowerPath.startsWith(prefix)) {
  221. result = result.substring(share.length + 1);
  222. break;
  223. }
  224. }
  225. return result;
  226. }
  227. function extractSmbRelativePath(song: VideoItem, shareNameOverride?: string): string {
  228. const shareFromFilePath = getShareNameFromFilePath(song.filePath);
  229. const shareName = shareNameOverride ?? shareFromFilePath;
  230. if (song.remote_rel_path && song.remote_rel_path.length > 0) {
  231. const cleaned = song.remote_rel_path.replace(/^\/+/, '');
  232. return removeSharePrefixFromPath(cleaned, shareName, shareFromFilePath);
  233. }
  234. if (!song.filePath) {
  235. return '';
  236. }
  237. const match = song.filePath.match(/^smb:\/\/[^/]+\/([^/]+)(\/.*)?$/i);
  238. if (!match) {
  239. return song.filePath.replace(/^\/+/, '');
  240. }
  241. const remainder = match[2] ? match[2].replace(/^\/+/, '') : '';
  242. if (remainder.length === 0) {
  243. return '';
  244. }
  245. return remainder;
  246. }
  247. function extractFtpRelativePath(song: VideoItem): string {
  248. if (song.remote_rel_path && song.remote_rel_path.length > 0) {
  249. return song.remote_rel_path.replace(/^\/+/, '');
  250. }
  251. if (!song.filePath) {
  252. return '';
  253. }
  254. const match = song.filePath.match(/^ftp:\/\/[^/]+(?::\d+)?(\/.*)$/i);
  255. if (match && match[1]) {
  256. return match[1].replace(/^\/+/, '');
  257. }
  258. return song.filePath.replace(/^\/+/, '');
  259. }
  260. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  261. interface MetadataExtractionOptions {
  262. context?: common.Context;
  263. autoParseMusicName?: boolean;
  264. }
  265. interface WorkerEditMusicResult {
  266. success: boolean;
  267. error?: string;
  268. coverResult?: boolean;
  269. needRefreshList?: boolean;
  270. metadataResult?: boolean;
  271. }
  272. interface LocalEditMusicPayload {
  273. context: Context;
  274. item: VideoItem;
  275. titleStr: string;
  276. artistStr: string;
  277. ablumStr: string;
  278. yearStr: string;
  279. genreStr: string;
  280. trackStr: string;
  281. albumArtistStr: string;
  282. composerStr: string;
  283. lyricistStr: string;
  284. commentStr: string;
  285. discStr: string;
  286. lyricConStr: string;
  287. imagePathStr: string;
  288. currentPath: string;
  289. packName: string;
  290. modeType: number;
  291. autoParseMusicName: boolean;
  292. }
  293. interface WorkerMetadataPayload {
  294. originFilePath: string;
  295. originId?: string;
  296. bit_rate?: string;
  297. duration?: string;
  298. sampleRate?: string;
  299. mimeType?: string;
  300. md5Str?: string;
  301. videoSize?: number;
  302. size?: string;
  303. pixelMapPath?: string;
  304. artist?: string;
  305. album?: string;
  306. name?: string;
  307. lyricContent?: string;
  308. bits_per_raw_sample?: string;
  309. channels?: string;
  310. channel_layout?: string;
  311. start_time?: string;
  312. genre?: string;
  313. year?: string;
  314. probe_score?: number;
  315. track?: string;
  316. disc?: string;
  317. ALBUMARTIST?: string;
  318. COMPOSER?: string;
  319. COMMENT?: string;
  320. LYRICIST?: string;
  321. nb_streams?: number;
  322. nb_programs?: number;
  323. error?: string;
  324. }
  325. interface WebDavMetadataUpdatePayload {
  326. filePath: string;
  327. pixelMapPath?: string;
  328. name?: string;
  329. artist?: string;
  330. }
  331. const metadataExtractionInFlight: Set<string> = new Set();
  332. const METADATA_RETRY_DELAY_MS = 1500;
  333. const METADATA_MAX_RETRY = 120;
  334. async function scheduleMetadataExtractionFromCache(
  335. song: VideoItem,
  336. cachePath: string,
  337. options?: MetadataExtractionOptions,
  338. expectedSize?: number,
  339. retryCount: number = 0
  340. ): Promise<void> {
  341. if (!song || !cachePath || !song.filePath || !options || !options.context) {
  342. return;
  343. }
  344. if (!isRemoteCloudType(song.type ?? -1)) {
  345. return;
  346. }
  347. if (metadataExtractionInFlight.has(song.filePath)) {
  348. return;
  349. }
  350. if (song.bit_rate && song.sampleRate && song.duration) {
  351. return;
  352. }
  353. const requiredSize = expectedSize && expectedSize > 0 ? expectedSize : undefined;
  354. try {
  355. const stat = await fileIo.stat(cachePath);
  356. const ready = requiredSize !== undefined ? stat.size >= requiredSize : stat.size > 0;
  357. if (!ready) {
  358. if (retryCount >= METADATA_MAX_RETRY) {
  359. Logger.warn(TAG, `缓存尚未完成,放弃解析: ${cachePath}`);
  360. return;
  361. }
  362. setTimeout(() => {
  363. void scheduleMetadataExtractionFromCache(song, cachePath, options, expectedSize, retryCount + 1);
  364. }, METADATA_RETRY_DELAY_MS);
  365. return;
  366. }
  367. } catch (error) {
  368. if (retryCount >= METADATA_MAX_RETRY) {
  369. Logger.warn(TAG, `无法读取缓存文件,放弃解析: ${(error as Error).message}`);
  370. return;
  371. }
  372. setTimeout(() => {
  373. void scheduleMetadataExtractionFromCache(song, cachePath, options, expectedSize, retryCount + 1);
  374. }, METADATA_RETRY_DELAY_MS);
  375. return;
  376. }
  377. metadataExtractionInFlight.add(song.filePath);
  378. workerInstance.postMessage({
  379. code: 5,
  380. data: options.context,
  381. data2: cachePath,
  382. data3: song.type,
  383. data4: {
  384. name: song.name,
  385. originFilePath: song.filePath,
  386. originId: song.id,
  387. autoParseMusicName: options.autoParseMusicName ?? false
  388. }
  389. });
  390. }
  391. function sanitizePlaybackUrl(rawUrl: string | null | undefined): string {
  392. if (!rawUrl) {
  393. return '';
  394. }
  395. try {
  396. const decoded = decodeURI(rawUrl);
  397. const encoded = encodeURI(decoded);
  398. // encodeURI 不会处理 #,手动转义避免播放器把剩余内容当作片段
  399. return encoded.replace(/#/g, '%23');
  400. } catch (error) {
  401. const err = error as Error;
  402. Logger.warn(TAG, `URL 编码失败,使用降级方案: ${err?.message}`);
  403. return rawUrl.replace(/ /g, '%20').replace(/#/g, '%23');
  404. }
  405. }
  406. function cloneVideoItem(item: VideoItem): VideoItem {
  407. const copy = new VideoItem(
  408. item.name,
  409. item.id,
  410. item.filePath,
  411. item.type,
  412. item.videoSize,
  413. item.cTime,
  414. item.size,
  415. item.pixelMapPath,
  416. item.artist,
  417. item.album,
  418. item.fileName,
  419. item.lastPlayed
  420. );
  421. copy.parentPath = item.parentPath;
  422. copy.isFav = item.isFav;
  423. copy.size = item.size;
  424. copy.pixelMapPath = item.pixelMapPath;
  425. copy.artist = item.artist;
  426. copy.album = item.album;
  427. copy.duration = item.duration;
  428. copy.mimeType = item.mimeType;
  429. copy.sampleRate = item.sampleRate;
  430. copy.trackCount = item.trackCount;
  431. copy.lastPlayedStr = item.lastPlayedStr;
  432. copy.playCount = item.playCount;
  433. copy.lyricContent = item.lyricContent;
  434. copy.md5Str = item.md5Str;
  435. copy.extra_json = item.extra_json;
  436. copy.pyStr = item.pyStr;
  437. copy.bit_rate = item.bit_rate;
  438. copy.probe_score = item.probe_score;
  439. copy.year = item.year;
  440. copy.nb_streams = item.nb_streams;
  441. copy.nb_programs = item.nb_programs;
  442. copy.genre = item.genre;
  443. copy.track = item.track;
  444. copy.bits_per_raw_sample = item.bits_per_raw_sample;
  445. copy.channels = item.channels;
  446. copy.channel_layout = item.channel_layout;
  447. copy.start_time = item.start_time;
  448. copy.ALBUMARTIST = item.ALBUMARTIST;
  449. copy.COMPOSER = item.COMPOSER;
  450. copy.LYRICIST = item.LYRICIST;
  451. copy.COMMENT = item.COMMENT;
  452. copy.disc = item.disc;
  453. copy.webdav_account_id = item.webdav_account_id;
  454. copy.remote_rel_path = item.remote_rel_path;
  455. return copy;
  456. }
  457. /**
  458. * 异步设置videoUrl的辅助方法,处理WebDAV URL的构建
  459. * @param song 歌曲对象
  460. * @returns Promise<string> 完整的URL
  461. */
  462. /**
  463. * 设置videoUrl,通过webdav_account_id设置完整的 URL
  464. * @param song 歌曲对象
  465. * @returns Promise<string> 完整的URL
  466. */
  467. async function setVideoUrlForSong(song: VideoItem, options?: MetadataExtractionOptions): Promise<string> {
  468. const metadataOptions = options ?? {};
  469. Logger.info(TAG, `setVideoUrlForSong start -> name=${song.name}, type=${song.type}, path=${song.filePath}, fsId=${song.baiduFsId || song.id}`);
  470. if (isWebDavType(song.type) && song.webdav_account_id) {
  471. try {
  472. Logger.info(TAG, `WebDAV 路径信息 remote_rel_path: ${song.remote_rel_path}`);
  473. Logger.info(TAG, `WebDAV 路径信息 filePath: ${song.filePath}`);
  474. const relativePath = song.remote_rel_path || song.filePath;
  475. const manager = RemoteDriveManager.getInstance();
  476. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  477. if (account) {
  478. const cachePath = await findWebDavCacheIfExists(account, relativePath);
  479. if (cachePath) {
  480. Logger.info(TAG, `WebDAV 缓存命中,直接播放: ${cachePath}`);
  481. void scheduleMetadataExtractionFromCache(song, cachePath, metadataOptions, song.videoSize);
  482. return cachePath;
  483. }
  484. const fullUrlFromAccount = WebDavUrlUtil.buildFullUrl(account, relativePath);
  485. if (fullUrlFromAccount) {
  486. const sanitizedUrl = sanitizePlaybackUrl(fullUrlFromAccount);
  487. const downloadPromise = triggerWebDavCacheDownload(account, relativePath, sanitizedUrl);
  488. if (downloadPromise) {
  489. downloadPromise.then((completedPath?: string | null) => {
  490. if (completedPath) {
  491. void scheduleMetadataExtractionFromCache(song, completedPath, metadataOptions, song.videoSize);
  492. }
  493. }).catch((error: Error) => {
  494. Logger.error(TAG, `WebDAV 缓存后台下载失败: ${error.message}`);
  495. });
  496. }
  497. Logger.info(TAG, `WebDAV 启动异步缓存: ${relativePath}`);
  498. return sanitizedUrl;
  499. }
  500. }
  501. const fallbackUrl = await WebDavUrlUtil.buildFullUrlByAccountId(song.webdav_account_id, relativePath);
  502. if (fallbackUrl) {
  503. Logger.warn(TAG, `WebDAV 使用全局查询到的URL: ${fallbackUrl}`);
  504. return sanitizePlaybackUrl(fallbackUrl);
  505. }
  506. Logger.error(TAG, `WebDAV URL构建失败,使用原始路径: ${relativePath}`);
  507. return sanitizePlaybackUrl(relativePath);
  508. } catch (error) {
  509. Logger.error(TAG, `WebDAV URL构建出错: ${(error as Error).message}`);
  510. const fallbackPath = song.remote_rel_path || song.filePath;
  511. return sanitizePlaybackUrl(fallbackPath);
  512. }
  513. }
  514. if (isNavidromeType(song.type) && song.webdav_account_id) {
  515. try {
  516. const manager = RemoteDriveManager.getInstance();
  517. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  518. if (!account) {
  519. throw new Error('Navidrome账号不可用');
  520. }
  521. const navSongId = song.remote_rel_path || song.id || song.filePath;
  522. const streamUrl = await navidromeApi.buildStreamUrl(account, navSongId);
  523. void ServerLogUtil.info(TAG, `流地址构建成功: ${streamUrl}`);
  524. void ServerLogUtil.debug(TAG, `播放songId=${navSongId}, account=${ServerLogUtil.sanitizeAccount(account)}`);
  525. return sanitizePlaybackUrl(streamUrl);
  526. } catch (error) {
  527. const err = error as Error;
  528. void ServerLogUtil.error(TAG, `URL构建失败: ${err.message}`);
  529. throw new Error(err.message);
  530. }
  531. }
  532. if (isSmbType(song.type) && song.webdav_account_id) {
  533. try {
  534. const manager = RemoteDriveManager.getInstance();
  535. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  536. if (!account) {
  537. throw new Error('SMB账号不可用');
  538. }
  539. const relativePath = extractSmbRelativePath(song, account.smbShare);
  540. const pathInfo = await resolveCacheFilePath(
  541. RemoteCacheType.SMB,
  542. account.id?.toString(),
  543. relativePath
  544. );
  545. const streamMeta: SmbStreamingMeta = {
  546. fileSize: song.videoSize,
  547. mimeType: song.mimeType,
  548. fileName: song.fileName || song.name
  549. };
  550. const streamingUrl = await ensureSmbFileStreaming(account, pathInfo.normalizedRelative, streamMeta);
  551. Logger.info(TAG, `SMB 流地址: ${streamingUrl}`);
  552. void scheduleMetadataExtractionFromCache(song, pathInfo.cachePath, metadataOptions, song.videoSize);
  553. const shouldBypassSanitize = streamingUrl.startsWith('http://127.0.0.1:');
  554. return shouldBypassSanitize ? streamingUrl : sanitizePlaybackUrl(streamingUrl);
  555. } catch (error) {
  556. const err = error as Error;
  557. Logger.error(TAG, `SMB 流式播放失败: ${err.message}`);
  558. throw new Error(err.message);
  559. }
  560. }
  561. if (isFtpType(song.type) && song.webdav_account_id) {
  562. try {
  563. const manager = RemoteDriveManager.getInstance();
  564. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  565. if (!account) {
  566. throw new Error('FTP账号不可用');
  567. }
  568. const relativePath = extractFtpRelativePath(song);
  569. const cachedPath = await RemoteCacheManager.ensureCached(RemoteCacheType.FTP, {
  570. account,
  571. remotePath: relativePath
  572. });
  573. Logger.info(TAG, `FTP 缓存路径: ${cachedPath}`);
  574. void scheduleMetadataExtractionFromCache(song, cachedPath, metadataOptions, song.videoSize);
  575. return cachedPath;
  576. } catch (error) {
  577. const err = error as Error;
  578. Logger.error(TAG, `FTP 缓存失败: ${err.message}`);
  579. throw new Error(err.message);
  580. }
  581. }
  582. if (isBaiduType(song.type) && song.webdav_account_id) {
  583. try {
  584. const manager = RemoteDriveManager.getInstance();
  585. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  586. if (!account) {
  587. throw new Error('百度网盘账户不可用');
  588. }
  589. Logger.info(TAG, `百度网盘播放准备 - accountId: ${account.id}, fsId: ${song.baiduFsId || song.id}`);
  590. const sanitizedAccount = ServerLogUtil.sanitizeAccount(account);
  591. void ServerLogUtil.info('BaiduStream', `准备播放百度歌曲: account=${sanitizedAccount}, fsId=${song.baiduFsId || song.id}`);
  592. const fsId = song.baiduFsId || song.id;
  593. if (!fsId) {
  594. throw new Error('缺少百度网盘文件fs_id');
  595. }
  596. // 优先使用remote_rel_path,回退到文件名
  597. const relativePath = song.remote_rel_path || song.name || song.fileName || song.filePath;
  598. const streamPath = song.remote_rel_path;
  599. const cachedPath = await resolveCacheFilePath(
  600. RemoteCacheType.BAIDU,
  601. account.id?.toString(),
  602. relativePath
  603. );
  604. const fileExists = await FileManager.isExist(cachedPath.cachePath);
  605. if (fileExists) {
  606. const fileSize = await FileManager.getFileSize(cachedPath.cachePath);
  607. if (fileSize > 0) {
  608. Logger.info(TAG, `百度网盘文件已缓存: ${cachedPath.cachePath}`);
  609. void scheduleMetadataExtractionFromCache(song, cachedPath.cachePath, metadataOptions, song.videoSize);
  610. return cachedPath.cachePath;
  611. }
  612. }
  613. // 缓存不存在或无效,获取文件信息(包含大小和下载链接)
  614. Logger.info(TAG, `百度网盘文件未缓存,准备获取文件信息: ${relativePath}`);
  615. const fileInfo = await manager.getBaiduFileInfo(account, fsId, streamPath);
  616. Logger.info(TAG, `百度网盘文件信息获取成功: 大小=${fileInfo.size}字节,流地址已获取`);
  617. void ServerLogUtil.info('BaiduStream', `音频流URL获取成功: ${fileInfo.streamUrl}`);
  618. // 立即返回媒体流地址,开始播放
  619. Logger.info(TAG, `返回音频流链接进行播放,同时后台缓存: ${fileInfo.streamUrl}`);
  620. // 异步进行缓存,不阻塞播放
  621. void (async () => {
  622. try {
  623. Logger.info(TAG, `后台开始缓存百度网盘文件: ${relativePath},大小: ${fileInfo.size}字节`);
  624. void ServerLogUtil.info('BaiduStream', `开始缓存百度文件: account=${sanitizedAccount}, path=${relativePath}`);
  625. const cachedFilePath = await ensureBaiduFileCached(
  626. account,
  627. fsId,
  628. relativePath,
  629. fileInfo.dlink,
  630. fileInfo.size
  631. );
  632. Logger.info(TAG, `后台缓存完成: ${cachedFilePath}`);
  633. void ServerLogUtil.info('BaiduStream', `缓存完成: ${cachedFilePath}`);
  634. void scheduleMetadataExtractionFromCache(song, cachedFilePath, metadataOptions, song.videoSize);
  635. } catch (cacheError) {
  636. const cacheErr = cacheError as Error;
  637. Logger.warn(TAG, `后台缓存失败: ${cacheErr.message}`);
  638. void ServerLogUtil.error('BaiduStream', `缓存失败: ${cacheErr.message}`);
  639. }
  640. })();
  641. return fileInfo.streamUrl;
  642. } catch (error) {
  643. const err = error as Error;
  644. Logger.error(TAG, `百度网盘播放链接获取失败: ${err.message}`);
  645. throw err;
  646. }
  647. }
  648. if (isWebDavType(song.type)) {
  649. Logger.warn(TAG, `WebDAV歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
  650. return sanitizePlaybackUrl(song.filePath);
  651. }
  652. if (isSmbType(song.type)) {
  653. Logger.warn(TAG, `SMB歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
  654. return song.filePath;
  655. }
  656. if (isFtpType(song.type)) {
  657. Logger.warn(TAG, `FTP歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
  658. return song.filePath;
  659. }
  660. if (isBaiduType(song.type)) {
  661. throw new Error('百度网盘歌曲缺少webdav_account_id,无法构建播放链接');
  662. }
  663. if (isNavidromeType(song.type)) {
  664. throw new Error('Navidrome歌曲缺少webdav_account_id,无法构建播放链接');
  665. }
  666. Logger.info(TAG, `setVideoUrlForSong fallback直接返回原始路径: ${song.filePath}`);
  667. return song.filePath;
  668. }
  669. // 定义接口
  670. interface HiCarAspectRatio {
  671. ratio: number;
  672. name: string;
  673. }
  674. interface GeneratedObjectLiteralInterface_1 {
  675. assetId: string;
  676. title: string;
  677. artist: string;
  678. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  679. mediaUri: string;
  680. // 该字段大写,音频'AUDIO',视频'VIDEO'
  681. mediaType: string;
  682. mediaSize: number;
  683. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  684. startPosition: number;
  685. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  686. duration: number;
  687. albumCoverUri: string;
  688. albumTitle: string;
  689. appName: string;
  690. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  691. drmScheme: string;
  692. }
  693. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  694. const ITEM_HEIGHT: number = 65; // 列表项中高度
  695. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  696. //功能强大的音乐播放器
  697. @Preview
  698. @Component
  699. export struct LocalMusic {
  700. @State showZMIndex: boolean = false //是否右侧显示字母索引
  701. private prevOffsetY: number = 0; // 记录上一次的Y轴偏移量
  702. @State autoHideTitle: boolean = true //滚动自动隐藏标题栏
  703. // 字母表
  704. @State alphaBet: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
  705. 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  706. @State alphaBetStyle: GlobalAlphabetIndexerModifier = new GlobalAlphabetIndexerModifier()
  707. @State selectAlphaBetIndex: number = 0
  708. @State isShowAlphaBet: boolean = false
  709. @State isScrolling: boolean = false
  710. @State isTouchingAlphaBet: boolean = false
  711. @State alphabetHeight: number = 0
  712. public enableShowAlphabet: boolean = true // 是否显示字母表
  713. @State isShowPrecious: boolean = false //播控条显示上一首按钮
  714. //背景两侧流光控制器
  715. @State sceneBgController: HdsSceneController|undefined = deviceInfo.sdkApiVersion>=20
  716. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  717. new HdsSceneController()
  718. .setSceneParams({
  719. backgroundMaskColors: [Color.Green, Color.Red],
  720. firstEdgeFlowLight: {
  721. startPos: 0,
  722. endPos: 0.5,
  723. color: Color.Red
  724. },
  725. secondEdgeFlowLight: {
  726. startPos: 0,
  727. endPos: -0.5,
  728. color: Color.Green
  729. }
  730. }) : undefined;
  731. //背景流光控制器
  732. @State bgController: hdsEffect.ShaderEffectController|undefined = deviceInfo.sdkApiVersion>=20
  733. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  734. new hdsEffect.ShaderEffectController():undefined;
  735. @State showAddSheet:boolean = false
  736. searchController: SearchController = new SearchController()
  737. @State rightTopImage:Resource = $r('sys.symbol.sort')
  738. @State isEditAudio:boolean = false
  739. @State isExtractAcc:boolean = false
  740. @State isConverter:boolean = false
  741. @State isAIVoiceSeparation:boolean = false
  742. @State isExtractAudio:boolean = false
  743. @State isMergeAudio:boolean = false
  744. @State isCopyFileToDownLoad: boolean = false
  745. @State isChangeTone:boolean = false
  746. @State offHeight: number = 75
  747. @State currentSongList: Array<VideoItem> = []//当前歌单
  748. @Consume currentSongListName:string //当前歌单名称
  749. @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
  750. @State isRefreshing: boolean = false;
  751. @State maxRefreshingHeight: number = 100.0;
  752. private contentNode?: ComponentContent<Object> = undefined;
  753. // WebDAV相关实例变量(现在改为从内存读取,不再需要存储)
  754. @State ratioL: number = 1;
  755. @State mediaKuCount: number = 0;
  756. @State albumCount: number = 0;
  757. @State artistCount: number = 0;
  758. @State fastForwardSeconds: string = '10'
  759. @State isShowBackFast: boolean = true//快进快退按钮
  760. @State isCanAuto:boolean = true
  761. @State opacityValueImage: number = 1;
  762. @State tipPopup:boolean = false
  763. @Consume mType: number;
  764. @StorageProp('themeColor') themeColor: string =
  765. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  766. themeMode: number = 0;
  767. @State titleName: string = '首页'
  768. @State textStr: string = ''
  769. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  770. // private download_path: string = '';
  771. @Consume rootPath: string //音频根目录
  772. @Consume currentPath: string
  773. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  774. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  775. @State lockPath: string = ''
  776. @State favPath: string = ''
  777. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  778. @State historyPath: string = ''
  779. @State historyList: Array<VideoItem> = []
  780. @Consume isHistory: boolean
  781. static readonly HISTORY_MUSIC: string = 'music_historyList';
  782. private table: MediaTable = new MediaTable(getContext(this))
  783. private playlistTable: PlaylistTable | null = null
  784. private deletionWatcher: FileDeletionWatcher | null = null
  785. @State allPlaylists: Playlist[] = []
  786. @State isZero: boolean = false
  787. @State fileList: Array<string> = []
  788. @State dirList: Array<VideoItem> = []
  789. @Consume videoLocalList:VideoItem[]
  790. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  791. @State listRefreshKey: number = 0
  792. // @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  793. @StorageProp('mediaKuList') mediaKuList: Array<VideoItem> = []; //媒体库文件
  794. @State artistList: Array<VideoItem> = []; //艺术家文件
  795. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  796. @State albumList: Array<VideoItem> = []; //专辑文件
  797. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  798. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  799. @State imageOpacities: number[] = [];
  800. @Consume isCanBack: boolean
  801. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  802. @State showSingleLyric: boolean = false
  803. @State sortType: number = 4 //默认排序方式
  804. @State isShowSimi: boolean = false //是否显示私密音频
  805. @State isShowFAV: boolean = true //是否显示我的收藏
  806. @State isShowTitleBar: boolean = true //是否显示分类导航条
  807. @State isShowAllBar: boolean = true //是否显示播放全部条
  808. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  809. @State isShowHistory: boolean = true //是否显示最近播放
  810. @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
  811. @State isGridMusic: boolean = false //是否网格布局
  812. @State isCircleBtn: boolean = false //是否圆形播放按钮
  813. @State twoFingerType: number = 3 //双支放大缩小的类型
  814. @State isScrollHide: boolean = false //是否滚动隐藏
  815. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  816. @State isStartAutoPlay: boolean = false //启动后自动播放
  817. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  818. @State isShowHeader: boolean = true
  819. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  820. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  821. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  822. @State isSwipe: boolean = false //listItem的左滑开关
  823. @State openSkipSongAnimate: boolean = true//切歌动画效果
  824. @State customizeBgPath: string | undefined = '';
  825. @State isDarkMode: boolean = false
  826. @State lyricTextWeight: number = 400
  827. @State lyricTextWeightPip: number = 400
  828. @State currentSwiperIndex: number = 0
  829. @State blurValue: number = 0 //背景模糊
  830. @State bgBrightness: number = 0 //背景亮度
  831. private listScroller: ListScroller = new ListScroller()
  832. private playListScroller: Scroller = new Scroller()
  833. @State isOneKeyTags:boolean = false
  834. @State isFixMessy:boolean = false
  835. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  836. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  837. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  838. @StorageProp('windowWidth') windowWidth: number = 0;
  839. @StorageProp('windowHeight') windowHeight: number = 0;
  840. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  841. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  842. private UNKONWN:string = '';
  843. private listArea: Area = {
  844. width: 0,
  845. height: 0,
  846. position: {},
  847. globalPosition: {}
  848. }
  849. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  850. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  851. // WebDAV认证信息缓存(作为实例变量,比全局上下文更可靠)
  852. private currentWebDavAuthInfo: WebDavAuthItem | null = null;
  853. //瀑布流的列数横竖屏动态切换
  854. onIsLandscapeChange() {
  855. if(this.isLandscape){
  856. this.columns = 4
  857. }else{
  858. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  859. }
  860. }
  861. onColorModeChange() {
  862. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  863. }
  864. //点击某个歌单id发生变化的时候回调
  865. onIDChange(){
  866. console.log('onecold 歌单id发生变化this.currentSongListID='+this.currentSongListID)
  867. console.log('onecold 歌单id发生变化this.currentSongListName='+this.currentSongListName)
  868. if(this.modeType==4){
  869. this.titleName = this.currentSongListName
  870. this.rightTopImage = $r('sys.symbol.sort')
  871. //获取缓存
  872. const cacheSongs:string =PreferencesUtil.getStringSync(this.currentSongListID+'currentSongList', '')
  873. console.log('onecold 歌单id发生变化获取缓存2 cacheSongs = '+cacheSongs)
  874. if(StrUtil.isNotEmpty(cacheSongs)){
  875. this.currentSongList = JSON.parse(cacheSongs) as VideoItem[]
  876. this.updateListData(this.currentSongList, true)
  877. }
  878. this.doSongListTask()//获取歌单信息
  879. }
  880. }
  881. async doSongListTask() {
  882. // 初始化歌单数据库
  883. const playlistTable = new PlaylistTable(this.context);
  884. // 查询歌单中的所有歌曲
  885. const playlistSongs: PlaylistSong[] = await playlistTable.queryPlaylistSongs(this.currentSongListID);
  886. console.log('onecold 歌单id发生变化获取缓存7 playlistSongs='+playlistSongs.length)
  887. if (ArrayUtil.isEmpty(playlistSongs)) {
  888. this.updateListData([], true)
  889. } else {
  890. this.currentSongList = await convertPlaylistSongsToVideoItems(this.context, playlistSongs);
  891. console.log('onecold 从数据库读取的歌曲为 playlistSongs='+this.currentSongList.length)
  892. this.updateListData(this.currentSongList, true)
  893. if (ArrayUtil.isNotEmpty(this.currentSongList)&&this.currentSongList.length > 100) {
  894. // 只保存前100条记录到缓存中
  895. let canceList = this.currentSongList.slice(0, 100);
  896. PreferencesUtil.putSync(this.currentSongListID+'currentSongList',
  897. JSON.stringify(canceList))
  898. } else {
  899. PreferencesUtil.putSync(this.currentSongListID+'currentSongList', JSON.stringify(this.currentSongList));
  900. }
  901. }
  902. this.isRefreshing = false
  903. }
  904. onModeChange() {
  905. this.isFavMusic = false
  906. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  907. switch (this.modeType) {
  908. case 0:
  909. this.getSortedFiles(this.currentPath)
  910. break
  911. case 1:
  912. this.rightTopImage = $r('sys.symbol.sort')
  913. this.updateListData(this.mediaKuList)
  914. this.titleName = Utility.resourceToString(this.context,$r('app.string.media_ku'))
  915. break
  916. case 2:
  917. this.rightTopImage = $r('sys.symbol.sort')
  918. this.updateListData(this.artistList)
  919. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  920. break
  921. case 3:
  922. this.rightTopImage = $r('sys.symbol.sort')
  923. this.updateListData(this.albumList)
  924. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  925. break
  926. }
  927. }
  928. // @Consume currentSong: VideoItem | undefined;
  929. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  930. // @StorageLink('isPlay') isPlay: boolean = false;
  931. @Consume isShowPlay: boolean ;
  932. @StorageLink('songList') songList: Array<VideoItem> = [];
  933. @State translateY: number = 0;
  934. @State isShowSheet: boolean = false;
  935. @State isShowSheetView: boolean = false;
  936. @State isShowTimeCloseView: boolean = false;
  937. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  938. @StorageLink('currIndex') curIndex: number = 0;
  939. @Consume isShowDrawer: boolean;
  940. @Consume offsetX: number;
  941. @State isFac: boolean = false;
  942. @State favList: Array<VideoItem> = []
  943. @Consume isFavMusic: boolean
  944. @State isClickedPLayAll: boolean = false;
  945. private scrollerForlist: ListScroller = new ListScroller();
  946. private knockController: KnockController | undefined = undefined;
  947. // 修改为:
  948. imagesF: ImageFrameInfo[] = CommonConstants.IMAGE_FRAME_INFO;
  949. @StorageProp('animationState') animationState: AnimationStatus = AnimationStatus.Initial
  950. // 缓存机制
  951. private cache: Map<string, Array<VideoItem>> = new Map();
  952. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  953. // 持久化缓存
  954. private async saveCacheToStorage() {
  955. const cacheArray = Array.from(this.cache.entries());
  956. const stringCacheArray = Array.from(this.stringCache.entries());
  957. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  958. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  959. }
  960. // 载入缓存
  961. private async loadCacheFromStorage() {
  962. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  963. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  964. if (cacheString) {
  965. const parsedCache: Object | null = JSON.parse(cacheString);
  966. if (parsedCache && Array.isArray(parsedCache)) {
  967. const cacheArray: [string, Array<VideoItem>][] = parsedCache;
  968. this.cache = new Map(cacheArray);
  969. }
  970. }
  971. if (stringCacheString) {
  972. const parsedStringCache: Object | null = JSON.parse(stringCacheString);
  973. if (parsedStringCache && Array.isArray(parsedStringCache)) {
  974. const stringCacheArray: [string, string][] = parsedStringCache;
  975. this.stringCache = new Map(stringCacheArray);
  976. }
  977. }
  978. }
  979. // 查找缓存
  980. private findCache(key: string): Array<VideoItem> | undefined {
  981. return this.cache.get(key);
  982. }
  983. // 查找字符串缓存
  984. private findStringCache(key: string): string | undefined {
  985. return this.stringCache.get(key);
  986. }
  987. // 添加缓存
  988. private addCache(key: string, value: Array<VideoItem>) {
  989. this.cache.set(key, value);
  990. }
  991. // 添加字符串缓存
  992. private addStringCache(key: string, value: string) {
  993. this.stringCache.set(key, value);
  994. }
  995. // 删除缓存
  996. private deleteCache(key: string) {
  997. this.cache.delete(key);
  998. this.saveCacheToStorage()
  999. }
  1000. // 删除字符串缓存
  1001. private deleteStringCache(key: string) {
  1002. this.stringCache.delete(key);
  1003. }
  1004. // 多选机制
  1005. @State selectedFiles: Array<VideoItem> = [];
  1006. @Consume isMultiSelect: boolean;
  1007. @State isAllSelected: boolean = false;
  1008. @State appName: string = ''
  1009. @State isHasDir: boolean = false
  1010. @State packName: string = ''
  1011. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  1012. doSwipBack() {
  1013. if(this.isSearchMode){
  1014. console.info('onecold doSwipBack = ' +this.isSearchMode)
  1015. this.isSearchMode = false
  1016. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  1017. this.searchText = ''
  1018. this.getSortedFiles(this.currentPath)
  1019. return
  1020. }
  1021. this.onSearchInput('')
  1022. return
  1023. }
  1024. this.isZero = false
  1025. if (this.modeType !== 0 && this.isCanBack) {
  1026. this.onModeChange()
  1027. this.isCanBack = false
  1028. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  1029. setTimeout(() => {
  1030. if (this.modeType == 2) {
  1031. if (this.isGridMusic||this.twoFingerType==4) {
  1032. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  1033. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  1034. if(this.twoFingerType==4){
  1035. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  1036. }else{
  1037. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1038. }
  1039. } else {
  1040. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  1041. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1042. }
  1043. } else if (this.modeType == 3) {
  1044. if (this.isGridMusic||this.twoFingerType==4) {
  1045. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  1046. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 0
  1047. if(this.twoFingerType==4){
  1048. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  1049. }else{
  1050. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1051. }
  1052. } else {
  1053. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  1054. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1055. }
  1056. }
  1057. }, 200)
  1058. return
  1059. }
  1060. if (this.isHistory || this.isFavMusic) {
  1061. this.isHistory = false
  1062. this.getSortedFiles(this.currentPath)
  1063. return
  1064. }
  1065. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  1066. animateTo({ duration: 555 }, () => {
  1067. // 动画闭包内控制Image组件的出现和消失
  1068. this.isShowDrawer = !this.isShowDrawer
  1069. this.offsetX = 0
  1070. })
  1071. return
  1072. }
  1073. //返回上一级歌单的滚动位置
  1074. setTimeout(() => {
  1075. if (this.modeType == 0) {
  1076. if (this.isGridMusic||this.twoFingerType==4) {
  1077. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  1078. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
  1079. if(this.twoFingerType==4){
  1080. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  1081. }else{
  1082. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1083. }
  1084. } else {
  1085. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  1086. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1087. }
  1088. }
  1089. }, 300)
  1090. this.currentPath = Utility.getParentDirectory(this.currentPath)
  1091. Logger.info('this.currentPath2 = ' + this.currentPath)
  1092. this.getSortedFiles(this.currentPath)
  1093. }
  1094. // 组件生命周期
  1095. aboutToAppear() {
  1096. console.info('onecold aboutToAppear sdkApiVersion = '+deviceInfo.sdkApiVersion)
  1097. if(ArrayUtil.isNotEmpty(this.videoLocalList)&&this.modeType==0){
  1098. this.updateListData(this.videoLocalList)
  1099. }
  1100. // 初始化 PlaylistTable
  1101. this.playlistTable = new PlaylistTable(getContext(this))
  1102. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  1103. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  1104. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  1105. this.tipPopup = !this.tipPopup
  1106. PreferencesUtil.putSync('isFirstTiped',false)
  1107. }
  1108. this.initSetting()
  1109. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  1110. Utility.getAppName(getContext(this)).then((appName: string) => {
  1111. this.appName = appName
  1112. })
  1113. this.packName = AppUtil.getBundleName()
  1114. this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
  1115. this.loadCacheFromStorage(); // 加载文件夹缓存
  1116. // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
  1117. this.initLoadCache()
  1118. this.mkDownLoadDir()
  1119. let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
  1120. // 监听广播事件(打开其他应用处理)
  1121. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  1122. this.saveVideoDatas([eventData.data?.message], true)
  1123. });
  1124. //侧滑广播接收时间
  1125. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
  1126. // 监听广播事件(打开其他应用处理)
  1127. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  1128. animateTo({ duration: 555 }, () => {
  1129. this.doSwipBack()
  1130. })
  1131. });
  1132. //ScanFilePage广播接收时间
  1133. let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
  1134. // 监听ScanFilePage广播事件(更新数据库)
  1135. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  1136. this.doUpdateData()
  1137. });
  1138. // 监听歌单播放请求事件
  1139. let eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY }
  1140. emitter.on(eventPlaylistPlay, async (eventData: emitter.EventData) => {
  1141. const data = eventData.data as Record<string, Object>
  1142. if (!data) {
  1143. Logger.error('heanup eventPlaylistPlay: eventData.data is undefined or null')
  1144. return
  1145. }
  1146. // 检查歌单播放数据结构
  1147. if (data.playlistId && data.songFilePaths && data.startIndex !== undefined) {
  1148. const playlistData: PlaylistEventData = {
  1149. playlistId: data.playlistId as string,
  1150. playlistName: data.playlistName as string,
  1151. songCount: data.songCount as number,
  1152. startIndex: data.startIndex as number,
  1153. isJump: data.isJump as boolean,
  1154. songFilePaths: data.songFilePaths as string[]
  1155. }
  1156. await this.handlePlaylistPlayRequest(
  1157. playlistData.playlistId,
  1158. playlistData.playlistName,
  1159. playlistData.songFilePaths,
  1160. playlistData.startIndex,
  1161. playlistData.isJump,
  1162. )
  1163. return
  1164. }
  1165. Logger.error('heanup eventPlaylistPlay: 接收到无效的数据结构')
  1166. });
  1167. let eventRefreshSort: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_REFRESH_SORT }
  1168. // 监听广播事件(通用设置配置更新)
  1169. emitter.on(eventRefreshSort, (eventData: emitter.EventData) => {
  1170. if(this.modeType ==4){
  1171. this.doSongListTask()//获取歌单信息
  1172. }
  1173. });
  1174. let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
  1175. // 监听广播事件(通用设置配置更新)
  1176. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  1177. this.doChangeSetting()
  1178. });
  1179. let event: Callback<InterruptEvent> = (event) => {
  1180. // LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  1181. console.info(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  1182. this.savePlaybackPosition()
  1183. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  1184. this.pause();
  1185. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  1186. console.info(`onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  1187. console.info('onecold startPlayOrResumePlay 514')
  1188. this.startPlayOrResumePlay();
  1189. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  1190. console.info(`onecold 与其他应用音频冲突 被截断点 INTERRUPT_HINT_STOP`)
  1191. if(!this.isSameTimePlay){
  1192. this.stop();
  1193. }
  1194. }
  1195. }
  1196. this.mIjkMediaPlayer.on('audioInterrupt', event);
  1197. // 音频设备断连回调处理比如蓝牙耳机断开
  1198. let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  1199. LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  1200. if (event.reason === DeviceChangeReason.REASON_NEW_DEVICE_AVAILABLE) { // 音频设备连接
  1201. } else if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  1202. console.info('onecold 音频设备断开连接, 暂停播放')
  1203. this.pause();
  1204. }
  1205. }
  1206. // 订阅音频设备断开和连接事件
  1207. this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  1208. const eventPause: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_PAUSE }
  1209. // 监听广播事件(hicar断开暂停播放)
  1210. emitter.on(eventPause, (eventData: emitter.EventData) => {
  1211. this.pause();
  1212. });
  1213. // 有线耳机断开和连接的监听。监听音频设备状态变化。
  1214. let audioManager = audio.getAudioManager(); // 需要先创建AudioManager实例。
  1215. let audioRoutingManager = audioManager.getRoutingManager(); // 再调用AudioManager的方法创建AudioRoutingManager实例。
  1216. audioRoutingManager.on('deviceChange', audio.DeviceFlag.INPUT_DEVICES_FLAG, (deviceChanged: audio.DeviceChangeAction) => {
  1217. console.info('device change type : ' + deviceChanged.type); // 设备连接状态变化,0为连接,1为断开连接。
  1218. // 设备类型 22是USB耳机,带麦克风,3是有线耳机。
  1219. if(deviceChanged.type==1&&
  1220. (deviceChanged.deviceDescriptors[0].deviceType== 22||
  1221. deviceChanged.deviceDescriptors[0].deviceType==3)){
  1222. this.pause();
  1223. }
  1224. });
  1225. this.makeWorker()
  1226. //折叠屏的屏幕显示模式变化
  1227. display.on('foldDisplayModeChange', (data) => {
  1228. this.doChangeBarHeight()
  1229. });
  1230. display.on('foldStatusChange', (data) => {
  1231. Logger.info('onecold foldStatusChange ')
  1232. });
  1233. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  1234. // 读取 themeMode 并同步 currentColorMode
  1235. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  1236. this.applyThemeMode(this.themeMode)
  1237. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  1238. AppStorage.setOrCreate('themeColor', themeColor);
  1239. this.themeColor = themeColor;
  1240. this.doChangeSetting()
  1241. this.windowClass.on('windowSizeChange', (size) => {
  1242. LogUtil.info('onecold windowSizeChange')
  1243. this.doChangeBarHeight()
  1244. let viewWidth = px2vp(size.width);
  1245. let viewHeight = px2vp(size.height);
  1246. if(this.isPhoneLan()){
  1247. this.is_auto_hide_progress = false
  1248. if(this.isHiCar()){
  1249. return
  1250. }
  1251. setTimeout(() => {
  1252. this.is_auto_hide_progress = true
  1253. }, 6000)
  1254. }else{
  1255. this.startAutoHide()
  1256. }
  1257. });
  1258. this.eventHub.on('onStateChange', (fg: boolean) => {
  1259. if (fg && this.curState === 'STARTED') {
  1260. this.stopPip();
  1261. }
  1262. });
  1263. //NewIndex的博空调收到eventHub消息控制播放
  1264. this.getUIContext().getHostContext()!.eventHub.on('playOrPause', () => {
  1265. if (ArrayUtil.isNotEmpty(this.songList)) {
  1266. this.playOrPause();
  1267. } else {
  1268. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1269. }
  1270. });
  1271. this.getUIContext().getHostContext()!.eventHub.on('playPrevious', () => {
  1272. if (ArrayUtil.isNotEmpty(this.songList)) {
  1273. this.playPrevious();
  1274. } else {
  1275. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1276. }
  1277. });
  1278. this.getUIContext().getHostContext()!.eventHub.on('playNext', () => {
  1279. if (ArrayUtil.isNotEmpty(this.songList)) {
  1280. this.playNext();
  1281. } else {
  1282. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1283. }
  1284. });
  1285. this.getUIContext().getHostContext()!.eventHub.on('showPlayerView', () => {
  1286. this.showPlayerView();
  1287. });
  1288. this.getUIContext().getHostContext()!.eventHub.on('openPlayList', () => {
  1289. this.openPlayList();
  1290. });
  1291. }
  1292. //载入媒体库,艺术家,专辑等缓存
  1293. initLoadCache(){
  1294. this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
  1295. this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
  1296. this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
  1297. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  1298. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  1299. if(ArrayUtil.isNotEmpty(cachedList)){
  1300. this.mediaKuList = cachedList
  1301. if(this.modeType==1){
  1302. this.updateListData(this.mediaKuList)
  1303. }
  1304. }
  1305. let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
  1306. let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
  1307. if(ArrayUtil.isNotEmpty(artistCachedList)){
  1308. this.artistList = artistCachedList
  1309. let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
  1310. const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
  1311. this.artistMap = new Map(parsedArray);
  1312. // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
  1313. if(this.modeType==2){
  1314. this.updateListData(this.artistList)
  1315. }
  1316. }
  1317. let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
  1318. let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
  1319. if(ArrayUtil.isNotEmpty(albumCachedList)){
  1320. this.albumList = albumCachedList
  1321. let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
  1322. const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
  1323. this.albumMap = new Map(parsedArray);
  1324. if(this.modeType==3){
  1325. this.updateListData(this.albumList)
  1326. }
  1327. }
  1328. }
  1329. startAutoHide() {
  1330. if(this.isHiCar()){
  1331. return
  1332. }
  1333. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  1334. console.info('onecold startAutoHide')
  1335. this.is_auto_hide_progress = false
  1336. setTimeout(() => {
  1337. this.is_auto_hide_progress = true
  1338. }, 6000)
  1339. }
  1340. }
  1341. applyThemeMode(mode: number) {
  1342. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  1343. if (mode === 1) {
  1344. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  1345. } else if (mode === 2) {
  1346. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1347. }
  1348. AppStorage.setOrCreate('currentColorMode', colorMode)
  1349. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  1350. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  1351. AppStorage.setOrCreate('themeMode', mode)
  1352. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1353. // 只有强制浅色/深色时才主动设置
  1354. const context = getContext(this) as common.UIAbilityContext
  1355. context.getApplicationContext().setColorMode(colorMode)
  1356. }
  1357. initSetting() {
  1358. this.showZMIndex = PreferencesUtil.getBooleanSync('showZMIndex', false)
  1359. this.autoHideTitle = PreferencesUtil.getBooleanSync('autoHideTitle', true)
  1360. this.isShowPrecious = PreferencesUtil.getBooleanSync('isShowPrecious', false)
  1361. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1362. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  1363. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  1364. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, false)
  1365. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  1366. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  1367. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  1368. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  1369. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  1370. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  1371. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  1372. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  1373. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  1374. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 2)
  1375. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  1376. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  1377. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  1378. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  1379. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  1380. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  1381. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  1382. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  1383. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  1384. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  1385. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  1386. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  1387. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  1388. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  1389. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  1390. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  1391. this.isCopyFileToDownLoad = PreferencesUtil.getBooleanSync(SettingPage.IS_COPYFILE_TO_DOWNLOAD, false)
  1392. let audioManager = audio.getAudioManager();
  1393. let audioSessionManager: audio.AudioSessionManager = audioManager.getSessionManager();
  1394. if(this.isSameTimePlay){
  1395. //与其他应用同时播放,关键代码
  1396. let strategy: audio.AudioSessionStrategy = {
  1397. concurrencyMode: audio.AudioConcurrencyMode.CONCURRENCY_MIX_WITH_OTHERS
  1398. };
  1399. audioSessionManager.activateAudioSession(strategy).then(() => {
  1400. console.info('onecold Succeeded in doing activateAudioSession.');
  1401. }).catch((err: BusinessError) => {
  1402. console.error(`Failed to activateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1403. });
  1404. }else{
  1405. let isActivated = audioSessionManager.isAudioSessionActivated();
  1406. if(isActivated){
  1407. audioSessionManager.deactivateAudioSession().then(() => {
  1408. console.info('Succeeded in doing deactivateAudioSession.');
  1409. }).catch((err: BusinessError) => {
  1410. console.error(`Failed to deactivateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1411. });
  1412. }
  1413. }
  1414. if(this.volumeSmall){
  1415. this.volume = 0.5
  1416. }else{
  1417. this.volume = 1
  1418. }
  1419. //如果是hicar连接状态,这些都是false
  1420. if(this.isHiCar()){
  1421. this.autoHideTitle = false
  1422. this.isCoverRectangle= true
  1423. this.columns=4
  1424. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  1425. {
  1426. this.isGridMusic= false//用list不用网格
  1427. this.isCoverTopBig = false
  1428. }
  1429. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  1430. }
  1431. if (this.isSavePlayMode) {
  1432. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  1433. }
  1434. }
  1435. doChangeSetting() {
  1436. this.initSetting()
  1437. this.deleteCache(this.currentPath)
  1438. if (this.modeType === 0) {
  1439. this.getSortedFiles(this.currentPath)
  1440. }
  1441. }
  1442. doChangeBarHeight() {
  1443. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  1444. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  1445. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  1446. this.setBarHeightNormal()
  1447. }
  1448. }
  1449. onPageShow() {
  1450. this.knockController?.immersiveListening();
  1451. app.setImageCacheCount(100);
  1452. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  1453. app.setImageRawDataCacheSize(104857600);
  1454. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  1455. }
  1456. //开启线程查看各个数据库
  1457. makeWorker() {
  1458. setTimeout(() => {
  1459. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  1460. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  1461. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  1462. // workerInstance.postMessage({
  1463. // code: 1,
  1464. // data1: this.context,
  1465. // data2: this.rootPath,
  1466. // data3: this.lockPath,
  1467. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1468. // data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  1469. // });
  1470. PreferencesUtil.putSync('isFirstApp', false)
  1471. } else {
  1472. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1473. workerInstance.postMessage({ code: 3, data: this.context });
  1474. workerInstance.postMessage({ code: 4, data: this.context });
  1475. this.getHistoryList(false)
  1476. }
  1477. }, 1000)
  1478. workerInstance.onmessage = (e: MessageEvents): void => {
  1479. switch (e.data.code) {
  1480. case 101: //第一次扫描文件夹入库
  1481. ToastUtil.showToast('刷新同步数据库成功!')
  1482. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  1483. this.doAllUpdateData()
  1484. break;
  1485. case 102: //查询媒体库列表
  1486. this.isRefreshing = false
  1487. this.mediaKuList = e.data.data
  1488. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  1489. Utility.doSortListAscending(this.mediaKuList)
  1490. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  1491. if (this.modeType === 1) {
  1492. this.updateListData(this.mediaKuList)
  1493. }
  1494. PreferencesUtil.putSync('mediaKuCount', this.mediaKuList.length)
  1495. // 处理媒体库前100条记录,列表长度并存储到PreferencesUtil
  1496. if (ArrayUtil.isNotEmpty(this.mediaKuList)&&this.mediaKuList.length > 100) {
  1497. // 只保存前100条记录到缓存中
  1498. let truncatedList = this.mediaKuList.slice(0, 100);
  1499. PreferencesUtil.putSync('mediaKuList', JSON.stringify(truncatedList));
  1500. } else {
  1501. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  1502. }
  1503. break;
  1504. case 103: //收到查询艺术家列表
  1505. this.isRefreshing = false
  1506. this.artistMap = e.data.data1;
  1507. this.artistList = e.data.data2;
  1508. PreferencesUtil.putSync('artistCount', this.artistList.length)
  1509. // 处理艺术家前100条记录,列表长度并存储到PreferencesUtil
  1510. if (ArrayUtil.isNotEmpty(this.artistList)&&this.artistList.length > 100) {
  1511. // 只保存前100条记录到缓存中
  1512. let truncatedList = this.artistList.slice(0, 100);
  1513. PreferencesUtil.putSync('artistList', JSON.stringify(truncatedList));
  1514. } else {
  1515. PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
  1516. }
  1517. // 处理并缓存前60条艺术家数据
  1518. const sortedEntries = Array.from(this.artistMap.entries())
  1519. .sort((a, b) => b[1].length - a[1].length)
  1520. .slice(0, 60);
  1521. PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
  1522. break;
  1523. case 104: //收到查询专辑列表
  1524. this.isRefreshing = false
  1525. this.albumMap = e.data.data1;
  1526. this.albumList = e.data.data2
  1527. //查询完毕在启动是否自动播放
  1528. if (this.isStartAutoPlay&&this.isCanAuto) {
  1529. this.isCanAuto = false
  1530. console.info('onecold startPlayOrResumePlay 757')
  1531. this.startPlayOrResumePlay()
  1532. }
  1533. PreferencesUtil.putSync('albumCount', this.albumList.length)
  1534. // 处理专辑前100条记录,列表长度并存储到PreferencesUtil
  1535. if (ArrayUtil.isNotEmpty(this.albumList)&&this.albumList.length > 100) {
  1536. // 只保存前100条记录到缓存中
  1537. let truncatedList = this.albumList.slice(0, 100);
  1538. PreferencesUtil.putSync('albumList', JSON.stringify(truncatedList));
  1539. } else {
  1540. PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
  1541. }
  1542. const mapArrayAlbum = Array.from(this.albumMap.entries())
  1543. .sort((a, b) => b[1].length - a[1].length)
  1544. .slice(0, 60);
  1545. PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
  1546. break;
  1547. case 105: // 缓存完成后返回的元数据
  1548. this.handleWorkerMetadataPayload(e.data.data as WorkerMetadataPayload);
  1549. break;
  1550. case 106: // 编辑音乐元数据和封面完成
  1551. this.handleEditMusicResult(e.data);
  1552. break;
  1553. }
  1554. };
  1555. // 在调用terminate后,执行onexit
  1556. workerInstance.onexit = (code) => {
  1557. metadataExtractionInFlight.clear();
  1558. Logger.info(TAG, 'workerInstance 线程已退出,code: ' + code);
  1559. }
  1560. workerInstance.onerror = (err: ErrorEvent) => {
  1561. metadataExtractionInFlight.clear();
  1562. console.error('workerInstance 线程执行发生异常: ' + err.message)
  1563. }
  1564. }
  1565. private handleWorkerMetadataPayload(payload: WorkerMetadataPayload | undefined): void {
  1566. if (!payload || !payload.originFilePath) {
  1567. return;
  1568. }
  1569. metadataExtractionInFlight.delete(payload.originFilePath);
  1570. if (payload.error) {
  1571. Logger.warn(TAG, `缓存文件元数据解析失败: ${payload.error}`);
  1572. return;
  1573. }
  1574. this.applyMetadataToCollections(payload.originFilePath, payload);
  1575. }
  1576. private applyMetadataToCollections(filePath: string, payload: WorkerMetadataPayload): void {
  1577. const targets: Array<VideoItem> = [];
  1578. let mainListUpdated = false;
  1579. let playlistUpdated = false;
  1580. if (this.currentSong && this.currentSong.filePath === filePath) {
  1581. targets.push(this.currentSong);
  1582. }
  1583. const collectFromList = (list?: Array<VideoItem>, markUpdated?: () => void) => {
  1584. if (!list || list.length === 0) {
  1585. return;
  1586. }
  1587. const found = Utility.getItemByFilePath(list, filePath);
  1588. if (found) {
  1589. markUpdated?.();
  1590. targets.push(found);
  1591. }
  1592. };
  1593. collectFromList(this.videoLocalList, () => {
  1594. mainListUpdated = true;
  1595. });
  1596. collectFromList(this.songList, () => {
  1597. playlistUpdated = true;
  1598. });
  1599. collectFromList(this.historyList);
  1600. collectFromList(this.favList);
  1601. const remoteManager = RemoteDriveManager.getInstance();
  1602. collectFromList(remoteManager.webDavSongs);
  1603. const updated = new Set<VideoItem>();
  1604. const remoteMetadataUpdates: Map<string, WebDavMetadataUpdatePayload> = new Map();
  1605. for (let i = 0; i < targets.length; i++) {
  1606. const target = targets[i];
  1607. if (!target || updated.has(target)) {
  1608. continue;
  1609. }
  1610. updated.add(target);
  1611. this.mergeVideoItemWithPayload(target, payload);
  1612. if (isRemoteCloudType(target.type) && StrUtil.isNotEmpty(target.filePath)) {
  1613. remoteMetadataUpdates.set(target.filePath, {
  1614. filePath: target.filePath,
  1615. pixelMapPath: target.pixelMapPath,
  1616. name: target.name,
  1617. artist: target.artist
  1618. });
  1619. }
  1620. }
  1621. if (this.currentSong && this.currentSong.filePath === filePath) {
  1622. this.mergeVideoItemWithPayload(this.currentSong, payload);
  1623. if (payload.name) {
  1624. this.name = payload.name;
  1625. }
  1626. if (payload.artist) {
  1627. this.artist = payload.artist;
  1628. }
  1629. if (payload.pixelMapPath) {
  1630. this.cover = payload.pixelMapPath;
  1631. }
  1632. if (payload.lyricContent) {
  1633. this.applyInlineLyricContent(payload.lyricContent);
  1634. }
  1635. let avSessionDurationMs = this.duration;
  1636. if (payload.duration) {
  1637. const durationSeconds = Number(payload.duration);
  1638. if (!Number.isNaN(durationSeconds) && durationSeconds > 0) {
  1639. avSessionDurationMs = durationSeconds * 1000;
  1640. this.duration = avSessionDurationMs;
  1641. this.durationTime = Math.floor(avSessionDurationMs / 1000);
  1642. this.durationStringTime = secondToTime(this.durationTime);
  1643. }
  1644. }
  1645. if (avSessionDurationMs > 0) {
  1646. this.avSessionController.setAVMetadataMusic(this.currentSong, avSessionDurationMs, this.lyricContent);
  1647. }
  1648. this.currentSong = cloneVideoItem(this.currentSong);
  1649. AppStorage.setOrCreate('currentSong', this.currentSong);
  1650. }
  1651. const primaryTarget = targets.length > 0 ? targets[0] : undefined;
  1652. if (primaryTarget) {
  1653. this.persistRemoteMetadataToDb(primaryTarget).catch((error: Error) => {
  1654. Logger.error(TAG, `缓存元数据持久化失败: ${error.message}`);
  1655. });
  1656. }
  1657. if (remoteMetadataUpdates.size > 0) {
  1658. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  1659. emitter.emit(eventUpdate, { data: Array.from(remoteMetadataUpdates.values()) });
  1660. }
  1661. this.refreshLazyListViews(mainListUpdated, playlistUpdated);
  1662. }
  1663. private handleEditMusicResult(result: WorkerEditMusicResult): void {
  1664. // 关闭进度条
  1665. DialogHelper.closeLoading();
  1666. if (result.success) {
  1667. console.log("heanup 编辑信息成功,数据库已同步");
  1668. if (result.coverResult) {
  1669. ToastUtil.showToast('内嵌封面成功');
  1670. }
  1671. ToastUtil.showToast('内嵌音乐标签成功');
  1672. this.isShowMoreView = false;
  1673. this.name = this.titleStr;
  1674. // 同步当前播放的歌曲信息
  1675. if (this.editingItem && this.editingItem.filePath == this.currentSong?.filePath) {
  1676. this.currentSong.name = this.titleStr;
  1677. this.artist = this.artistStr;
  1678. this.currentSong.artist = this.artistStr;
  1679. this.currentSong.album = this.ablumStr;
  1680. this.currentSong.year = this.yearStr;
  1681. this.currentSong.genre = this.genreStr;
  1682. this.currentSong.track = this.trackStr;
  1683. this.currentSong.lyricContent = this.lyricConStr;
  1684. this.currentSong.ALBUMARTIST = this.albumArtistStr;
  1685. this.currentSong.COMPOSER = this.composerStr;
  1686. this.currentSong.LYRICIST = this.lyricistStr;
  1687. this.currentSong.COMMENT = this.commentStr;
  1688. }
  1689. // if (result.needRefreshList && this.modeType == 0) {
  1690. // this.deleteCache(this.currentPath);
  1691. // this.getSortedFiles(this.currentPath);
  1692. // }
  1693. // 同步编辑字段到本地列表
  1694. if (this.editingItem) {
  1695. this.syncEditedFields(this.editingItem);
  1696. this.syncListsAfterEdit(this.editingItem.filePath);
  1697. this.doUpateEditedFields(this.editingItem);
  1698. }
  1699. // 清理临时变量
  1700. this.longItemFilePath = '';
  1701. this.tempLyricContent = '';
  1702. this.isShowEdit = false;
  1703. this.imagePathStr = '';
  1704. } else {
  1705. console.error("heanup 编辑信息失败: " + result.error);
  1706. ToastUtil.showToast('编辑失败: ' + (result.error || '未知错误'));
  1707. // 清理临时变量
  1708. this.longItemFilePath = '';
  1709. this.tempLyricContent = '';
  1710. this.isShowEdit = false;
  1711. this.imagePathStr = '';
  1712. }
  1713. }
  1714. private assignStringMetadata(target: VideoItem, key: keyof VideoItem, value?: string | null, allowEmpty = false): void {
  1715. if (value === undefined || value === null) {
  1716. return;
  1717. }
  1718. const text = value.toString();
  1719. if (!allowEmpty && text.trim().length === 0) {
  1720. return;
  1721. }
  1722. Reflect.set(target, key as string, value);
  1723. }
  1724. private assignNumberMetadata(target: VideoItem, key: keyof VideoItem, value?: number | null): void {
  1725. if (value === undefined || value === null || Number.isNaN(value)) {
  1726. return;
  1727. }
  1728. Reflect.set(target, key as string, value);
  1729. }
  1730. private mergeVideoItemWithPayload(target: VideoItem, payload: WorkerMetadataPayload): void {
  1731. if (!target || !payload) {
  1732. return;
  1733. }
  1734. this.assignStringMetadata(target, 'name', payload.name);
  1735. this.assignStringMetadata(target, 'artist', payload.artist);
  1736. this.assignStringMetadata(target, 'album', payload.album);
  1737. this.assignStringMetadata(target, 'bit_rate', payload.bit_rate);
  1738. this.assignStringMetadata(target, 'duration', payload.duration);
  1739. this.assignStringMetadata(target, 'sampleRate', payload.sampleRate);
  1740. this.assignStringMetadata(target, 'mimeType', payload.mimeType);
  1741. this.assignStringMetadata(target, 'size', payload.size);
  1742. this.assignStringMetadata(target, 'pixelMapPath', payload.pixelMapPath);
  1743. this.assignStringMetadata(target, 'lyricContent', payload.lyricContent, true);
  1744. this.assignStringMetadata(target, 'genre', payload.genre);
  1745. this.assignStringMetadata(target, 'track', payload.track);
  1746. this.assignStringMetadata(target, 'bits_per_raw_sample', payload.bits_per_raw_sample);
  1747. this.assignStringMetadata(target, 'channels', payload.channels);
  1748. this.assignStringMetadata(target, 'channel_layout', payload.channel_layout);
  1749. this.assignStringMetadata(target, 'start_time', payload.start_time);
  1750. this.assignStringMetadata(target, 'year', payload.year);
  1751. this.assignStringMetadata(target, 'disc', payload.disc);
  1752. this.assignStringMetadata(target, 'ALBUMARTIST', payload.ALBUMARTIST);
  1753. this.assignStringMetadata(target, 'COMPOSER', payload.COMPOSER);
  1754. this.assignStringMetadata(target, 'LYRICIST', payload.LYRICIST);
  1755. this.assignStringMetadata(target, 'COMMENT', payload.COMMENT, true);
  1756. this.assignNumberMetadata(target, 'videoSize', payload.videoSize);
  1757. this.assignNumberMetadata(target, 'probe_score', payload.probe_score);
  1758. this.assignNumberMetadata(target, 'nb_streams', payload.nb_streams);
  1759. this.assignNumberMetadata(target, 'nb_programs', payload.nb_programs);
  1760. }
  1761. private mergeVideoItemFromSource(target: VideoItem, source: VideoItem): void {
  1762. if (!target || !source) {
  1763. return;
  1764. }
  1765. this.assignStringMetadata(target, 'name', source.name);
  1766. this.assignStringMetadata(target, 'artist', source.artist);
  1767. this.assignStringMetadata(target, 'album', source.album);
  1768. this.assignStringMetadata(target, 'bit_rate', source.bit_rate);
  1769. this.assignStringMetadata(target, 'duration', source.duration);
  1770. this.assignStringMetadata(target, 'sampleRate', source.sampleRate);
  1771. this.assignStringMetadata(target, 'trackCount', source.trackCount);
  1772. this.assignStringMetadata(target, 'mimeType', source.mimeType);
  1773. this.assignStringMetadata(target, 'size', source.size);
  1774. this.assignStringMetadata(target, 'pixelMapPath', source.pixelMapPath);
  1775. this.assignStringMetadata(target, 'lyricContent', source.lyricContent, true);
  1776. this.assignStringMetadata(target, 'genre', source.genre);
  1777. this.assignStringMetadata(target, 'track', source.track);
  1778. this.assignStringMetadata(target, 'bits_per_raw_sample', source.bits_per_raw_sample);
  1779. this.assignStringMetadata(target, 'channels', source.channels);
  1780. this.assignStringMetadata(target, 'channel_layout', source.channel_layout);
  1781. this.assignStringMetadata(target, 'start_time', source.start_time);
  1782. this.assignStringMetadata(target, 'year', source.year);
  1783. this.assignStringMetadata(target, 'disc', source.disc);
  1784. this.assignStringMetadata(target, 'ALBUMARTIST', source.ALBUMARTIST);
  1785. this.assignStringMetadata(target, 'COMPOSER', source.COMPOSER);
  1786. this.assignStringMetadata(target, 'LYRICIST', source.LYRICIST);
  1787. this.assignStringMetadata(target, 'COMMENT', source.COMMENT, true);
  1788. this.assignNumberMetadata(target, 'videoSize', source.videoSize);
  1789. this.assignNumberMetadata(target, 'probe_score', source.probe_score);
  1790. this.assignNumberMetadata(target, 'nb_streams', source.nb_streams);
  1791. this.assignNumberMetadata(target, 'nb_programs', source.nb_programs);
  1792. if (source.remote_rel_path && StrUtil.isEmpty(target.remote_rel_path)) {
  1793. target.remote_rel_path = source.remote_rel_path;
  1794. }
  1795. }
  1796. private async hydrateRemoteSongFromDb(item: VideoItem | undefined): Promise<void> {
  1797. if (!item || !isRemoteCloudType(item.type)) {
  1798. return;
  1799. }
  1800. const storagePath = item.remote_rel_path || WebDavUrlUtil.toStoragePath(item.filePath);
  1801. if (!storagePath) {
  1802. return;
  1803. }
  1804. try {
  1805. const cached = await this.table.queryVideoByFilePath(storagePath);
  1806. if (!cached) {
  1807. return;
  1808. }
  1809. this.mergeVideoItemFromSource(item, cached);
  1810. if (StrUtil.isEmpty(item.remote_rel_path)) {
  1811. item.remote_rel_path = storagePath;
  1812. }
  1813. if (item === this.currentSong) {
  1814. if (StrUtil.isNotEmpty(item.name)) {
  1815. this.name = item.name;
  1816. }
  1817. if (StrUtil.isNotEmpty(item.artist)) {
  1818. this.artist = item.artist!;
  1819. }
  1820. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  1821. this.cover = item.pixelMapPath!;
  1822. }
  1823. if (StrUtil.isNotEmpty(item.lyricContent) && StrUtil.isEmpty(this.lyricContent)) {
  1824. this.applyInlineLyricContent(item.lyricContent as string);
  1825. }
  1826. }
  1827. } catch (error) {
  1828. Logger.error(TAG, `hydrateRemoteSongFromDb 失败: ${(error as Error).message}`);
  1829. }
  1830. }
  1831. private applyInlineLyricContent(content: string): void {
  1832. if (StrUtil.isEmpty(content)) {
  1833. return;
  1834. }
  1835. this.lyricContent = content;
  1836. const lines = content.split('\n').map(line => line.trim());
  1837. const lyric = this.parser.parse(lines);
  1838. this.lyricController.setLyric(lyric);
  1839. this.lyricControllerXF.setLyric(lyric);
  1840. this.lyricControllerSingle.setLyric(lyric);
  1841. }
  1842. private extractParentPathFromStoragePath(path: string): string {
  1843. if (!path) {
  1844. return '';
  1845. }
  1846. const lastSlash = path.lastIndexOf('/');
  1847. if (lastSlash <= 0) {
  1848. return '';
  1849. }
  1850. return path.substring(0, lastSlash);
  1851. }
  1852. private resolveRemoteStoragePath(target: VideoItem): string | null {
  1853. if (!target || !isRemoteCloudType(target.type)) {
  1854. return null;
  1855. }
  1856. if (isWebDavType(target.type)) {
  1857. const storagePath = target.remote_rel_path || WebDavUrlUtil.toStoragePath(target.filePath);
  1858. if (storagePath) {
  1859. target.remote_rel_path = storagePath;
  1860. return storagePath;
  1861. }
  1862. return null;
  1863. }
  1864. if (target.remote_rel_path && target.remote_rel_path.length > 0) {
  1865. return target.remote_rel_path;
  1866. }
  1867. return null;
  1868. }
  1869. private async persistRemoteMetadataToDb(target: VideoItem): Promise<void> {
  1870. if (!this.context || !target || !isRemoteCloudType(target.type)) {
  1871. return;
  1872. }
  1873. const storagePath = this.resolveRemoteStoragePath(target);
  1874. if (!storagePath) {
  1875. return;
  1876. }
  1877. const table = new MediaTable(this.context);
  1878. await new Promise<void>((resolve) => {
  1879. table.getRdbStore(this.context as Context, () => resolve());
  1880. });
  1881. const cloneItem = cloneVideoItem(target);
  1882. cloneItem.filePath = storagePath;
  1883. cloneItem.remote_rel_path = storagePath;
  1884. cloneItem.parentPath = this.extractParentPathFromStoragePath(storagePath);
  1885. await table.saveOrUpdateWebDavItem(cloneItem);
  1886. }
  1887. onPageHide(): void {
  1888. this.knockController?.immersiveDisableListening();
  1889. }
  1890. @State isFirstStartPlay: boolean = false
  1891. private async startFileDeletionWatcher(): Promise<void> {
  1892. if (!this.rootPath) {
  1893. return;
  1894. }
  1895. if (!this.deletionWatcher) {
  1896. this.deletionWatcher = new FileDeletionWatcher(this.context, this.table);
  1897. }
  1898. try {
  1899. await this.deletionWatcher.watchDirectories([
  1900. this.rootPath,
  1901. this.lockPath,
  1902. this.favPath,
  1903. this.historyPath
  1904. ]);
  1905. } catch (error) {
  1906. Logger.error(TAG, `初始化文件删除监听失败: ${(error as Error).message}`);
  1907. }
  1908. }
  1909. //获取download_path
  1910. async mkDownLoadDir() {
  1911. const documentViewPicker = new picker.DocumentViewPicker()
  1912. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  1913. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  1914. PreferencesUtil.putSync('download_path', this.rootPath+'/')
  1915. this.currentPath = this.rootPath
  1916. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  1917. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  1918. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  1919. Logger.info('onecold rootPath = ' + this.rootPath)
  1920. Logger.info('onecold lockPath = ' + this.lockPath)
  1921. if (!FileUtil.accessSync(this.lockPath)) {
  1922. FileUtil.mkdirSync(this.lockPath)
  1923. }
  1924. if (!FileUtil.accessSync(this.favPath)) {
  1925. FileUtil.mkdirSync(this.favPath)
  1926. }
  1927. if (!FileUtil.accessSync(this.historyPath)) {
  1928. FileUtil.mkdirSync(this.historyPath)
  1929. }
  1930. // await this.startFileDeletionWatcher();
  1931. this.getSortedFiles(this.rootPath).then(async () => {
  1932. this.isFavMusic = false
  1933. //穿山甲
  1934. // this.loadBannerAd(CSJUtil.getBannerID())
  1935. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  1936. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  1937. if (ArrayUtil.isEmpty(this.songList)) {
  1938. this.songList = this.getCurFileList()
  1939. } else {
  1940. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  1941. }
  1942. if (ArrayUtil.isNotEmpty(this.songList)) {
  1943. this.isFirstStartPlay = true
  1944. this.sonDataSource.pushArrayData(this.songList)
  1945. if (this.currentSong === undefined) {
  1946. this.isFirstStartPlay = false
  1947. this.currentSong = this.songList[0]
  1948. }
  1949. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  1950. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  1951. context: this.context,
  1952. autoParseMusicName: this.autoParseMusicName
  1953. });
  1954. Logger.info(TAG, `WebDAV URL同步构建完成: ${this.videoUrl}`);
  1955. this.name = this.currentSong.name
  1956. this.cover = this.currentSong.pixelMapPath
  1957. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  1958. } else {
  1959. this.name = '空空如也'
  1960. }
  1961. })
  1962. this.getFavList(false)
  1963. }
  1964. getFavList(isFavRefresh: boolean) {
  1965. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  1966. this.favList = result
  1967. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  1968. this.videoLocalList = this.favList
  1969. this.updateListData(this.videoLocalList)
  1970. }
  1971. })
  1972. }
  1973. getHistoryList(isRefresh: boolean) {
  1974. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  1975. this.historyList = result
  1976. // for (let i = 0; i < this.historyList.length; i++) {
  1977. //
  1978. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  1979. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  1980. // }
  1981. if (isRefresh) {
  1982. this.videoLocalList = this.historyList
  1983. this.updateListData(this.videoLocalList, true)
  1984. }
  1985. })
  1986. }
  1987. // 组件消失生命周期
  1988. aboutToDisappear() {
  1989. console.info('LifeCycleComponent aboutToDisappear');
  1990. this.deletionWatcher?.stop();
  1991. this.knockController?.immersiveDisableListening();
  1992. this.curIndex = 0
  1993. emitter.off(EventConstants.EVENT_AUDIO_OPEN);
  1994. emitter.off(EventConstants.EVENT_SCAN_UPDATE);
  1995. emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
  1996. emitter.off(EventConstants.EVENT_SETTING_UPDATE);
  1997. this.mDestroyPage = true;
  1998. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  1999. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  2000. this.stop();
  2001. }
  2002. this.mIjkMediaPlayer.off('audioInterrupt');
  2003. this.mIjkMediaPlayer.off('deviceChange');
  2004. if (workerInstance) {
  2005. workerInstance.terminate();
  2006. }
  2007. this.stopPip();
  2008. this.destroyPipController()
  2009. this.getUIContext().getHostContext()!.eventHub.off('playOrPause');
  2010. this.getUIContext().getHostContext()!.eventHub.off('playPrevious');
  2011. this.getUIContext().getHostContext()!.eventHub.off('playNext');
  2012. this.getUIContext().getHostContext()!.eventHub.off('showPlayerView');
  2013. this.getUIContext().getHostContext()!.eventHub.off('openPlayList');
  2014. }
  2015. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean,openItem?:VideoItem) {
  2016. this.isFavMusic = false
  2017. console.info('onecold getSortedFiles 1 curPath '+curPath)
  2018. if (isWorkerPost) {
  2019. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  2020. }
  2021. if (this.modeType !== 0) {
  2022. return
  2023. }
  2024. console.info('onecold getSortedFiles 2')
  2025. this.isCanBack = false
  2026. this.currentPath = curPath
  2027. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  2028. this.titleName = getFileDirName(this.currentPath,this.rootPath)
  2029. if (curPath === this.rootPath) {
  2030. this.rightTopImage = $r('sys.symbol.sort')
  2031. } else {
  2032. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  2033. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  2034. this.rightTopImage = $r('sys.symbol.chevron_left')
  2035. }
  2036. }
  2037. // Get the current file list and calculate its hash
  2038. this.fileList = FileUtil.listFileSync(curPath);
  2039. const currentHash = simpleHash(this.fileList);
  2040. // Check cache
  2041. const cachedValue = this.findCache(curPath);
  2042. Logger.info('onecold cachedValue = ' + cachedValue)
  2043. const cachedHash = this.findStringCache(curPath + '_hash');
  2044. const cachedDirList = this.findCache(curPath + "_dirList");
  2045. if (cachedValue !== undefined&&!this.isRefreshing) {
  2046. // this.videoLocalList = cachedValue;
  2047. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  2048. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  2049. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  2050. }
  2051. this.isRefreshing = false
  2052. this.updateListData(cachedValue)
  2053. }
  2054. if (cachedDirList !== undefined) {
  2055. this.dirList = cachedDirList
  2056. }
  2057. //通过当前hash值和缓存hash判断list有没有变化
  2058. if (cachedValue && cachedHash === currentHash) {
  2059. return;
  2060. }
  2061. // this.fileList = FileUtil.listFileSync(curPath)
  2062. let directories: Array<VideoItem> = [];
  2063. let files: Array<VideoItem> = [];
  2064. for (let i = 0; i < this.fileList.length; i++) {
  2065. console.info(`The name of file: ${this.fileList[i]}`);
  2066. let path = curPath + '/' + this.fileList[i]
  2067. if (FileUtil.isDirectory(path)) {
  2068. let item: VideoItem =
  2069. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  2070. '')
  2071. if (this.isShowDir(item.name)) {
  2072. directories.push(item);
  2073. }
  2074. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2075. // Utility.doSortListAscending(directories)
  2076. } else {
  2077. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  2078. let item: VideoItem =
  2079. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  2080. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  2081. files.push(item);
  2082. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2083. // this.doSortListAscending(files)
  2084. }
  2085. }
  2086. }
  2087. }
  2088. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  2089. if (this.currentPath !== this.lockPath) {
  2090. files = result;
  2091. }
  2092. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2093. Utility.doSortListAscending(files)
  2094. if (this.currentPath === this.rootPath) {
  2095. this.dirList = directories
  2096. this.addCache(curPath + "_dirList", this.dirList);
  2097. }
  2098. //插入广告先注释掉
  2099. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  2100. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  2101. // directories.push(adItem)
  2102. // }
  2103. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  2104. this.videoLocalList = directories.concat(files);
  2105. this.updateListData(this.videoLocalList)
  2106. if (ArrayUtil.isNotEmpty(files)) {
  2107. if (this.currentPath != this.rootPath) {
  2108. if (files) {
  2109. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  2110. }
  2111. }
  2112. // 缓存结果
  2113. this.addCache(curPath, this.videoLocalList);
  2114. await this.saveCacheToStorage(); // 保存缓存至本地存储
  2115. this.addStringCache(curPath + '_hash', currentHash);
  2116. }
  2117. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  2118. for (let i = 0; i < this.videoLocalList.length; i++) {
  2119. console.info(`onecold gengxin 1: ${this.videoLocalList[i].name}`);
  2120. }
  2121. // this.setButtonStatus()
  2122. this.openMusic(isOpen, destPath,openItem)
  2123. this.isRefreshing = false
  2124. });
  2125. }
  2126. //第三方app打开天天静听导入音乐后播放
  2127. openMusic(isOpen?: boolean, destPath?: string,openItem?:VideoItem){
  2128. if (isOpen&&destPath) {
  2129. if (destPath === undefined) {
  2130. // 处理 destPath 为 undefined 的情况
  2131. return
  2132. }
  2133. if (destPath.endsWith('.lrc')) {
  2134. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  2135. if (StrUtil.isNotEmpty(this.videoUrl)) {
  2136. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  2137. this.initLyric(lyricPath);
  2138. }
  2139. return
  2140. }
  2141. if(openItem){
  2142. this.doPlay(openItem,0,false,true)
  2143. // this.isShowPlay = true
  2144. this.setShowPlayTrue()
  2145. }
  2146. }
  2147. }
  2148. //扫描文件夹入库
  2149. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  2150. const files = FileUtil.listFileSync(curPath);
  2151. let mediaItems: VideoItem[] = [];
  2152. Logger.info('onecold scanDirectory start ')
  2153. for (const file of files) {
  2154. const fPath = `${curPath}/${file}`;
  2155. if (fPath === this.lockPath) {
  2156. Logger.info(`Skipping locked path: ${fPath}`);
  2157. continue;
  2158. }
  2159. if (FileUtil.isDirectory(fPath)) {
  2160. // Recursively scan subdirectories
  2161. const subDirItems = await this.scanDirectory(fPath);
  2162. mediaItems = mediaItems.concat(subDirItems);
  2163. } else {
  2164. Logger.info('onecold scanDirectory filePath = ' + fPath)
  2165. // Process media files
  2166. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  2167. let mediaItem: VideoItem =
  2168. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2169. mediaItems.push(mediaItem);
  2170. this.table.insert(mediaItem, (id: number) => {
  2171. });
  2172. }
  2173. }
  2174. }
  2175. return mediaItems;
  2176. }
  2177. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  2178. this.isShowTitleBar = true
  2179. animateTo({ duration: 666 }, () => {
  2180. this.opacityItem = 0.5;
  2181. });
  2182. setTimeout(() => {
  2183. this.videoLocalList = mList;
  2184. if (!noSort) {
  2185. if (this.modeType === 0 || this.modeType === 1) {
  2186. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  2187. this.doSortType(this.sortType)
  2188. }
  2189. }
  2190. this.dataSource.pushArrayData(this.videoLocalList)
  2191. animateTo({ duration: 666 }, () => {
  2192. this.opacityItem = 1;
  2193. });
  2194. this.setButtonStatus()
  2195. //添加到字母索引表
  2196. this.setAlphaBet()
  2197. }, 200);
  2198. }
  2199. getCurFileList(): Array<VideoItem> {
  2200. if(this.isSearchMode){
  2201. return this.filteredList
  2202. }
  2203. let files: Array<VideoItem> = [];
  2204. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2205. for (let i = 0; i < this.videoLocalList.length; i++) {
  2206. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  2207. files.push(this.videoLocalList[i]);
  2208. }
  2209. }
  2210. }
  2211. return files
  2212. }
  2213. setButtonStatus() {
  2214. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2215. this.isZero = false
  2216. } else {
  2217. this.isZero = true
  2218. }
  2219. if (this.currentPath !== this.rootPath &&
  2220. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  2221. this.isHasDir = true //不为空,说明有子文件夹
  2222. } else {
  2223. this.isHasDir = false
  2224. }
  2225. }
  2226. @Builder
  2227. SortMenuBuilder() {
  2228. Menu() {
  2229. MenuItem({
  2230. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2231. content: "按艺术家升序"
  2232. })
  2233. .onClick(async () => {
  2234. this.doSortType(0)
  2235. PreferencesUtil.put(SettingPage.SORT_TYPE, 0)
  2236. this.updateListData(this.videoLocalList, true)
  2237. })
  2238. MenuItem({
  2239. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2240. content: "按艺术家降序"
  2241. })
  2242. .onClick(async () => {
  2243. this.doSortType(1)
  2244. PreferencesUtil.put(SettingPage.SORT_TYPE, 1)
  2245. this.updateListData(this.videoLocalList, true)
  2246. })
  2247. MenuItem({
  2248. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat_size_square')),
  2249. content: "按专辑升序"
  2250. })
  2251. .onClick(async () => {
  2252. this.doSortType(2)
  2253. PreferencesUtil.put(SettingPage.SORT_TYPE, 2)
  2254. this.updateListData(this.videoLocalList, true)
  2255. })
  2256. MenuItem({
  2257. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.character_arrow_clockwise')),
  2258. content: "按专辑降序"
  2259. })
  2260. .onClick(async () => {
  2261. this.doSortType(3)
  2262. PreferencesUtil.put(SettingPage.SORT_TYPE, 3)
  2263. this.updateListData(this.videoLocalList, true)
  2264. })
  2265. MenuItem({
  2266. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2267. content: $r('app.string.sort_by_name')
  2268. })
  2269. .onClick(async () => {
  2270. this.doSortType(4)
  2271. PreferencesUtil.put(SettingPage.SORT_TYPE, 4)
  2272. this.updateListData(this.videoLocalList, true)
  2273. })
  2274. MenuItem({
  2275. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2276. content: '按名称降序'
  2277. })
  2278. .onClick(async () => {
  2279. this.doSortType(5)
  2280. PreferencesUtil.put(SettingPage.SORT_TYPE, 5)
  2281. this.updateListData(this.videoLocalList, true)
  2282. })
  2283. MenuItem({
  2284. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2285. content: $r('app.string.sort_by_time')
  2286. })
  2287. .onClick(async () => {
  2288. this.doSortType(6)
  2289. PreferencesUtil.put(SettingPage.SORT_TYPE, 6)
  2290. this.updateListData(this.videoLocalList, true)
  2291. })
  2292. MenuItem({
  2293. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  2294. content: '按添加时间降序'
  2295. })
  2296. .onClick(async () => {
  2297. this.doSortType(7)
  2298. PreferencesUtil.put(SettingPage.SORT_TYPE, 7)
  2299. this.updateListData(this.videoLocalList, true)
  2300. })
  2301. }.attributeModifier(new MenuModifier())
  2302. }
  2303. @Builder
  2304. SortMenuForArtistAblumBuilder() {
  2305. Menu() {
  2306. MenuItem({
  2307. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2308. content: $r('app.string.sort_by_name')
  2309. })
  2310. .onClick(async () => {
  2311. this.doSortType(4)
  2312. // PreferencesUtil.put(SettingPage.SORT_TYPE, 2)
  2313. this.updateListData(this.videoLocalList, true)
  2314. })
  2315. MenuItem({
  2316. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2317. content: '按名称降序'
  2318. })
  2319. .onClick(async () => {
  2320. this.doSortType(5)
  2321. this.updateListData(this.videoLocalList, true)
  2322. })
  2323. MenuItem({
  2324. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2325. content: '按数量升序'
  2326. })
  2327. .onClick(async () => {
  2328. this.doSortType(8)
  2329. this.updateListData(this.videoLocalList, true)
  2330. })
  2331. MenuItem({
  2332. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  2333. content: '按数量降序'
  2334. })
  2335. .onClick(async () => {
  2336. this.doSortType(9)
  2337. this.updateListData(this.videoLocalList, true)
  2338. })
  2339. }.attributeModifier(new MenuModifier())
  2340. }
  2341. doSortType(index: number) {
  2342. switch (index) {
  2343. case 0:
  2344. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2345. // 类型排序优先级
  2346. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2347. if (typeOrder !== 0) {
  2348. return typeOrder;
  2349. }
  2350. // 处理艺术家可能为undefined的字符串比较
  2351. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  2352. const artistB = b.artist?.trim() || '';
  2353. return artistA.localeCompare(artistB);
  2354. });
  2355. break;
  2356. case 1:
  2357. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2358. // 类型排序优先级
  2359. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2360. if (typeOrder !== 0) {
  2361. return typeOrder;
  2362. }
  2363. // 处理艺术家可能为undefined的字符串比较
  2364. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  2365. const artistB = b.artist?.trim() || '';
  2366. return artistB.localeCompare(artistA);
  2367. });
  2368. break;
  2369. case 2:
  2370. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2371. // 类型排序优先级
  2372. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2373. if (typeOrder !== 0) {
  2374. return typeOrder;
  2375. }
  2376. // 处理专辑可能为undefined的字符串比较
  2377. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  2378. const albumB = b.album?.trim() || '';
  2379. return albumA.localeCompare(albumB);
  2380. });
  2381. break;
  2382. case 3:
  2383. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2384. // 类型排序优先级
  2385. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2386. if (typeOrder !== 0) {
  2387. return typeOrder;
  2388. }
  2389. // 处理专辑可能为undefined的字符串比较
  2390. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  2391. const albumB = b.album?.trim() || '';
  2392. return albumB.localeCompare(albumA);
  2393. });
  2394. break;
  2395. case 4:
  2396. Utility.doSortListAscending(this.videoLocalList,this.isShowFileName)
  2397. break;
  2398. case 5:
  2399. Utility.doSortListDescending(this.videoLocalList,this.isShowFileName)
  2400. break;
  2401. case 6:
  2402. this.videoLocalList.sort((a, b) => {
  2403. // First, sort by type
  2404. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2405. if (typeOrder !== 0) {
  2406. return typeOrder;
  2407. }
  2408. // If types are the same, sort by cTime in ascending order
  2409. return a.cTime.localeCompare(b.cTime);
  2410. });
  2411. break;
  2412. case 7:
  2413. this.videoLocalList.sort((a, b) => {
  2414. // First, sort by type
  2415. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2416. if (typeOrder !== 0) {
  2417. return typeOrder;
  2418. }
  2419. // If types are the same, sort by cTime in descending order
  2420. return b.cTime.localeCompare(a.cTime);
  2421. });
  2422. break;
  2423. case 8:
  2424. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  2425. // 1. Sort by type first
  2426. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  2427. if (typeOrder !== 0) {
  2428. return typeOrder;
  2429. }
  2430. // 2. Then sort by artist count (numeric comparison)
  2431. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  2432. if(this.modeType === 2){
  2433. sortMap = this.artistMap
  2434. }else{
  2435. sortMap = this.albumMap
  2436. }
  2437. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  2438. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  2439. return aArtistCount - bArtistCount;
  2440. });
  2441. break;
  2442. case 9:
  2443. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  2444. // 1. Sort by type first
  2445. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  2446. if (typeOrder !== 0) {
  2447. return typeOrder;
  2448. }
  2449. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  2450. if(this.modeType === 2){
  2451. sortMap = this.artistMap
  2452. }else{
  2453. sortMap = this.albumMap
  2454. }
  2455. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  2456. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  2457. return bArtistCount - aArtistCount;
  2458. });
  2459. break;
  2460. }
  2461. }
  2462. showSheelDialog() {
  2463. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  2464. // this.showTips()
  2465. // return
  2466. // }
  2467. this.showAddDialog()
  2468. }
  2469. showAddDialog() {
  2470. if (this.modeType === 2 || this.modeType === 3) {
  2471. return
  2472. }
  2473. DialogHelper.showActionSheetDialog({
  2474. title: "请选择添加方式(建议歌词文件一起导入)",
  2475. sheets: [
  2476. { value: "新建文件夹", fontColor: $r('app.color.text_color') },
  2477. { value: "手动导入", fontColor: $r('app.color.text_color') },
  2478. { value: "自动导入", fontColor: $r('app.color.text_color') },
  2479. { value: "全选导入", fontColor: $r('app.color.text_color') },
  2480. ],
  2481. maskColor: Color.Transparent,
  2482. backgroundColor: $r('app.color.bg_card'),
  2483. transition: AnimationHelper.transitionInDown(555),
  2484. onAction: (index) => {
  2485. switch (index) {
  2486. case 0:
  2487. if (this.modeType === 0) {
  2488. this.showMkDialog()
  2489. } else {
  2490. ToastUtil.showToast('请切换到首页才能新建文件夹!')
  2491. }
  2492. break;
  2493. case 1:
  2494. this.callFilePickerSelectFile()
  2495. break;
  2496. case 2:
  2497. this.showTips()
  2498. break;
  2499. case 3:
  2500. this.goSelectMusic()
  2501. break;
  2502. }
  2503. }
  2504. })
  2505. }
  2506. //拉起音频
  2507. goSelectMusic() {
  2508. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  2509. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  2510. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  2511. ) {
  2512. ToastUtil.showToast('暂时不支持该设备')
  2513. return
  2514. }
  2515. try {
  2516. let documentSelectOptions = new picker.DocumentSelectOptions();
  2517. documentSelectOptions.authMode = true
  2518. documentSelectOptions.multiAuthMode = true
  2519. if( deviceInfo.sdkApiVersion>=21){//如果api大于21 ,可以支持1w首歌以上
  2520. documentSelectOptions.maxSelectNumber = 20000
  2521. }
  2522. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  2523. let documentPicker = new picker.DocumentViewPicker(this.context);
  2524. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  2525. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  2526. this.saveVideoDatas(documentSelectResult)
  2527. }
  2528. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  2529. JSON.stringify(documentSelectResult));
  2530. }).catch((err: BusinessError) => {
  2531. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  2532. });
  2533. } catch (error) {
  2534. let err: BusinessError = error as BusinessError;
  2535. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2536. }
  2537. }
  2538. async showTips() {
  2539. try {
  2540. this.getUIContext().getPromptAction().showDialog({
  2541. title: '导入指南',
  2542. message:'用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2543. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2544. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2545. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后去文件扫描一下。\n',
  2546. buttons: [
  2547. {
  2548. text: '知道了',
  2549. color: '#000000'
  2550. },
  2551. ]
  2552. }, (err, data) => {
  2553. if (err) {
  2554. console.error('showDialog err: ' + err);
  2555. return;
  2556. }
  2557. console.info('showDialog success callback, click button: ' + data.index);
  2558. });
  2559. } catch (error) {
  2560. let message = (error as BusinessError).message;
  2561. let code = (error as BusinessError).code;
  2562. console.error(`showDialog args error code is ${code}, message is ${message}`);
  2563. };
  2564. // DialogHelper.showTipsDialog({
  2565. // title: '使用提示:自动导入教程',
  2566. //
  2567. // content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2568. // + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2569. // '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2570. // '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  2571. // onAction: (action) => {
  2572. // if (action == DialogAction.TWO) {
  2573. // PreferencesUtil.putSync('isFirstMusic', false)
  2574. // router.pushUrl({
  2575. // url: 'pages/ScanFilePage'
  2576. // });
  2577. // }
  2578. // }
  2579. // })
  2580. }
  2581. showMkDialog() {
  2582. DialogHelper.showTextInputDialog({
  2583. title: '新建歌单',
  2584. maskColor: Color.Transparent,
  2585. text: '',
  2586. transition: AnimationHelper.transitionInDown(666),
  2587. onChange: (text) => {
  2588. console.error("onChange: " + text);
  2589. },
  2590. onAction: (action, dialogId, content) => {
  2591. // ToastUtil.showToast('content = ' +content)
  2592. if (action == DialogAction.TWO) {
  2593. const newName = content
  2594. const newPath = this.currentPath + '/' + newName
  2595. FileUtil.mkdir(newPath, true).then(() => {
  2596. this.cache.delete(this.currentPath); // 删除目标路径缓存
  2597. this.getSortedFiles(this.currentPath)
  2598. }).catch((error: BusinessError) => {
  2599. console.error(error.message);
  2600. });
  2601. }
  2602. }
  2603. })
  2604. }
  2605. @State progress: number = 0;
  2606. async saveVideoDatas(uris:string[],isOpen?:boolean){
  2607. if (ArrayUtil.isEmpty(uris)) {
  2608. return;
  2609. }
  2610. console.info('onecold this.isCopyFileToDownLoad = ' + this.isCopyFileToDownLoad);
  2611. if(this.isCopyFileToDownLoad||this.currentPath==this.lockPath||isOpen){
  2612. this.saveVideoDatasToDownLoad(uris,isOpen)
  2613. return
  2614. }
  2615. // 初始化进度条
  2616. this.progress = 0;
  2617. DialogHelper.showLoadingProgress({
  2618. progress: this.progress,
  2619. backCancel: false,
  2620. autoCancel: false,
  2621. loadColor: $r('app.color.title_bar_bg'),
  2622. fontColor: $r('app.color.title_bar_bg')
  2623. });
  2624. // 计算处理总数用于进度计算
  2625. const totalItems = uris.length;
  2626. let processedItems = 0;
  2627. for (let i = 0; i < uris.length; i++) {
  2628. let filePath = uris[i];
  2629. try {
  2630. if (this.currentPath !== this.lockPath) { // 判断不是私密音乐,才入库
  2631. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2632. let mediaItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context,
  2633. filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2634. console.info('onecold saveVideoDatas filePath = ' + filePath)
  2635. if (!filePath.includes(this.rootPath)) {
  2636. console.info('onecold saveVideoDatas mediaItem.parentPath111 = ' + mediaItem.parentPath)
  2637. mediaItem.parentPath = this.currentPath;
  2638. }
  2639. console.info('onecold saveVideoDatas mediaItem.parentPath = ' + mediaItem.parentPath)
  2640. this.table.insert(mediaItem, (id: number) => {
  2641. // 插入完成回调
  2642. });
  2643. }
  2644. }
  2645. // 更新进度
  2646. processedItems++;
  2647. this.progress = Math.floor((processedItems / totalItems) * 100);
  2648. DialogHelper.updateLoading(' 正在处理', this.progress);
  2649. } catch (error) {
  2650. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2651. // 即使出错也更新进度
  2652. processedItems++;
  2653. this.progress = Math.floor((processedItems / totalItems) * 100);
  2654. DialogHelper.updateLoading(' 正在处理', this.progress);
  2655. }
  2656. }
  2657. // 关闭进度条
  2658. DialogHelper.closeLoading();
  2659. this.isZero = false
  2660. // 删除目标路径缓存
  2661. setTimeout(() => {
  2662. this.cache.delete(this.currentPath);
  2663. this.getSortedFiles(this.currentPath,false,uris[0],isOpen)
  2664. this.setButtonStatus()
  2665. }, 500);
  2666. }
  2667. async saveVideoDatasToDownLoad(uris: string[], isOpen?: boolean) {
  2668. if (ArrayUtil.isEmpty(uris)) {
  2669. return;
  2670. }
  2671. let newUris: string[] = [];
  2672. this.progress = 0
  2673. DialogHelper.showLoadingProgress({
  2674. progress: this.progress,
  2675. backCancel: false,
  2676. autoCancel: false,
  2677. loadColor: this.themeColor,
  2678. fontColor: this.themeColor
  2679. });
  2680. // 计算所有文件的总大小
  2681. let totalSize = 0;
  2682. for (let uri of uris) {
  2683. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  2684. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  2685. await fileIo.close(sourceFile.fd);
  2686. }
  2687. let totalRead = 0;
  2688. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  2689. Logger.info(TAG, 'destPath uri: ' + destPath);
  2690. for (let i = 0; i < uris.length; i++) {
  2691. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  2692. Logger.info(TAG, 'filePath uri: ' + filePath);
  2693. newUris.push(filePath);
  2694. try {
  2695. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  2696. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  2697. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  2698. const buffer = new ArrayBuffer(buffSize);
  2699. let len = await fileIo.read(sourceFile.fd, buffer);
  2700. while (len > 0) {
  2701. await fileIo.write(destFile.fd, buffer.slice(0, len));
  2702. totalRead += len;
  2703. // 计算总进度
  2704. this.progress = Math.floor((totalRead / totalSize) * 100);
  2705. DialogHelper.updateLoading('正在导入', this.progress);
  2706. len = await fileIo.read(sourceFile.fd, buffer);
  2707. }
  2708. await fileIo.close(sourceFile.fd);
  2709. await fileIo.close(destFile.fd);
  2710. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  2711. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2712. let mediaItem: VideoItem =
  2713. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2714. this.table.insert(mediaItem, (id: number) => {
  2715. // 删除目标路径缓存
  2716. this.cache.delete(this.currentPath);
  2717. this.getSortedFiles(this.currentPath, true, destPath, isOpen,mediaItem)
  2718. });
  2719. }
  2720. }
  2721. } catch (error) {
  2722. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2723. }
  2724. }
  2725. DialogHelper.closeLoading()
  2726. this.isZero = false
  2727. // setTimeout(() => {
  2728. // // 删除目标路径缓存
  2729. // this.cache.delete(this.currentPath);
  2730. // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
  2731. // }, 500);
  2732. Logger.info(TAG, 'scan select video result:' + newUris)
  2733. }
  2734. //拉起音频
  2735. // goSelectMusic(){
  2736. //
  2737. // try {
  2738. // let audioSelectOptions = new picker.AudioSelectOptions();
  2739. // let audioPicker = new picker.AudioViewPicker(this.context);
  2740. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  2741. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  2742. // this.saveVideoDatas(audioSelectResult)
  2743. // }
  2744. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  2745. // }).catch((err: BusinessError) => {
  2746. //
  2747. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  2748. // });
  2749. // } catch (error) {
  2750. // let err: BusinessError = error as BusinessError;
  2751. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2752. // }
  2753. //
  2754. //
  2755. //
  2756. // }
  2757. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  2758. if (!item) {
  2759. return undefined;
  2760. }
  2761. try {
  2762. let selectUris: Array<string> = [];
  2763. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  2764. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  2765. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  2766. photoSelectOptions.maxSelectNumber = 1;
  2767. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  2768. selectUris = photoSelectResult.photoUris;
  2769. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  2770. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  2771. console.info('file fd: ' + file.fd);
  2772. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  2773. let imagePath = this.context.filesDir + FileUtil.separator + name
  2774. imagePath = fileUri.getUriFromPath(imagePath)
  2775. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  2776. fileIo.copyFileSync(file.fd, file2.fd)
  2777. fileIo.closeSync(file);
  2778. fileIo.closeSync(file2);
  2779. if (item.filePath == this.currentSong?.filePath) {
  2780. this.cover = imagePath
  2781. }
  2782. if (item) {
  2783. item.pixelMapPath = imagePath
  2784. }
  2785. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  2786. if (success) {
  2787. this.doUpdateData()
  2788. console.log("onecold 更新音乐封面成功,数据库已同步");
  2789. } else {
  2790. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  2791. }
  2792. });
  2793. LogUtil.debug("onecold this.cover =" + this.cover)
  2794. return FileUtil.getFilePath(imagePath); // Return the image path here
  2795. } catch (err) {
  2796. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  2797. return undefined;
  2798. }
  2799. }
  2800. // 拉起picker选择文件管理器
  2801. async callFilePickerSelectFile(): Promise<void> {
  2802. try {
  2803. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  2804. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  2805. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  2806. } else {
  2807. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  2808. }
  2809. let documentPicker = new picker.DocumentViewPicker();
  2810. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  2811. Logger.info(TAG,
  2812. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  2813. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  2814. this.saveVideoDatas(DocumentSelectResult)
  2815. }
  2816. }).catch((err: BusinessError) => {
  2817. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  2818. });
  2819. } catch (err) {
  2820. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  2821. }
  2822. }
  2823. //重命名的对话框
  2824. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  2825. if(!item.filePath.includes(this.packName)){
  2826. ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限重命名')
  2827. return
  2828. }
  2829. DialogHelper.showTextInputDialog({
  2830. title: '重命名',
  2831. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  2832. maskColor: Color.Transparent,
  2833. backgroundColor: Color.Grey,
  2834. transition: AnimationHelper.transitionInDown(666),
  2835. onChange: (text) => {
  2836. console.error("onChange: " + text);
  2837. },
  2838. onAction: (action, dialogId, content) => {
  2839. // ToastUtil.showToast('content = ' +content)
  2840. if (action == DialogAction.TWO) {
  2841. const newName = content
  2842. const newPath = this.currentPath + '/' + newName
  2843. console.log("onecold item = " + item.type);
  2844. this.doReName(index, newName, filePath, newPath, item)
  2845. }
  2846. }
  2847. })
  2848. }
  2849. //剪切 移动到另个文件夹的对话框
  2850. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2851. Logger.info('onecold showCutDialog')
  2852. let mList: Array<string> = []
  2853. let rPath = this.rootPath
  2854. if (isCurrent) {
  2855. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2856. rPath = this.currentPath
  2857. } else {
  2858. mList = Utility.getNameList(this.dirList);
  2859. rPath = this.rootPath
  2860. }
  2861. let dataBean = new BubbleBean()
  2862. dataBean.data = mList
  2863. dataBean.color = this.themeColor
  2864. dataBean.onItemClick = (i) => {
  2865. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2866. Logger.info('newPath = ' + newPath)
  2867. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  2868. ToastUtil.showToast('移动成功')
  2869. this.table.deleteData(item, () => {
  2870. });
  2871. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2872. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2873. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2874. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2875. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2876. this.table.insert(newItem, (id: number) => {
  2877. //加入数据库
  2878. });
  2879. }
  2880. this.cache.delete(this.currentPath); // 删除原路径缓存
  2881. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2882. this.getSortedFiles(this.currentPath, true)
  2883. }).catch((error: BusinessError) => {
  2884. console.error(error.message);
  2885. });
  2886. XPopup.dismissTop()
  2887. }
  2888. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2889. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2890. popupPosition = PopupPosition.TOP
  2891. }
  2892. if (index <= 3) {
  2893. popupPosition = PopupPosition.BOTTOM
  2894. }
  2895. let pup: XPopup
  2896. if (this.isDarkMode) {
  2897. pup = XPopup.Builder()
  2898. .setPopupPosition(popupPosition)
  2899. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  2900. .setBackgroundColor(Color.Black)
  2901. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2902. .show()
  2903. } else {
  2904. pup = XPopup.Builder()
  2905. .setPopupPosition(popupPosition)
  2906. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  2907. .setBackgroundColor(Color.White)
  2908. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2909. .show()
  2910. }
  2911. }
  2912. //复制 到另个文件夹的对话框
  2913. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2914. Logger.info('onecoldv showCopyDialog')
  2915. let mList: Array<string> = []
  2916. let rPath = this.rootPath
  2917. if (isCurrent) {
  2918. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2919. rPath = this.currentPath
  2920. } else {
  2921. mList = Utility.getNameList(this.dirList);
  2922. rPath = this.rootPath
  2923. }
  2924. let dataBean = new BubbleBean()
  2925. dataBean.data = mList
  2926. dataBean.isCopy = true
  2927. dataBean.color = this.themeColor
  2928. dataBean.onItemClick = (i) => {
  2929. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2930. Logger.info('newPath = ' + newPath)
  2931. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2932. ToastUtil.showToast('复制成功')
  2933. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2934. this.getSortedFiles(this.currentPath)
  2935. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2936. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2937. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2938. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2939. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2940. this.table.insert(newItem, (id: number) => {
  2941. //加入数据库
  2942. });
  2943. }
  2944. }).catch((error: BusinessError) => {
  2945. console.error(error.message);
  2946. });
  2947. XPopup.dismissTop()
  2948. }
  2949. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2950. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2951. popupPosition = PopupPosition.TOP
  2952. }
  2953. if (index <= 3) {
  2954. popupPosition = PopupPosition.BOTTOM
  2955. }
  2956. let pup: XPopup
  2957. if (this.isDarkMode) {
  2958. pup = XPopup.Builder()
  2959. .setPopupPosition(popupPosition)
  2960. .atView(id)
  2961. .setMaxHeight('60%')
  2962. .setBackgroundColor(Color.Black)
  2963. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2964. .show();
  2965. } else {
  2966. pup = XPopup.Builder()
  2967. .setPopupPosition(popupPosition)
  2968. .atView(id)
  2969. .setMaxHeight('60%')
  2970. .setBackgroundColor(Color.White)
  2971. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2972. .show();
  2973. }
  2974. }
  2975. //重命名索引index的视频
  2976. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  2977. FileUtil.rename(oldPath, newPath).then(async () => {
  2978. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2979. if (info.type === CommonConstants.TYPE_IS_DIR) {
  2980. //如果是文件夹先删除源数据,再添加新数据
  2981. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  2982. if (success) {
  2983. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  2984. } else {
  2985. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  2986. }
  2987. });
  2988. this.scanDirectory(newPath)
  2989. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  2990. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  2991. if (success) {
  2992. console.log(" onecold 重命名成功,数据库已同步");
  2993. } else {
  2994. console.error(" onecold 重命名数据库失败原因: " + error);
  2995. }
  2996. });
  2997. }
  2998. let mediaItem: VideoItem =
  2999. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3000. this.videoLocalList[index] = mediaItem;
  3001. }
  3002. this.cache.delete(this.currentPath)
  3003. this.getSortedFiles(this.currentPath, true)
  3004. }).catch((error: BusinessError) => {
  3005. console.error(error.message);
  3006. });
  3007. }
  3008. build() {
  3009. Stack() {
  3010. this.ContentBuild()
  3011. Stack() {
  3012. Column()
  3013. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  3014. height: '95%',
  3015. dragBar: true,
  3016. showClose: true,
  3017. blurStyle: BlurStyle.Thin,
  3018. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3019. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  3020. title: {
  3021. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  3022. + `(${this.songList.length}首)`
  3023. }
  3024. })
  3025. }
  3026. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  3027. modalTransition: this.isCoverRectangle?ModalTransition.DEFAULT:ModalTransition.NONE,
  3028. transition: this.isCoverRectangle?null:AnimationHelper.transitionInDown(500),
  3029. onWillDisappear: () => {
  3030. this.setShowPlayFalse()
  3031. },
  3032. })
  3033. }
  3034. .alignContent(Alignment.Bottom)
  3035. .width('100%')
  3036. .height('100%')
  3037. }
  3038. @Builder
  3039. ContentBuild() {
  3040. Scroll() {
  3041. Column() {
  3042. Stack() {
  3043. //libraryname加上去后onKeyEvent监听不了,因为目前的解决方案是上面的XComponent,去掉libraryname
  3044. XComponent({ id: 'for_onKeyEvent',type: XComponentType.SURFACE,
  3045. controller: this.xcomponentController })
  3046. .onLoad(async (event?: object) => {
  3047. })
  3048. .focusable(true)
  3049. .height(0)
  3050. .focusOnTouch(true)
  3051. .defaultFocus(true) // 自动获取键盘焦点
  3052. .onKeyEvent((event?: KeyEvent) => {
  3053. console.info('onecold点击 onKeyEvent')
  3054. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  3055. if (!event || event.type !== KeyType.Down) {
  3056. return;
  3057. }
  3058. console.info('onecold点击 onKeyEvent event.keyCode: ' + event.keyCode)
  3059. //空格键 Space key controls pause/play
  3060. if (event.keyCode === KeyCode.KEYCODE_SPACE|| event.keyCode === KeyCode.KEYCODE_MEDIA_PLAY_PAUSE) {
  3061. this.playOrPause()
  3062. }
  3063. if (event.keyCode === KeyCode.KEYCODE_DPAD_UP) {
  3064. this.playPrevious()
  3065. }
  3066. if (event.keyCode === KeyCode.KEYCODE_DPAD_DOWN) {
  3067. this.playNext()
  3068. }
  3069. // Right-click to fast forward
  3070. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  3071. this.fastForward()
  3072. }
  3073. // Left-click to rewind
  3074. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  3075. this.backForward()
  3076. }
  3077. })
  3078. Column() {
  3079. XComponent({
  3080. id: 'xcomponentId',
  3081. type: 'surface',
  3082. libraryname: 'ijkplayer_napi',
  3083. controller: this.xcomponentController
  3084. })
  3085. .onLoad((event?: object) => {
  3086. if (!!event) {
  3087. this.initDelayPlay(event);
  3088. }
  3089. })
  3090. .onDestroy(() => {
  3091. })
  3092. .width('100%')// .width(this.videoWidth)
  3093. .aspectRatio(this.videoAspectRatio)
  3094. }
  3095. .aspectRatio(this.videoAspectRatio)
  3096. .justifyContent(FlexAlign.Center)
  3097. .backgroundColor(Color.Transparent)
  3098. .visibility(Visibility.Hidden)
  3099. .height(CommonConstants.FULL_PERCENT)
  3100. .width(CommonConstants.FULL_PERCENT)
  3101. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  3102. height:this.isLandscape?'80%': '43%',
  3103. dragBar: true,
  3104. showClose: true,
  3105. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3106. blurStyle:BlurStyle.Thin,
  3107. backgroundColor:Color.Transparent,
  3108. title: { title: 'AB循环' }
  3109. })
  3110. Stack() {
  3111. Column() {
  3112. if(this.twoFingerType==4){
  3113. this.getWaterView()
  3114. }else{
  3115. if(this.isGridMusic){
  3116. this.getGridView()
  3117. }else {
  3118. this.getList()
  3119. }
  3120. }
  3121. if (this.modeType ==0||this.modeType==4) {
  3122. Column() {
  3123. emptyView(this.themeColor)
  3124. }
  3125. .onClick(()=>{
  3126. this.asyncCurrentPathOnlyFile()
  3127. })
  3128. .position({ top: 200 })
  3129. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  3130. .animation({ duration: 500 }),
  3131. TransitionEffect.scale({ x: 0, y: 0 })))
  3132. .justifyContent(FlexAlign.Center)
  3133. .opacity(this.isZero ? 1 : 0)
  3134. .visibility(this.isZero && !this.isFavMusic && !this.isHistory
  3135. ? Visibility.Visible : Visibility.None)
  3136. .animation({
  3137. duration: 500,
  3138. curve: Curve.Friction // 可选动画曲线
  3139. })
  3140. .width('100%')
  3141. }
  3142. }
  3143. .layoutWeight(1)
  3144. .height('100%')
  3145. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  3146. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3147. .onDrop((event?: DragEvent) => {
  3148. try {
  3149. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3150. if (dragData !== undefined) {
  3151. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3152. if (records.length > 0) {
  3153. for (let i = 0; i < records.length; i++) {
  3154. let types = records[i].getTypes();
  3155. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3156. const fileUriUds =
  3157. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3158. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3159. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3160. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3161. this.targetFile = fileUriUds.oriUri;
  3162. this.saveVideoDatas([this.targetFile])
  3163. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3164. }
  3165. }
  3166. }
  3167. } else {
  3168. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3169. }
  3170. } else {
  3171. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3172. }
  3173. } catch (error) {
  3174. const err = error as BusinessError;
  3175. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3176. }
  3177. })
  3178. // 右侧居中的字母表索引
  3179. if(this.showZMIndex){
  3180. this.indexBuilder()
  3181. }
  3182. this.topTitleBar()
  3183. }
  3184. .alignContent(Alignment.Top)
  3185. .layoutWeight(1)
  3186. .height('100%')
  3187. Row() {
  3188. Button(this.isAllSelected ? '反选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  3189. .width(45)
  3190. .height(45)
  3191. .fontSize(10)
  3192. .margin({ top: 10, bottom: 10, right: 6 })
  3193. .backgroundColor(this.themeColor)
  3194. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3195. .onClick(() => {
  3196. if (this.isAllSelected) {
  3197. // 全不选
  3198. this.selectedFiles = [];
  3199. } else {
  3200. // 全选
  3201. this.selectedFiles = [...this.getCurFileList()];
  3202. }
  3203. this.isAllSelected = !this.isAllSelected;
  3204. })
  3205. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  3206. .width(72)
  3207. .height(45)
  3208. .fontSize(10)
  3209. .margin({ top: 10, bottom: 10, right: 6 })
  3210. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3211. .backgroundColor(this.themeColor)
  3212. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  3213. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3214. })
  3215. .onClick(() => {
  3216. // if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  3217. this.isOneKeyTags = !this.isOneKeyTags
  3218. // }else{
  3219. // ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限批量内嵌标签,导入的时候请勾选复制一份。')
  3220. // }
  3221. })
  3222. Button('合并', { type: ButtonType.Circle, stateEffect: true })
  3223. .width(45)
  3224. .height(45)
  3225. .fontSize(10)
  3226. .margin({ top: 10, bottom: 10, right: 6 })
  3227. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3228. .backgroundColor(this.themeColor)
  3229. .bindContentCover($$this.isMergeAudio, this.MergeAudioBuilder(), {
  3230. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3231. })
  3232. .onClick(() => {
  3233. if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  3234. this.isMergeAudio = !this.isMergeAudio
  3235. }else{
  3236. ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限合并')
  3237. }
  3238. })
  3239. Button('+歌单', { type: ButtonType.Circle, stateEffect: true })
  3240. .width(45)
  3241. .height(45)
  3242. .fontSize(10)
  3243. .margin({ top: 10, bottom: 10, right: 6 })
  3244. .backgroundColor(this.themeColor)
  3245. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3246. .onClick(async () => {
  3247. this.longItemFilePath = ''
  3248. await this.openAddToPlaylistDialog(this.selectedFiles)
  3249. })
  3250. // Button('乱码', { type: ButtonType.Circle, stateEffect: true })
  3251. // .width(45)
  3252. // .height(45)
  3253. // .fontSize(10)
  3254. // .margin({ top: 10, bottom: 10, right: 6 })
  3255. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3256. // .backgroundColor(this.themeColor)
  3257. // .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  3258. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3259. // })
  3260. // .onClick(() => {
  3261. // this.isFixMessy = !this.isFixMessy
  3262. // })
  3263. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  3264. // .width('35%')
  3265. // .height(60)
  3266. // .id('music_cut')
  3267. // .margin({ top: 10, bottom: 10, right: 6 })
  3268. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3269. // .backgroundColor(this.themeColor)
  3270. // .onClick(() => {
  3271. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  3272. // })
  3273. //
  3274. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  3275. // .width('35%')
  3276. // .height(60)
  3277. // .id('music_cut_current')
  3278. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  3279. // .margin({ top: 10, bottom: 10, right: 6 })
  3280. // .backgroundColor(this.themeColor)
  3281. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3282. // .onClick(() => {
  3283. //
  3284. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  3285. // })
  3286. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  3287. // .width('35%')
  3288. // .height(60)
  3289. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  3290. // .margin({ top: 10, bottom: 10, right: 6 })
  3291. // .backgroundColor(this.themeColor)
  3292. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3293. // .onClick(() => {
  3294. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  3295. // })
  3296. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  3297. .width(45)
  3298. .height(45)
  3299. .fontSize(10)
  3300. .margin({ top: 10, bottom: 10, right: 6 })
  3301. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  3302. .backgroundColor(this.themeColor)
  3303. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3304. .onClick(() => {
  3305. this.showWarnIsDelete()
  3306. })
  3307. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  3308. .width(45)
  3309. .height(45)
  3310. .fontSize(10)
  3311. .margin({ top: 10, bottom: 10, right: 6 })
  3312. .backgroundColor(this.themeColor)
  3313. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3314. .onClick(() => {
  3315. this.selectedFiles = [];
  3316. this.isAllSelected = false
  3317. this.isMultiSelect = false
  3318. })
  3319. }
  3320. .width('100%')
  3321. .justifyContent(FlexAlign.Center)
  3322. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  3323. .opacity(this.isMultiSelect ? 1 : 0)
  3324. .animation({
  3325. duration: 666,
  3326. curve: 'ease-in-out' // 可选动画曲线
  3327. })
  3328. .position({ bottom: 20 }) // 将 Row 固定在底部
  3329. }
  3330. .width('100%')
  3331. .height('100%')
  3332. .alignContent(Alignment.Top)
  3333. }
  3334. .width('100%')
  3335. .height('100%')
  3336. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  3337. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  3338. .backgroundImagePosition(Alignment.Center)
  3339. .backdropBlur(this.blurValue)
  3340. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  3341. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  3342. }
  3343. }
  3344. //字母表索引
  3345. @Builder
  3346. indexBuilder(){
  3347. if(this.enableShowAlphabet){
  3348. Column({space: 5}){
  3349. if(this.isShowAlphaBet&&!(this.modeType==2&&!this.isCanBack)
  3350. &&!(this.modeType==3&&!this.isCanBack)){
  3351. AlphabetIndexer({arrayValue: this.alphaBet,selected: this.selectAlphaBetIndex})
  3352. .attributeModifier(this.alphaBetStyle)
  3353. .usingPopup(this.isTouchingAlphaBet)
  3354. .onAreaChange((old_value,new_value)=>{
  3355. this.alphabetHeight = new_value.height as number
  3356. })
  3357. .popupPosition({
  3358. x: 40,
  3359. y: this.alphabetHeight / 2
  3360. })
  3361. .onSelect((index: number) => {
  3362. this.onSelectIndexItem(this.alphaBet[index])
  3363. })
  3364. .onTouch((event: TouchEvent) =>{
  3365. this.isShowAlphaBet = true
  3366. if(event.type === TouchType.Up || event.type === TouchType.Cancel){
  3367. this.isTouchingAlphaBet = false
  3368. }else{
  3369. this.isTouchingAlphaBet = true
  3370. }
  3371. })
  3372. .transition(
  3373. TransitionEffect.translate({x: 10})
  3374. .combine(TransitionEffect.opacity(0.1))
  3375. .animation({
  3376. duration: 150,
  3377. curve: Curve.EaseInOut,
  3378. })
  3379. )
  3380. }else{
  3381. Blank()
  3382. .layoutWeight(1)
  3383. }
  3384. // ListLocateButton()
  3385. // .onClick(() =>{
  3386. // this.locateSong()
  3387. // })
  3388. // .clickEffect({level:ClickEffectLevel.LIGHT,scale: 0.5})
  3389. // .margin({
  3390. // bottom: 10
  3391. // })
  3392. }
  3393. .padding({
  3394. bottom: 0
  3395. })
  3396. .position({x:'92%'})
  3397. .height('100%')
  3398. .justifyContent(FlexAlign.Center)
  3399. }
  3400. }
  3401. onSelectIndexItem(letter: string) {
  3402. let songs = this.videoLocalList
  3403. let targetIndex = -1;
  3404. for (let i = 0; i < songs.length; i++) {
  3405. let song = songs[i]
  3406. let text = this.isShowFileName?song.fileName:
  3407. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  3408. if(this.sortType === 0||this.sortType==1){
  3409. text = song.artist
  3410. }else if(this.sortType === 2||this.sortType==3){
  3411. text = song.album
  3412. }
  3413. if(text){
  3414. let firstPinyin = getFirstLetter(text)
  3415. if (firstPinyin&&firstPinyin === letter) {
  3416. targetIndex = i;
  3417. break;
  3418. }
  3419. }
  3420. }
  3421. if (targetIndex !== -1) {
  3422. this.listScroller.scrollToIndex(targetIndex);
  3423. }
  3424. }
  3425. // 找到对应字母表的索引
  3426. findAlphaBetIndex(song: VideoItem):number{
  3427. let text = this.isShowFileName?song.fileName:
  3428. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  3429. if(this.sortType === 0||this.sortType==1){
  3430. text = song.artist
  3431. }else if(this.sortType === 2||this.sortType==3){
  3432. text = song.album
  3433. }
  3434. if(text){
  3435. let firstLetter = getFirstLetter(text)
  3436. for(let i=0;i<this.alphaBet.length;i++){
  3437. if(this.alphaBet[i] === firstLetter){
  3438. return i
  3439. }
  3440. }
  3441. }
  3442. return 0
  3443. }
  3444. async setAlphaBet(){
  3445. if(!this.showZMIndex){
  3446. return
  3447. }
  3448. return new Promise<void>((resolve,reject) => {
  3449. try {
  3450. let songs = this.videoLocalList
  3451. if(songs.length > 40000){
  3452. this.alphaBet = []
  3453. resolve()
  3454. return
  3455. }
  3456. let alphabetSet = new Set<string>();
  3457. for (let song of songs) {
  3458. let text = this.isShowFileName?song.fileName:
  3459. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  3460. if(this.sortType === 0||this.sortType==1){
  3461. text = song.artist
  3462. }else if(this.sortType === 2||this.sortType==3){
  3463. text = song.album
  3464. }
  3465. if(text){
  3466. let firstPinyin = getFirstLetter(text)
  3467. if(!alphabetSet.has(firstPinyin)){
  3468. alphabetSet.add(firstPinyin)
  3469. }
  3470. }
  3471. // const pyStr = song.pyStr
  3472. // if(pyStr){
  3473. // if(!alphabetSet.has(pyStr)){
  3474. // alphabetSet.add(pyStr)
  3475. // }
  3476. // }
  3477. }
  3478. this.alphaBet = Array.from(alphabetSet).sort((a,b)=>{
  3479. if(this.sortType ===4||this.sortType==0||this.sortType==2||this.sortType==6){
  3480. return a.localeCompare(b)
  3481. }else{
  3482. return b.localeCompare(a)
  3483. }
  3484. })
  3485. if(this.videoLocalList.length > 0){
  3486. this.listScroller.scrollToIndex(0)
  3487. this.selectAlphaBetIndex = 0
  3488. }
  3489. resolve()
  3490. }catch (e) {
  3491. console.error('testTag','排序字母表出错',JSON.stringify(e))
  3492. resolve()
  3493. }
  3494. })
  3495. }
  3496. @Builder
  3497. topTitleBar(){
  3498. Column() {
  3499. Row({ space: 15 }) {
  3500. if (!this.isSearchMode ) {
  3501. //左侧滑动按钮
  3502. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3503. SymbolGlyph(this.rightTopImage)
  3504. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3505. }
  3506. .attributeModifier(new ButtonFancyModifier(40, 40))
  3507. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3508. .animation({ duration: 300, curve: Curve.Ease })
  3509. .onClick(() => {
  3510. this.doSwipBack()
  3511. })
  3512. .attributeModifier(new ShadowModifier())
  3513. .zIndex(0)
  3514. }else{
  3515. //左侧搜索返回按钮
  3516. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3517. SymbolGlyph($r('sys.symbol.chevron_left'))
  3518. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3519. }
  3520. .attributeModifier(new ButtonFancyModifier(40, 40))
  3521. .margin({bottom:5})
  3522. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3523. .animation({ duration: 300, curve: Curve.Ease })
  3524. .onClick(() => {
  3525. this.isSearchMode = false
  3526. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  3527. this.searchText = ''
  3528. this.getSortedFiles(this.currentPath)
  3529. return
  3530. }
  3531. this.onSearchInput('')
  3532. })
  3533. .attributeModifier(new ShadowModifier())
  3534. .zIndex(0)
  3535. }
  3536. if (!this.isSearchMode) {
  3537. Text(this.modeType==1?`${this.titleName}(${this.mediaKuCount}首)`:this.titleName)
  3538. .margin({left:3,right:10})
  3539. .fontColor($r('app.color.text_color'))
  3540. .fontSize(this.twoFingerType==3?17:16)
  3541. .maxLines(1)
  3542. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3543. .layoutWeight(1)
  3544. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3545. }
  3546. //搜索框
  3547. Search({ controller: this.searchController,value: this.searchText, placeholder: '搜索标题、艺术家...' })
  3548. .searchButton('搜索',{fontColor:this.themeColor})
  3549. .searchIcon({
  3550. src: $r('sys.media.ohos_ic_public_search_filled')
  3551. })
  3552. .cancelButton({
  3553. style: CancelButtonStyle.CONSTANT,
  3554. icon: {
  3555. src: $r('sys.media.ohos_ic_public_cancel_filled')
  3556. }
  3557. })
  3558. .layoutWeight(1)
  3559. .height(40)
  3560. .maxLength(20)
  3561. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  3562. .placeholderColor(Color.Grey)
  3563. .placeholderFont({ size: 14, weight: 400 })
  3564. .textFont({ size: 14, weight: 400 })
  3565. .onSubmit((value: string) => {
  3566. console.log('onecold onSubmit ='+value)
  3567. this.searchController.stopEditing()
  3568. this.onSearchInput(this.searchText);
  3569. })
  3570. .onChange((value: string) => {
  3571. console.log('onecold onChange ='+value)
  3572. this.onSearchInput(value);
  3573. })
  3574. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  3575. .animation({ duration: 300, curve: Curve.Ease })
  3576. //搜索按钮
  3577. if (!this.isSearchMode) {
  3578. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3579. SymbolGlyph($r('sys.symbol.magnifyingglass'))
  3580. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3581. }
  3582. .attributeModifier(new ButtonFancyModifier(40, 40))
  3583. .animation({ duration: 300, curve: Curve.Ease })
  3584. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3585. .attributeModifier(new ShadowModifier())
  3586. .zIndex(0)
  3587. .onClick(()=>{
  3588. this.isSearchMode = true
  3589. })
  3590. //排序按钮
  3591. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3592. SymbolGlyph($r('sys.symbol.list_number'))
  3593. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3594. }
  3595. .attributeModifier(new ButtonFancyModifier(40, 40))
  3596. .animation({ duration: 300, curve: Curve.Ease })
  3597. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3598. .bindMenu((this.modeType==2&&!this.isCanBack)||(this.modeType==3&&!this.isCanBack)
  3599. ?this.SortMenuForArtistAblumBuilder:this.SortMenuBuilder)
  3600. .attributeModifier(new ShadowModifier())
  3601. .zIndex(0)
  3602. //添加按钮
  3603. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3604. SymbolGlyph($r('sys.symbol.plus'))
  3605. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3606. }
  3607. .attributeModifier(new ButtonFancyModifier(40, 40))
  3608. .animation({ duration: 300, curve: Curve.Ease })
  3609. .visibility(this.modeType==0||this.modeType==1?Visibility.Visible:Visibility.None)
  3610. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3611. .bindSheet($$this.showAddSheet, this.addSheet(), {
  3612. height: SheetSize.FIT_CONTENT,
  3613. dragBar: true,
  3614. showClose: true,
  3615. preferType: SheetType.CENTER ,
  3616. title: {
  3617. title: '导入音乐'
  3618. }
  3619. })
  3620. .onClick(() => {
  3621. this.showAddSheet = !this.showAddSheet;
  3622. })
  3623. .attributeModifier(new ShadowModifier())
  3624. .zIndex(0)
  3625. }
  3626. }
  3627. }
  3628. .padding({ top: this.topSafeHeight+10, left: 10, right: 10 })
  3629. .width('100%')
  3630. .visibility(this.isShowTitleBar?Visibility.Visible:
  3631. this.autoHideTitle?Visibility.None:Visibility.Visible)
  3632. .animation({
  3633. duration: 500,
  3634. curve: Curve.Friction // 可选动画曲线
  3635. })
  3636. }
  3637. @Builder
  3638. addSheet() {
  3639. Scroll() {
  3640. Column() {
  3641. Column() {
  3642. Row() {
  3643. Text('导入音乐复制到DownLoad目录')
  3644. .margin({ left: 18 })
  3645. .fontSize(14)
  3646. .fontColor($r('app.color.text_color'))
  3647. .fontWeight(480)
  3648. .layoutWeight(1)
  3649. Toggle({ type: ToggleType.Switch, isOn: this.isCopyFileToDownLoad })
  3650. .selectedColor(this.themeColor)
  3651. .switchPointColor(Color.White)
  3652. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  3653. .margin({ right: 18 })
  3654. .onChange((checked: boolean) => {
  3655. this.isCopyFileToDownLoad = checked;
  3656. PreferencesUtil.put(SettingPage.IS_COPYFILE_TO_DOWNLOAD, this.isCopyFileToDownLoad)
  3657. })
  3658. .width(50)
  3659. .height(30);
  3660. }
  3661. .height(88)
  3662. }
  3663. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3664. .backgroundColor($r('app.color.start_window_background'))
  3665. .borderRadius(15)
  3666. .margin({
  3667. left: 30,
  3668. right: 30,
  3669. top: 10,
  3670. bottom: 10
  3671. })
  3672. .padding(0)
  3673. .border({
  3674. color: Color.White,
  3675. width: 1.8
  3676. })
  3677. Menu() {
  3678. MenuItem({
  3679. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder_badge_plus')),
  3680. content: "新建文件夹"
  3681. })
  3682. .backgroundColor($r('app.color.silvery'))
  3683. .border({
  3684. width: { bottom: 1 },
  3685. color: '#12ec5c87'
  3686. })
  3687. .margin(10)
  3688. .padding({left:15,right:15})
  3689. .onClick(async () => {
  3690. this.showMkDialog()
  3691. this.showAddSheet = !this.showAddSheet
  3692. })
  3693. MenuItem({
  3694. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder')),
  3695. content: $r('app.string.import_from_files')
  3696. })
  3697. .padding({left:15,right:15})
  3698. .backgroundColor($r('app.color.silvery'))
  3699. .border({
  3700. width: { bottom: 1 },
  3701. color: '#12ec5c87'
  3702. })
  3703. .margin(10)
  3704. .onClick(async () => {
  3705. this.callFilePickerSelectFile()
  3706. this.showAddSheet = !this.showAddSheet
  3707. })
  3708. MenuItem({
  3709. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square')),
  3710. content: '全选导入'
  3711. // content: '从下载文件夹导入(路径:Download/' +
  3712. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  3713. })
  3714. .padding({left:15,right:15})
  3715. .backgroundColor($r('app.color.silvery'))
  3716. .border({
  3717. width: { bottom: 1 },
  3718. color: '#12ec5c87'
  3719. })
  3720. .margin(10)
  3721. .onClick(async () => {
  3722. this.goSelectMusic()
  3723. this.showAddSheet = !this.showAddSheet
  3724. })
  3725. MenuItem({
  3726. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.save')),
  3727. content: '自动导入教程'
  3728. // content: '从下载文件夹导入(路径:Download/' +
  3729. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  3730. })
  3731. .padding({left:15,right:15})
  3732. .backgroundColor($r('app.color.silvery'))
  3733. .border({
  3734. width: { bottom: 1 },
  3735. color: '#12ec5c87'
  3736. })
  3737. .margin(10)
  3738. .onClick(async () => {
  3739. this.showTips()
  3740. this.showAddSheet = !this.showAddSheet
  3741. })
  3742. }.attributeModifier(new MenuModifier())
  3743. .margin({bottom:30})
  3744. }
  3745. .layoutWeight(1)
  3746. }
  3747. }
  3748. @Builder
  3749. TagsContentCoverBuilder() {
  3750. Scroll() {
  3751. Column() {
  3752. TagsContentCover(
  3753. {
  3754. selectedFiles:this.selectedFiles,
  3755. isOneKeyTags:this.isOneKeyTags,
  3756. onSeePath:(path:string)=>{
  3757. this.modeType = 0
  3758. this.deleteCache(path)
  3759. this.getSortedFiles(path)
  3760. },
  3761. onTagsResult:(result: boolean,deleteCache_path?:string)=>{
  3762. this.isMultiSelect = false
  3763. if(result){//如果嵌入成功,更新数据
  3764. this.listRefreshKey++
  3765. setTimeout(()=>{
  3766. this.doUpdateData()
  3767. },500)
  3768. }
  3769. console.info('onecold onTagsResult deleteCache_path =' +deleteCache_path)
  3770. if(deleteCache_path){
  3771. this.deleteCache(deleteCache_path)
  3772. }
  3773. }
  3774. }
  3775. )
  3776. }
  3777. }
  3778. .width('100%')
  3779. .height('100%')
  3780. }
  3781. @Builder
  3782. FixMessyViewBuilder() {
  3783. Scroll() {
  3784. Column() {
  3785. FixMessyView(
  3786. {
  3787. selectedFiles:this.selectedFiles,
  3788. isFixMessy:this.isFixMessy,
  3789. onFixResult:(result: boolean)=>{
  3790. this.isMultiSelect = false
  3791. if(result){//如果嵌入成功,更新数据
  3792. this.deleteCache(this.currentPath)
  3793. this.doUpdateData()
  3794. }
  3795. }
  3796. }
  3797. )
  3798. }
  3799. }
  3800. .width('100%')
  3801. .height('100%')
  3802. }
  3803. //剪辑音频
  3804. @Builder
  3805. EditAudioBuilder(item:VideoItem) {
  3806. Scroll() {
  3807. Column() {
  3808. EditAudio(
  3809. {
  3810. mVideoItem:item,
  3811. currentPath:this.currentPath,
  3812. videoUrl:this.videoUrl,
  3813. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3814. currentTime:this.currentTime,
  3815. progressValue:this.progressValue,
  3816. onBack:()=>{
  3817. this.isEditAudio = !this.isEditAudio
  3818. },
  3819. onSeeOutputPath:(outPutPath:string)=>{
  3820. this.isEditAudio = !this.isEditAudio
  3821. this.longItemFilePath = ''
  3822. this.modeType = 0
  3823. this.isShowFileName = true
  3824. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3825. },
  3826. onPlayOrPause:()=>{
  3827. if(this.videoUrl==item.filePath){
  3828. this.playOrPause()
  3829. }else{//如果不是当前播放的,则播放该文件
  3830. this.videoUrl==item.filePath
  3831. this.doPlay(item,0,false,true)
  3832. }
  3833. },
  3834. onSliderChange:(value:number)=>{
  3835. if(this.videoUrl!=item.filePath){
  3836. this.videoUrl==item.filePath
  3837. return
  3838. }
  3839. this.isSeekTo = true;
  3840. this.mDestroyPage = false;
  3841. this.showLoadIng();
  3842. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  3843. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3844. this.seekTo(seekValue + "");
  3845. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  3846. this.isSeekTo = false;
  3847. },
  3848. onResult:(result: boolean,outPath:string)=>{
  3849. if(result){//如果剪辑成功,更新数据
  3850. this.doUpdateData()
  3851. }else{
  3852. ToastUtil.showToast('剪辑失败')
  3853. }
  3854. }
  3855. }
  3856. )
  3857. }
  3858. }
  3859. .width('100%')
  3860. .height('100%')
  3861. }
  3862. //提取伴奏
  3863. @Builder
  3864. ConverterBuilder(item:VideoItem) {
  3865. Scroll() {
  3866. Column() {
  3867. AudioFormatConverter(
  3868. {
  3869. mVideoItem:item,
  3870. videoUrl:this.videoUrl,
  3871. currentPath:this.currentPath,
  3872. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3873. currentTime:this.currentTime,
  3874. progressValue:this.progressValue,
  3875. onBack:()=>{
  3876. this.isConverter = !this.isConverter
  3877. this.longItemFilePath = ''
  3878. },
  3879. onPlayOrPause:()=>{
  3880. if(this.videoUrl==item.filePath){
  3881. this.playOrPause()
  3882. }else{//如果不是当前播放的,则播放该文件
  3883. this.videoUrl==item.filePath
  3884. this.doPlay(item,0,false,true)
  3885. }
  3886. },
  3887. onSeeOutputPath:(outPutPath:string)=>{
  3888. this.isConverter = !this.isConverter
  3889. this.longItemFilePath = ''
  3890. this.modeType = 0
  3891. this.isShowFileName = true
  3892. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3893. },
  3894. onSliderChange:(value:number)=>{
  3895. if(this.videoUrl!=item.filePath){
  3896. this.videoUrl==item.filePath
  3897. return
  3898. }
  3899. this.isSeekTo = true;
  3900. this.mDestroyPage = false;
  3901. this.showLoadIng();
  3902. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3903. this.seekTo(seekValue + "");
  3904. this.isSeekTo = false;
  3905. },
  3906. onResult:(result: boolean,outPath:string)=>{
  3907. if(result){//如果成功,更新数据
  3908. this.doUpdateData()
  3909. }else{
  3910. ToastUtil.showToast('格式转化失败')
  3911. }
  3912. }
  3913. }
  3914. )
  3915. }
  3916. }
  3917. .width('100%')
  3918. .height('100%')
  3919. }
  3920. //提取伴奏
  3921. @Builder
  3922. ExtractAccBuilder(item:VideoItem) {
  3923. Scroll() {
  3924. Column() {
  3925. ExtractAccompaniment(
  3926. {
  3927. mVideoItem:item,
  3928. currentPath:this.currentPath,
  3929. videoUrl:this.videoUrl,
  3930. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3931. currentTime:this.currentTime,
  3932. progressValue:this.progressValue,
  3933. onBack:()=>{
  3934. this.isExtractAcc = !this.isExtractAcc
  3935. this.longItemFilePath = ''
  3936. },
  3937. onPlayOrPause:()=>{
  3938. if(this.videoUrl==item.filePath){
  3939. this.playOrPause()
  3940. }else{//如果不是当前播放的,则播放该文件
  3941. this.videoUrl==item.filePath
  3942. this.doPlay(item,0,false,true)
  3943. }
  3944. },
  3945. onSeeOutputPath:(outPutPath:string)=>{
  3946. this.isExtractAcc = !this.isExtractAcc
  3947. this.longItemFilePath = ''
  3948. this.modeType = 0
  3949. this.isShowFileName = true
  3950. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3951. },
  3952. onSliderChange:(value:number)=>{
  3953. if(this.videoUrl!=item.filePath){
  3954. this.videoUrl==item.filePath
  3955. return
  3956. }
  3957. this.isSeekTo = true;
  3958. this.mDestroyPage = false;
  3959. this.showLoadIng();
  3960. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3961. this.seekTo(seekValue + "");
  3962. this.isSeekTo = false;
  3963. },
  3964. onResult:(result: boolean,outPath:string)=>{
  3965. if(result){//如果成功,更新数据
  3966. this.doUpdateData()
  3967. }else{
  3968. ToastUtil.showToast('提取伴奏失败')
  3969. }
  3970. }
  3971. }
  3972. )
  3973. }
  3974. }
  3975. .width('100%')
  3976. .height('100%')
  3977. }
  3978. //AI人声分离
  3979. @Builder
  3980. AiBuilder(item:VideoItem) {
  3981. Scroll() {
  3982. Column() {
  3983. AIVoiceSeparation(
  3984. {
  3985. mVideoItem:item,
  3986. videoUrl:this.videoUrl,
  3987. currentPath:this.currentPath,
  3988. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3989. currentTime:this.currentTime,
  3990. progressValue:this.progressValue,
  3991. onBack:()=>{
  3992. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  3993. this.longItemFilePath = ''
  3994. },
  3995. onPlayOrPause:()=>{
  3996. if(this.videoUrl==item.filePath||this.isPlaying){
  3997. this.playOrPause()
  3998. }else{//如果不是当前播放的,则播放该文件
  3999. this.videoUrl==item.filePath
  4000. this.doPlay(item,0,false,true)
  4001. }
  4002. },
  4003. onPlayPath:(path:string)=>{
  4004. this.videoUrl==path
  4005. const itemP = Utility.getItemByFilePath(this.videoLocalList,path)
  4006. if(itemP)
  4007. this.doPlay(itemP,0,false,true)
  4008. },
  4009. onSeeOutputPath:(outPutPath:string)=>{
  4010. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  4011. this.longItemFilePath = ''
  4012. this.modeType = 0
  4013. this.isShowFileName = true
  4014. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4015. },
  4016. onSliderChange:(value:number)=>{
  4017. if(this.videoUrl!=item.filePath){
  4018. this.videoUrl==item.filePath
  4019. return
  4020. }
  4021. this.isSeekTo = true;
  4022. this.mDestroyPage = false;
  4023. this.showLoadIng();
  4024. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  4025. this.seekTo(seekValue + "");
  4026. this.isSeekTo = false;
  4027. },
  4028. onResult:(result: boolean,outPath:string)=>{
  4029. if(result){//如果成功,更新数据
  4030. this.doUpdateData()
  4031. }else{
  4032. ToastUtil.showToast('Ai人声分离失败')
  4033. }
  4034. }
  4035. }
  4036. )
  4037. }
  4038. }
  4039. .width('100%')
  4040. .height('100%')
  4041. }
  4042. //变速变调
  4043. @Builder
  4044. ChangeToneBuilder(item:VideoItem) {
  4045. Scroll() {
  4046. Column() {
  4047. ChangeTone(
  4048. {
  4049. mVideoItem:item,
  4050. currentPath:this.currentPath,
  4051. videoUrl:this.videoUrl,
  4052. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4053. currentTime:this.currentTime,
  4054. progressValue:this.progressValue,
  4055. onBack:()=>{
  4056. this.isChangeTone = !this.isChangeTone
  4057. this.longItemFilePath = ''
  4058. },
  4059. onPlayOrPause:()=>{
  4060. if(this.videoUrl==item.filePath){
  4061. this.playOrPause()
  4062. }else{//如果不是当前播放的,则播放该文件
  4063. this.videoUrl==item.filePath
  4064. this.doPlay(item,0,false,true)
  4065. }
  4066. },
  4067. onSeeOutputPath:(outPutPath:string)=>{
  4068. this.isChangeTone = !this.isChangeTone
  4069. this.longItemFilePath = ''
  4070. this.modeType = 0
  4071. this.isShowFileName = true
  4072. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4073. },
  4074. onSliderChange:(value:number)=>{
  4075. if(this.videoUrl!=item.filePath){
  4076. this.videoUrl==item.filePath
  4077. return
  4078. }
  4079. this.isSeekTo = true;
  4080. this.mDestroyPage = false;
  4081. this.showLoadIng();
  4082. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  4083. this.seekTo(seekValue + "");
  4084. this.isSeekTo = false;
  4085. },
  4086. onResult:(result: boolean,outPath:string)=>{
  4087. if(result){//如果成功,更新数据
  4088. this.doUpdateData()
  4089. }else{
  4090. ToastUtil.showToast('变速变调失败')
  4091. }
  4092. }
  4093. }
  4094. )
  4095. }
  4096. }
  4097. .width('100%')
  4098. .height('100%')
  4099. }
  4100. //提取视频中的音频
  4101. @Builder
  4102. extractAudioFromVideoBuilder(item:VideoItem) {
  4103. Scroll() {
  4104. Column() {
  4105. ExtractAudioFromVideo(
  4106. {
  4107. mVideoItem:item,
  4108. currentPath:this.currentPath,
  4109. videoUrl:this.videoUrl,
  4110. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4111. currentTime:this.currentTime,
  4112. progressValue:this.progressValue,
  4113. onBack:()=>{
  4114. this.isExtractAudio = !this.isExtractAudio
  4115. this.longItemFilePath = ''
  4116. },
  4117. onPlayOrPause:()=>{
  4118. if(this.videoUrl==item.filePath){
  4119. this.playOrPause()
  4120. }else{//如果不是当前播放的,则播放该文件
  4121. this.videoUrl==item.filePath
  4122. this.doPlay(item,0,false,true)
  4123. }
  4124. },
  4125. onSeeOutputPath:(outPutPath:string)=>{
  4126. this.isExtractAudio = !this.isExtractAudio
  4127. this.longItemFilePath = ''
  4128. this.modeType = 0
  4129. this.isShowFileName = true
  4130. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4131. },
  4132. onSliderChange:(value:number)=>{
  4133. if(this.videoUrl!=item.filePath){
  4134. this.videoUrl==item.filePath
  4135. return
  4136. }
  4137. this.isSeekTo = true;
  4138. this.mDestroyPage = false;
  4139. this.showLoadIng();
  4140. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  4141. this.seekTo(seekValue + "");
  4142. this.isSeekTo = false;
  4143. },
  4144. onResult:(result: boolean,outPath:string)=>{
  4145. if(result){//如果成功,更新数据
  4146. this.doUpdateData()
  4147. }else{
  4148. ToastUtil.showToast('提取音频失败')
  4149. }
  4150. }
  4151. }
  4152. )
  4153. }
  4154. }
  4155. .width('100%')
  4156. .height('100%')
  4157. }
  4158. //合并音频
  4159. @Builder
  4160. MergeAudioBuilder() {
  4161. Scroll() {
  4162. Column() {
  4163. MergeAudio(
  4164. {
  4165. videoUrl:this.videoUrl,
  4166. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4167. currentPath:this.currentPath,
  4168. selectedFiles:this.selectedFiles,
  4169. currentTime:this.currentTime,
  4170. progressValue:this.progressValue,
  4171. onBack:()=>{
  4172. this.isMergeAudio = !this.isMergeAudio
  4173. this.longItemFilePath = ''
  4174. },
  4175. // onPlayPath:(path:string)=>{
  4176. // if(this.videoUrl==item.filePath){
  4177. // this.playOrPause()
  4178. // }else{//如果不是当前播放的,则播放该文件
  4179. // this.videoUrl==item.filePath
  4180. // this.doPlay(item,0,false,true)
  4181. // }
  4182. //
  4183. // },
  4184. onSeeOutputPath:(outPutPath:string)=>{
  4185. this.isMergeAudio = !this.isMergeAudio
  4186. this.longItemFilePath = ''
  4187. this.modeType = 0
  4188. this.isShowFileName = true
  4189. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4190. },
  4191. onResult:(result: boolean,outPath:string)=>{
  4192. if(result){//如果成功,更新数据
  4193. this.doUpdateData()
  4194. }else{
  4195. if(this.selectedFiles.length>=3){
  4196. ToastUtil.showToast('合并数量太多导致失败')
  4197. }else{
  4198. ToastUtil.showToast('合并失败')
  4199. }
  4200. }
  4201. }
  4202. }
  4203. )
  4204. }
  4205. }
  4206. .width('100%')
  4207. .height('100%')
  4208. }
  4209. asyncCurrentPathData() {
  4210. if (this.modeType == 0) {
  4211. workerInstance.postMessage({
  4212. code: 1,
  4213. data1: this.context,
  4214. data2: this.currentPath,
  4215. data3: this.lockPath,
  4216. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  4217. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  4218. });
  4219. }
  4220. }
  4221. // 处理文件选择的函数
  4222. handleFileSelection(item: VideoItem, checked: boolean) {
  4223. if (checked) {
  4224. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  4225. this.selectedFiles.push(item);
  4226. }
  4227. } else {
  4228. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  4229. if (index > -1) {
  4230. this.selectedFiles.splice(index, 1);
  4231. }
  4232. }
  4233. }
  4234. private deleteComponentId: number = 0
  4235. //多选删除文件
  4236. showWarnIsDelete(){
  4237. this.getUIContext().getPromptAction().openCustomDialog({
  4238. builder: () => {
  4239. this.deleteComptentBuilder()
  4240. },
  4241. isModal:true,
  4242. showInSubWindow:false,
  4243. maskColor: Color.Transparent,
  4244. dialogTransition: // 设置弹窗内容显示的过渡效果
  4245. TransitionEffect.translate({ x: 0, y: 290, z: 0 })
  4246. .animation({ duration: 600, curve: Curve.Smooth }),
  4247. maskTransition: // 设置蒙层显示的过渡效果
  4248. TransitionEffect.opacity(0)
  4249. .animation({ duration: 600, curve: Curve.Smooth })
  4250. }).then((dialogId: number) => {
  4251. this.deleteComponentId = dialogId
  4252. })
  4253. .catch((error: BusinessError) => {
  4254. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  4255. })
  4256. }
  4257. @Builder
  4258. deleteComptentBuilder(){
  4259. DeleteComptent({
  4260. selectedFiles:this.selectedFiles,
  4261. onCancel:()=>{
  4262. this.isMultiSelect = false
  4263. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  4264. },
  4265. onDeleteResult:(result: boolean)=>{
  4266. this.isMultiSelect = false
  4267. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  4268. if(result){//如果删除成功,更新数据
  4269. this.selectedFiles = [];
  4270. this.isAllSelected = false
  4271. this.cache.delete(this.currentPath);
  4272. this.getSortedFiles(this.currentPath, true);
  4273. }
  4274. }
  4275. })
  4276. }
  4277. //多选移动文件
  4278. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  4279. Logger.info('onecold showCutDialogForMultipleFiles')
  4280. let mList: Array<string> = []
  4281. let rPath = this.rootPath
  4282. if (isCurrent) {
  4283. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  4284. rPath = this.currentPath
  4285. } else {
  4286. mList = Utility.getNameList(this.dirList);
  4287. rPath = this.rootPath
  4288. }
  4289. let dataBean = new BubbleBean();
  4290. dataBean.data = mList;
  4291. dataBean.color = this.themeColor
  4292. dataBean.onItemClick = (i) => {
  4293. const newDirPath = rPath + '/' + mList[i];
  4294. // Logger.info('newDirPath = ' + newDirPath)
  4295. this.selectedFiles.forEach((item) => {
  4296. const newPath = newDirPath + '/' + item.fileName;
  4297. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  4298. ToastUtil.showToast('移动成功');
  4299. this.table.deleteData(item, () => {
  4300. this.cache.delete(this.currentPath); // 删除原路径缓存
  4301. this.cache.delete(newDirPath); // 删除目标路径缓存
  4302. this.getSortedFiles(this.currentPath, true);
  4303. });
  4304. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  4305. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  4306. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  4307. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  4308. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  4309. this.table.insert(newItem, (id: number) => {
  4310. //加入数据库
  4311. });
  4312. }
  4313. }).catch((error: Error) => {
  4314. console.error(error.message);
  4315. });
  4316. });
  4317. this.isMultiSelect = false
  4318. this.selectedFiles = [];
  4319. this.isAllSelected = false
  4320. XPopup.dismissTop();
  4321. };
  4322. let pup: XPopup
  4323. if (this.isDarkMode) {
  4324. pup = XPopup.Builder()
  4325. .setPopupPosition(PopupPosition.TOP)
  4326. .atView(viewId)
  4327. .setBackgroundColor(Color.Black)
  4328. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4329. .show();
  4330. } else {
  4331. pup = XPopup.Builder()
  4332. .setPopupPosition(PopupPosition.TOP)
  4333. .atView(viewId)
  4334. .setBackgroundColor(Color.White)
  4335. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4336. .show();
  4337. }
  4338. }
  4339. /**
  4340. * 加载所有歌单
  4341. */
  4342. async loadAllPlaylists() {
  4343. try {
  4344. this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
  4345. LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
  4346. } catch (error) {
  4347. LogUtil.error('heaunp Failed to load playlists: ' + error.message)
  4348. }
  4349. }
  4350. /**
  4351. * 显示添加到歌单对话框
  4352. */
  4353. async openAddToPlaylistDialog(items: VideoItem | VideoItem[]) {
  4354. const songs = Array.isArray(items) ? items : [items]
  4355. const musicItems = songs.filter(song => song.type !== CommonConstants.TYPE_IS_DIR)
  4356. if (musicItems.length === 0) {
  4357. ToastUtil.showToast('请选择要添加的歌曲')
  4358. return
  4359. }
  4360. // 加载最新的歌单列表
  4361. await this.loadAllPlaylists()
  4362. showAddToPlaylistDialog(
  4363. musicItems,
  4364. this.allPlaylists,
  4365. async (playlistId: string) => {
  4366. // 添加歌曲到歌单
  4367. const success = await this.playlistTable?.addSongsToPlaylist(playlistId,
  4368. musicItems.map(song => song.filePath))
  4369. if (success) {
  4370. const count = musicItems.length
  4371. ToastUtil.showToast(count > 1 ? `已添加 ${count} 首歌曲` : '已添加到歌单')
  4372. // 重新加载歌单列表
  4373. await this.loadAllPlaylists()
  4374. } else {
  4375. ToastUtil.showToast(musicItems.length > 1 ? '选中的歌曲已在该歌单中' : '歌曲已在该歌单中')
  4376. }
  4377. this.longItemFilePath = ''
  4378. if (this.isMultiSelect) {
  4379. this.isMultiSelect = false
  4380. this.isAllSelected = false
  4381. this.selectedFiles = []
  4382. }
  4383. },
  4384. () => {
  4385. LogUtil.info('取消添加到歌单')
  4386. },
  4387. () => {
  4388. // 创建新歌单
  4389. showCreatePlaylistDialog(
  4390. async (name: string, description: string, coverPath?: string) => {
  4391. const success = await this.playlistTable?.createPlaylist(name, description, coverPath)
  4392. if (success) {
  4393. ToastUtil.showToast('歌单创建成功')
  4394. // 重新加载歌单列表并打开添加对话框
  4395. await this.loadAllPlaylists()
  4396. await this.openAddToPlaylistDialog(musicItems)
  4397. } else {
  4398. ToastUtil.showToast('歌单创建失败')
  4399. }
  4400. },
  4401. () => {
  4402. // 取消创建歌单
  4403. }
  4404. )
  4405. }
  4406. )
  4407. }
  4408. doFav(item: VideoItem) {
  4409. LogUtil.info('onecold doFav isFav=' + item.isFav)
  4410. let isFav = 0
  4411. if (Utility.getIsFav(this.favList, item)) {
  4412. isFav = 0
  4413. } else {
  4414. isFav = 1
  4415. }
  4416. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  4417. if (result) {
  4418. if (isFav === 1) {
  4419. ToastUtil.showToast('收藏成功');
  4420. } else {
  4421. ToastUtil.showToast('取消收藏成功');
  4422. }
  4423. this.deleteCache(this.currentPath)
  4424. this.getFavList(false)
  4425. if (this.modeType === 0 && !this.isFavMusic) {
  4426. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  4427. this.getSortedFiles(this.currentPath)
  4428. }
  4429. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  4430. workerInstance.postMessage({ code: 3, data: this.context });
  4431. workerInstance.postMessage({ code: 4, data: this.context });
  4432. }
  4433. })
  4434. }
  4435. //多选复制文件
  4436. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  4437. console.log('onecold showCopyDialogForMultipleFiles');
  4438. let mList: Array<string> = []
  4439. let rPath = this.rootPath
  4440. if (isCurrent) {
  4441. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  4442. rPath = this.currentPath
  4443. } else {
  4444. mList = Utility.getNameList(this.dirList);
  4445. rPath = this.rootPath
  4446. }
  4447. let dataBean = new BubbleBean();
  4448. dataBean.data = mList;
  4449. dataBean.isCopy = true
  4450. dataBean.color = this.themeColor
  4451. dataBean.onItemClick = (i) => {
  4452. const newDirPath = rPath + '/' + mList[i];
  4453. // Logger.info('newDirPath = ' + newDirPath)
  4454. this.selectedFiles.forEach((item) => {
  4455. const newPath = newDirPath + '/' + item.fileName;
  4456. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  4457. ToastUtil.showToast('复制成功');
  4458. this.cache.delete(newDirPath); // 删除目标路径缓存
  4459. this.getSortedFiles(this.currentPath);
  4460. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  4461. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  4462. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  4463. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  4464. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  4465. this.table.insert(newItem, (id: number) => {
  4466. //加入数据库
  4467. });
  4468. }
  4469. }).catch((error: Error) => {
  4470. console.error(error.message);
  4471. });
  4472. });
  4473. this.isMultiSelect = false
  4474. this.selectedFiles = [];
  4475. this.isAllSelected = false
  4476. XPopup.dismissTop();
  4477. };
  4478. let pup: XPopup
  4479. if (this.isDarkMode) {
  4480. pup = XPopup.Builder()
  4481. .setPopupPosition(PopupPosition.TOP)
  4482. .atView(viewId)
  4483. .setBackgroundColor(Color.Black)
  4484. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4485. .show();
  4486. } else {
  4487. pup = XPopup.Builder()
  4488. .setPopupPosition(PopupPosition.TOP)
  4489. .atView(viewId)
  4490. .setBackgroundColor(Color.White)
  4491. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4492. .show();
  4493. }
  4494. }
  4495. @Builder
  4496. private DirItem(item: VideoItem, index?: number) {
  4497. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  4498. Row() {
  4499. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  4500. $r('app.media.music_group'))
  4501. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4502. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4503. .fillColor(this.themeColor)// .fontSize(33)
  4504. .alt($r('app.media.music_group'))
  4505. .borderRadius(this.isCoverRectangle?9:'100%')
  4506. .clip(true)
  4507. .shadow({
  4508. radius: 2,
  4509. type: ShadowType.BLUR,
  4510. color: 'on_primary'
  4511. })
  4512. .sourceSize({width:38, height:38})
  4513. .margin({ left: 20, top: 8, bottom: 8 })
  4514. Column() {
  4515. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4516. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4517. .maxLines(1)// .width('88%')
  4518. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4519. .animation({
  4520. duration: 555,
  4521. curve: 'ease-in-out',
  4522. })
  4523. .transition({
  4524. type: TransitionType.Insert,
  4525. opacity: 0,
  4526. translate: { x: 160 }
  4527. })
  4528. .margin({ left: 10, right: 20 })
  4529. .fontColor($r('app.color.text_color'))
  4530. Row() {
  4531. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  4532. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4533. .padding({ top: 8 })
  4534. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  4535. .fontColor($r('app.color.text_color'))
  4536. .margin({ left: 10 })
  4537. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  4538. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4539. .padding({ top: 8 })
  4540. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  4541. .fontColor($r('app.color.text_color'))
  4542. .margin({ left: 10 })
  4543. Blank()
  4544. }
  4545. }
  4546. .height('100%')
  4547. .layoutWeight(1)
  4548. .justifyContent(FlexAlign.Center)
  4549. .alignItems(HorizontalAlign.Start)
  4550. Blank()
  4551. Image($r('app.media.arrow_right'))
  4552. .height(25)
  4553. .alignSelf(ItemAlign.Center)
  4554. .id(item.filePath)
  4555. .visibility(this.isShowAlphaBet?Visibility.None:Visibility.Visible)
  4556. .animation({ duration: 300, curve: Curve.Ease })
  4557. }
  4558. }
  4559. .backgroundColor(Color.Transparent)
  4560. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  4561. .width('98%')
  4562. .reuseId('dir_item')
  4563. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  4564. .opacity(this.opacityItem) // 绑定透明度
  4565. }
  4566. isShowDir(dirName: string) {
  4567. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  4568. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  4569. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  4570. if (dirName === undefined) {
  4571. return true
  4572. }
  4573. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  4574. return this.isShowSimi
  4575. }
  4576. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  4577. return this.isShowFAV
  4578. }
  4579. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  4580. return this.isShowHistory
  4581. }
  4582. return true
  4583. }
  4584. @State opacityItem: number = 1; // 控制透明度的状态变量
  4585. @Builder
  4586. private MusicItem(item: VideoItem, index?: number) {
  4587. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  4588. Row() {
  4589. Stack() {
  4590. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  4591. .fillColor(this.themeColor)
  4592. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4593. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4594. .alt($r('app.media.alt'))
  4595. .borderRadius(this.isCoverRectangle?9:'100%')
  4596. .clip(true)
  4597. .draggable(false)
  4598. .sourceSize({width:38, height:38})
  4599. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4600. // .autoResize(true) // 重采样,可减少内存占用
  4601. .opacity(this.opacityItem)// 绑定透明度
  4602. .margin({ left: 20 })
  4603. .shadow({
  4604. radius: StrUtil.isEmpty(item.pixelMapPath) ?6:14,
  4605. type: ShadowType.BLUR,
  4606. color: 'on_primary'
  4607. })
  4608. .gesture(LongPressGesture()
  4609. .onAction(async () => {
  4610. //如果是专辑和艺术家的首页,不能长按
  4611. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4612. return
  4613. //如果是我的收藏 最近播放等也不能长按
  4614. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4615. item.name === LocalMusic.STR_HISTORY_MUSIC
  4616. )
  4617. return
  4618. this.longItemFilePath = item.filePath
  4619. this.tempLyricContent = await this.getLyricContent(item)
  4620. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4621. })
  4622. .onActionEnd((event: GestureEvent) => {
  4623. }))
  4624. .onClick(()=>{
  4625. if (this.isMultiSelect) {
  4626. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4627. this.handleFileSelection(item, !isChecked);
  4628. } else {
  4629. this.doPlay(item,index)
  4630. this.setShowPlayTrue()
  4631. }
  4632. })
  4633. }
  4634. Column() {
  4635. Column() {
  4636. Text(this.isShowFileName?item.fileName :item.name)
  4637. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4638. .maxLines(1)
  4639. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4640. .animation({
  4641. duration: 555,
  4642. curve: 'Linear',
  4643. })
  4644. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4645. $r('app.color.text_color'))
  4646. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4647. .padding({right:25})
  4648. .bindPopup(this.longItemFilePath === item.filePath, {
  4649. builder: this.MenuBuilder(item,index,item.filePath),
  4650. placement: Placement.Top,
  4651. // autoCancel: true,
  4652. mask: {color:'#33000000'},
  4653. // popupColor: Color.Yellow,
  4654. enableArrow: false,//是否显示箭头
  4655. showInSubWindow: false,
  4656. onStateChange: (e) => {
  4657. if (!e.isVisible) {
  4658. this.longItemFilePath = ''
  4659. this.tempLyricContent = ''
  4660. }
  4661. }
  4662. })
  4663. .gesture(LongPressGesture()
  4664. .onAction(async () => {
  4665. //如果是专辑和艺术家的首页,不能长按
  4666. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4667. return
  4668. //如果是我的收藏 最近播放等也不能长按
  4669. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4670. item.name === LocalMusic.STR_HISTORY_MUSIC
  4671. )
  4672. return
  4673. this.longItemFilePath = item.filePath
  4674. this.tempLyricContent = await this.getLyricContent(item)
  4675. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4676. })
  4677. .onActionEnd((event: GestureEvent) => {
  4678. })
  4679. )
  4680. Row() {
  4681. Column(){
  4682. Text(item.md5Str?.includes('Lossless')?
  4683. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4684. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  4685. .padding({ top: 3,right:6,left:6,bottom:3 })
  4686. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4687. $r('app.color.text_color'))
  4688. .fontWeight(500)
  4689. .borderRadius(12)
  4690. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  4691. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4692. .backgroundColor('#FFC107')
  4693. }
  4694. .padding({ top: 8 })
  4695. Text(StrUtil.isEmpty(item.artist) ? item.duration
  4696. :this.twoFingerType==2? item.artist +' ' + item.duration
  4697. : item.artist + ' ' + item?.duration)
  4698. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4699. .padding({ top: 8 ,right:25})
  4700. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  4701. .maxLines(1)
  4702. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4703. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4704. Color.Gray)
  4705. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4706. Blank()
  4707. Text(this.isShowFileName?item.duration:item.size)
  4708. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4709. .padding({ top: 8 })
  4710. .maxLines(1)
  4711. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  4712. ? Visibility.Visible : Visibility.None)
  4713. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4714. Color.Gray)
  4715. .margin({ left: StrUtil.isEmpty(item.artist) ?0:10 })
  4716. }
  4717. .gesture(LongPressGesture()
  4718. .onAction(async () => {
  4719. //如果是专辑和艺术家的首页,不能长按
  4720. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4721. return
  4722. //如果是我的收藏 最近播放等也不能长按
  4723. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4724. item.name === LocalMusic.STR_HISTORY_MUSIC
  4725. )
  4726. return
  4727. this.longItemFilePath = item.filePath
  4728. this.tempLyricContent = await this.getLyricContent(item)
  4729. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4730. })
  4731. .onActionEnd((event: GestureEvent) => {
  4732. })
  4733. )
  4734. }
  4735. .height('100%')
  4736. .width('100%')
  4737. .margin({ right: 10 })
  4738. .justifyContent(FlexAlign.Center)
  4739. .alignItems(HorizontalAlign.Start)
  4740. }
  4741. .height('100%')
  4742. .margin({ left: 5 })
  4743. .layoutWeight(1)
  4744. Column() {
  4745. Checkbox({ name: 'checkbox' + index })
  4746. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  4747. .selectedColor(this.themeColor)
  4748. .shape(CheckBoxShape.CIRCLE)
  4749. .opacity(this.isMultiSelect ? 1 : 0)
  4750. .animation({
  4751. duration: 666,
  4752. curve: 'Smooth' // 可选动画曲线
  4753. })
  4754. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  4755. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  4756. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  4757. .width(22)
  4758. .height(22)
  4759. ImageAnimator()
  4760. .images(this.imagesF)// 动画数组
  4761. .duration(1000)// 持续
  4762. .state(this.animationState)// 动画状态
  4763. .fillMode(FillMode.Forwards)
  4764. .width(18)
  4765. .margin({ right: 20, top: 8, bottom: 8 })
  4766. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  4767. Visibility.None)
  4768. .height(18)
  4769. .iterations(-1) // 播放次数
  4770. }
  4771. }
  4772. }
  4773. .backgroundColor(Color.Transparent)
  4774. .width('100%')
  4775. .reuseId('file_item')
  4776. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  4777. }
  4778. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  4779. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  4780. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  4781. direction: Direction.Ltr,
  4782. buttonPadding:{top:12,bottom:12},
  4783. backgroundColor: Color.Transparent,
  4784. fontSize:14,
  4785. selectedFontSize:15,
  4786. selectedFontColor:Color.White,
  4787. selectedBackgroundColor: this.themeColor,
  4788. localizedTextPadding: {
  4789. end: LengthMetrics.vp(20),
  4790. start: LengthMetrics.vp(20)
  4791. }
  4792. })
  4793. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  4794. //当胶囊按钮的选择发生变化时调用此函数
  4795. capsuleSelectedIndexesChanged() {
  4796. this.modeType = this.tabSelectedIndexes[0]
  4797. }
  4798. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  4799. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  4800. isShowCoverHeader() {
  4801. if (!this.isShowHeader) {
  4802. return false
  4803. }
  4804. if (this.modeType == 0) {
  4805. if (this.isHistory || this.isFavMusic) {
  4806. return true
  4807. }
  4808. if (this.currentPath != this.rootPath) {
  4809. return true
  4810. }
  4811. }
  4812. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  4813. }
  4814. getCoverTitleBg(): ResourceStr | image.PixelMap {
  4815. if (this.isCustomizeBg) {
  4816. return ('rgba(255,255,255,0.2)')
  4817. }
  4818. if (this.isDarkMode) {
  4819. return $r('app.color.user_center_card_background')
  4820. }
  4821. return this.currentTitleCover
  4822. }
  4823. // 第二步:popup构造器定义弹框内容
  4824. @Builder popupBuilder() {
  4825. Column({ space: 2 }) {
  4826. Text('友情提示:双指缩放可以放大缩小列表')
  4827. .fontSize(12)
  4828. .fontWeight(FontWeight.Regular)
  4829. .fontColor($r('app.color.text_color'))
  4830. }
  4831. .justifyContent(FlexAlign.SpaceAround)
  4832. .width(220)
  4833. .height(55)
  4834. .padding(15)
  4835. }
  4836. //搜索功能的实现
  4837. @State searchText: string = ''; // 用户输入内容
  4838. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  4839. @State isSearchMode: boolean = false
  4840. // 实时搜索逻辑(带防抖)
  4841. private onSearchInput(value: string) {
  4842. this.searchText = value.trim();
  4843. let mSearchList: Array<VideoItem> = []
  4844. switch (this.modeType) {
  4845. case 0:
  4846. case 1:
  4847. mSearchList = this.mediaKuList
  4848. break;
  4849. case 2:
  4850. mSearchList = this.artistList
  4851. break;
  4852. case 3:
  4853. mSearchList = this.albumList
  4854. break;
  4855. default :
  4856. mSearchList = this.videoLocalList
  4857. break;
  4858. }
  4859. // 新增条件判断:空输入时显示所有数据
  4860. if (this.searchText === '') {
  4861. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  4862. } else {
  4863. this.filteredList = mSearchList.filter((item: VideoItem) => {
  4864. //支持模糊匹配和艺术家 专辑匹配
  4865. const regex = new RegExp(this.searchText.toLowerCase().replace(/\s+/g, '.*'), 'i');
  4866. return regex.test(item.name.toLowerCase())||
  4867. regex.test(item.fileName?.toLowerCase() ?? "") ||
  4868. regex.test(item.artist?.toLowerCase() ?? "") ||
  4869. regex.test(item.album?.toLowerCase() ?? "")
  4870. });
  4871. }
  4872. this.updateListData(this.filteredList);
  4873. // this.isSearchMode = false; // 根据业务需求决定是否启用
  4874. }
  4875. @State dragItem: number = -1
  4876. @State scaleItem: number = -1
  4877. @State neighborItem: number = -1
  4878. @State neighborScale: number = -1
  4879. @State offsetY: number = 0
  4880. private dragRefOffset: number = 0
  4881. private ITEM_INTV: number = 78
  4882. scaleSelect(item: number): number {
  4883. if (this.scaleItem === item) {
  4884. return 1.05
  4885. } else if (this.neighborItem === item) {
  4886. return this.neighborScale
  4887. } else {
  4888. return 1
  4889. }
  4890. }
  4891. itemMove(index: number, newIndex: number): void {
  4892. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  4893. return;
  4894. }
  4895. let tmp = this.videoLocalList.splice(index, 1);
  4896. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  4897. this.dataSource.pushArrayData(this.videoLocalList)
  4898. if(this.modeType==4&&this.playlistTable){
  4899. updateAllSongsSortOrder(this.playlistTable, this.videoLocalList,this.currentSongListID)
  4900. }
  4901. }
  4902. //瀑布流布局 支持双指缩放
  4903. @State columns: number = 2;
  4904. @State waterFlowScale: number = 1;
  4905. @State imageScale: number = 1;
  4906. @State waterFlowOpacity: number = 1;
  4907. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  4908. private columnChanged: boolean = false;
  4909. private oldColumn: number = this.columns;
  4910. private pinchTime: number = 0;
  4911. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  4912. changeColumns(scale: number) {
  4913. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  4914. this.columns--;
  4915. this.columnChanged = true;
  4916. } else if (scale < 1 && this.columns < 4) {
  4917. this.columns++;
  4918. this.columnChanged = true;
  4919. }
  4920. }
  4921. @Builder
  4922. getWaterView(){
  4923. Scroll(this.scroller) {
  4924. Column() {
  4925. Blank().height(this.topSafeHeight + 55)
  4926. WaterFlow({
  4927. scroller:this.waterScroller,
  4928. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  4929. }) {
  4930. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  4931. FlowItem() {
  4932. this.MusicWaterCardItem(item,index)
  4933. }
  4934. .width('100%')
  4935. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  4936. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  4937. {
  4938. preview: MenuPreviewMode.IMAGE,
  4939. previewAnimationOptions: { scale: [0.8, 1.0] },
  4940. })
  4941. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  4942. {
  4943. preview: MenuPreviewMode.IMAGE,
  4944. previewAnimationOptions: { scale: [0.8, 1.0] },
  4945. })
  4946. .transition(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }))
  4947. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  4948. TransitionEffect.scale({ x: 0, y: 0 })))
  4949. .gesture(
  4950. GestureGroup(GestureMode.Exclusive,
  4951. SwipeGesture({ direction: SwipeDirection.Horizontal })
  4952. .onAction((event: GestureEvent) => {
  4953. if (event) {
  4954. // this.sideBarController.openSideBar()
  4955. }
  4956. }),
  4957. TapGesture({ count: 1, fingers: 1 })
  4958. .onAction(async () => {
  4959. })
  4960. )
  4961. )
  4962. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  4963. }
  4964. // .columnsTemplate('repeat(auto-fit, 160)')
  4965. .id('waterflow') // 设置id用于截图
  4966. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  4967. .columnsGap(12) // 列间距
  4968. .rowsGap(16) // 行间距
  4969. .cachedCount(6)
  4970. .padding({bottom:this.bottomBarHeight+10})
  4971. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4972. .animation({ duration: 500, curve: Curve.Ease }))
  4973. .scrollBar(BarState.Off)
  4974. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  4975. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  4976. .edgeEffect(EdgeEffect.Spring, { alwaysEnabled: true })
  4977. .width('90%')
  4978. .height('100%')
  4979. .opacity(this.waterFlowOpacity)
  4980. .scale({
  4981. x: this.waterFlowScale,
  4982. y: this.waterFlowScale,
  4983. centerX: 0,
  4984. centerY: 0
  4985. })
  4986. .onAppear(() => {
  4987. this.scroller.scrollEdge(Edge.Top)
  4988. })
  4989. .nestedScroll({
  4990. scrollForward: NestedScrollMode.PARENT_FIRST,
  4991. scrollBackward: NestedScrollMode.SELF_FIRST
  4992. })
  4993. .priorityGesture(
  4994. PinchGesture()
  4995. .onActionStart((event: GestureEvent) => {
  4996. // 双指捏合手势识别成功时截图
  4997. this.pinchTime = event.timestamp;
  4998. this.columnChanged = false;
  4999. this.oldColumn = this.columns;
  5000. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  5001. if (error) {
  5002. console.info('error:' + JSON.stringify(error));
  5003. return;
  5004. }
  5005. this.waterFlowSnapshot = pixmap;
  5006. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  5007. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  5008. if (this.oldColumn ===4) {
  5009. this.twoFingerType =3
  5010. this.isGridMusic = true
  5011. }else if (this.oldColumn ===1) {
  5012. this.twoFingerType =1
  5013. this.isGridMusic = false
  5014. }
  5015. return;
  5016. }
  5017. })
  5018. })
  5019. .onActionUpdate((event: GestureEvent) => {
  5020. // 手势更新:处理缩放逻辑和视觉效果
  5021. // 边界限制:防止超出列数范围时继续缩放
  5022. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  5023. return;
  5024. }
  5025. // 节流处理:避免过于频繁的更新,提升性能
  5026. if (event.timestamp - this.pinchTime < 10000000) {
  5027. return;
  5028. }
  5029. this.pinchTime = event.timestamp;
  5030. this.waterFlowScale = event.scale;
  5031. this.imageScale = event.scale;
  5032. // 根据缩放比例设置WaterFlow透明度
  5033. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  5034. this.waterFlowOpacity *= 3;
  5035. if (!this.columnChanged) {
  5036. this.changeColumns(event.scale);
  5037. }
  5038. // 列数改变后的缩放比例调整:避免出现空白区域
  5039. if (this.columnChanged) {
  5040. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  5041. // 限制缩放范围,确保视觉效果自然
  5042. if (event.scale < 1) {
  5043. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  5044. } else {
  5045. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  5046. }
  5047. }
  5048. })
  5049. .onActionEnd((event: GestureEvent) => {
  5050. // 手势结束:执行归位动画并保存状态
  5051. // 执行归位动画:平滑过渡到正常状态
  5052. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  5053. this.waterFlowScale = 1;
  5054. this.waterFlowOpacity = 1;
  5055. })
  5056. // 持久化保存当前列数:下次启动时恢复
  5057. PreferencesUtil.putSync('lastColumns', this.columns);
  5058. })
  5059. )
  5060. .onScrollFrameBegin((offset: number) => {
  5061. // 获取当前滚动偏移量
  5062. if(this.autoHideTitle){
  5063. const currentOffsetY = this.waterScroller.currentOffset().yOffset;
  5064. // 判断滚动方向
  5065. if (currentOffsetY > this.prevOffsetY) {
  5066. // console.log("onecold 向上滚动");
  5067. this.isShowTitleBar = false
  5068. } else if (currentOffsetY < this.prevOffsetY) {
  5069. // console.log("onecold 向下滚动");
  5070. this.isShowTitleBar = true
  5071. }
  5072. // 更新前一次偏移量
  5073. this.prevOffsetY = currentOffsetY;
  5074. }
  5075. return { offsetRemain: offset };
  5076. })
  5077. }
  5078. }
  5079. .scrollBar(BarState.Off)
  5080. }
  5081. //瀑布流卡片布局
  5082. @Builder
  5083. private MusicWaterCardItem(item: VideoItem, index: number) {
  5084. Button({ type: ButtonType.Normal, stateEffect: false }) {
  5085. Stack() {
  5086. Column() {
  5087. Image(item.pixelMapPath)
  5088. .backgroundImageSize(ImageSize.Auto)
  5089. .borderRadius({
  5090. topLeft: 12,
  5091. topRight : 12,
  5092. bottomLeft: 0,
  5093. bottomRight: 0
  5094. })
  5095. .draggable(false)// 禁止长按手势拖动
  5096. .autoResize(true) // 重采样,可减少内存占用
  5097. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  5098. .width('100%')
  5099. .height('auto')
  5100. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  5101. .objectFit(ImageFit.Auto)
  5102. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  5103. height: '99%' ,
  5104. dragBar: true,
  5105. onDisappear: () => {
  5106. this.longItemFilePath = '';
  5107. this.tempLyricContent = ''
  5108. },
  5109. showClose: true,
  5110. preferType: SheetType.CENTER ,
  5111. title: { title: '编辑标签' }
  5112. })
  5113. .draggable(false)
  5114. .opacity(this.opacityItem)// 绑定透明度
  5115. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  5116. // .animation({ duration: 500, curve: Curve.Ease }))
  5117. .animation({
  5118. duration: 666,
  5119. curve: 'ease-in-out' // 可选动画曲线
  5120. })
  5121. .margin({
  5122. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5123. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5124. })
  5125. Column() {
  5126. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5127. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  5128. .maxLines(1)
  5129. .fontWeight(FontWeight.Bold)
  5130. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5131. .animation({
  5132. duration: 555,
  5133. curve: 'Linear',
  5134. })
  5135. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  5136. height: '95%',
  5137. dragBar: true,
  5138. showClose: true,
  5139. onDisappear: () => {
  5140. this.longItemFilePathDetail = '';
  5141. },
  5142. blurStyle:BlurStyle.Thin,
  5143. backgroundColor:Color.Transparent,
  5144. preferType: SheetType.CENTER ,
  5145. title: { title: '详情' }
  5146. })
  5147. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5148. $r('app.color.text_color'))
  5149. Column() {
  5150. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  5151. .fontSize(11)
  5152. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  5153. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5154. .fontColor($r('app.color.text_color'))
  5155. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  5156. .fontSize(11)
  5157. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  5158. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5159. .fontColor($r('app.color.text_color'))
  5160. Row(){
  5161. Column(){
  5162. Text(item.md5Str?.includes('Lossless')?
  5163. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5164. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  5165. .padding({ top: 3,right:6,left:6,bottom:3 })
  5166. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5167. $r('app.color.text_color'))
  5168. .fontWeight(500)
  5169. .borderRadius(12)
  5170. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5171. .backgroundColor('#FFC107')
  5172. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  5173. }
  5174. .margin({ top: 2 ,right:6})
  5175. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  5176. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  5177. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  5178. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  5179. .maxLines(1)
  5180. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5181. .margin({ top: 2})
  5182. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  5183. || item.type == CommonConstants.TYPE_IS_ALBUM
  5184. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5185. .fontWeight(FontWeight.Medium)
  5186. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5187. $r('app.color.text_color'))
  5188. }
  5189. }
  5190. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  5191. }
  5192. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  5193. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  5194. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  5195. .width('100%')
  5196. .justifyContent(FlexAlign.Center)
  5197. .margin({
  5198. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5199. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5200. })
  5201. }
  5202. .width('100%')
  5203. .borderRadius(12)
  5204. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  5205. .backgroundImageSize({ height: '100%', width: '100%' })
  5206. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  5207. .animation({ curve: Curve.Sharp, duration: 300 })
  5208. Checkbox({ name: 'checkbox' + index })
  5209. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  5210. .selectedColor(this.themeColor)
  5211. .shape(CheckBoxShape.CIRCLE)
  5212. .opacity(this.isMultiSelect ? 1 : 0)
  5213. .animation({
  5214. duration: 666,
  5215. curve: 'Smooth' // 可选动画曲线
  5216. })
  5217. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  5218. Visibility.None)
  5219. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5220. .margin({ left: 20, top: 8, bottom: 8 })
  5221. .width(38)
  5222. .height(38)
  5223. }
  5224. }
  5225. .backgroundColor(Color.Transparent)
  5226. .width('100%')
  5227. .height('auto')
  5228. .padding({top:2})
  5229. .shadow({
  5230. radius: 10,
  5231. type: ShadowType.BLUR,
  5232. color: 'on_primary'
  5233. })
  5234. .reuseId('card_item')
  5235. .onClick(() => {
  5236. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5237. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5238. this.handleFileSelection(item, !isChecked);
  5239. } else {
  5240. this.doPlay(item, index)
  5241. }
  5242. })
  5243. }
  5244. // Grid布局的开始
  5245. private dragRefOffSetX: number = 0;
  5246. private dragRefOffSetY: number = 0;
  5247. private FIX_VP_X: number = 180;
  5248. private FIX_VP_Y: number = 84;
  5249. isDraggable(index: number): boolean {
  5250. return index >= 0;
  5251. }
  5252. getRowEnd(item: number) {
  5253. if (item.toString() === '0') {
  5254. return 1;
  5255. } else {
  5256. return 0;
  5257. }
  5258. }
  5259. isInLeft(index: number) {
  5260. return index % 2 == 0;
  5261. }
  5262. down(index: number): void {
  5263. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  5264. return;
  5265. }
  5266. this.offsetY -= this.FIX_VP_Y;
  5267. this.dragRefOffSetY += this.FIX_VP_Y;
  5268. this.itemMove(index, index + 1);
  5269. }
  5270. up(index: number): void {
  5271. if (!this.isDraggable(index - 2)) {
  5272. return;
  5273. }
  5274. this.offsetY += this.FIX_VP_Y;
  5275. this.dragRefOffSetY -= this.FIX_VP_Y;
  5276. this.itemMove(index, index - 1);
  5277. }
  5278. left(index: number): void {
  5279. if (this.isInLeft(index)) {
  5280. return;
  5281. }
  5282. if (!this.isDraggable(index - 1)) {
  5283. return;
  5284. }
  5285. this.offsetX += this.FIX_VP_X;
  5286. this.dragRefOffSetX -= this.FIX_VP_X;
  5287. this.itemMove(index, index - 1)
  5288. }
  5289. right(index: number): void {
  5290. if (!this.isInLeft(index)) {
  5291. return;
  5292. }
  5293. if (!this.isDraggable(index + 1)) {
  5294. return;
  5295. }
  5296. this.offsetX -= this.FIX_VP_X;
  5297. this.dragRefOffSetX += this.FIX_VP_X;
  5298. this.itemMove(index, index + 1)
  5299. }
  5300. private scroller: Scroller = new Scroller();
  5301. private waterScroller: Scroller = new Scroller();
  5302. @State startIndex: number = 0
  5303. @State endIndex: number = 0
  5304. @State scaleValue: number = 1
  5305. @State pinchValue: number = 1
  5306. layoutOptionsForHeader: GridLayoutOptions = {
  5307. regularSize: [1, 1], // 只支持[1, 1]
  5308. irregularIndexes: [0], // 索引为0的GridItem占用一行
  5309. };
  5310. @Builder
  5311. getGridView() {
  5312. Grid(this.scroller, this.layoutOptionsForHeader) {
  5313. GridItem() {
  5314. Column(){
  5315. Blank().height(this.topSafeHeight + 45)
  5316. }
  5317. }
  5318. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5319. GridItem() {
  5320. Stack({ alignContent: Alignment.Center }) {
  5321. this.MusicItemGrid(item, index)
  5322. }
  5323. }
  5324. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  5325. {
  5326. preview: MenuPreviewMode.IMAGE,
  5327. previewAnimationOptions: { scale: [0.8, 1.0] },
  5328. })
  5329. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  5330. {
  5331. preview: MenuPreviewMode.IMAGE,
  5332. previewAnimationOptions: { scale: [0.8, 1.0] },
  5333. })
  5334. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  5335. TransitionEffect.scale({ x: 0, y: 0 })))
  5336. .clickEffect({ level: ClickEffectLevel.LIGHT })
  5337. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  5338. .zIndex(this.dragItem === index ? 1 : 0)
  5339. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  5340. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5341. }
  5342. .width('94%')
  5343. .height('100%')
  5344. .editMode(true)
  5345. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  5346. .animation({ duration: 500, curve: Curve.Ease }))
  5347. .padding({bottom:this.bottomBarHeight+this.bottomSafeHeight+10})
  5348. .reuseId('grid_item')
  5349. .layoutWeight(1)
  5350. .scrollBar(BarState.Off)
  5351. .supportAnimation(true)
  5352. .cachedCount(this.twoFingerType==1?5:this.twoFingerType==2?4:3)
  5353. .columnsTemplate(
  5354. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  5355. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  5356. )
  5357. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  5358. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  5359. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5360. .gesture(PinchGesture({ fingers: 2 })
  5361. .onActionEnd((event: GestureEvent) => {
  5362. this.setGridTwoFingers()
  5363. })
  5364. .onActionUpdate(e => {
  5365. this.scaleValue = this.pinchValue * e.scale
  5366. })
  5367. .onActionStart(e => {
  5368. }))
  5369. .enableScrollInteraction(true)
  5370. .onScrollIndex((start: number, end: number) => {
  5371. this.startIndex = start
  5372. this.endIndex = end
  5373. })
  5374. .onScrollFrameBegin((offset: number) => {
  5375. if(this.autoHideTitle){
  5376. const currentOffsetY = this.scroller.currentOffset().yOffset;
  5377. // 判断滚动方向
  5378. if (currentOffsetY > this.prevOffsetY) {
  5379. // console.log("onecold 向上滚动");
  5380. this.isShowTitleBar = false
  5381. } else if (currentOffsetY < this.prevOffsetY) {
  5382. // console.log("onecold 向下滚动");
  5383. this.isShowTitleBar = true
  5384. }
  5385. // 更新前一次偏移量
  5386. this.prevOffsetY = currentOffsetY;
  5387. }
  5388. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  5389. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  5390. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  5391. if (this.isScrollHide) {
  5392. this.setBarHeightHide2(offset)
  5393. } else {
  5394. this.setBarHeightNormal()
  5395. }
  5396. } else {
  5397. this.setBarHeightHide(offset)
  5398. }
  5399. return { offsetRemain: offset };
  5400. })
  5401. }
  5402. @State targetFile: string = '';
  5403. setGridTwoFingers() {
  5404. this.pinchValue = this.scaleValue;
  5405. Logger.info('this.pinchValue = ' + this.pinchValue);
  5406. if (this.pinchValue >= 1) {
  5407. this.twoFingerType++
  5408. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  5409. if(this.twoFingerType >= 4){
  5410. this.twoFingerType = 4//切换成瀑布流
  5411. this.columns = 4
  5412. }
  5413. } else {
  5414. this.twoFingerType--
  5415. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  5416. if (this.twoFingerType < 1) {
  5417. this.twoFingerType = 3
  5418. this.isGridMusic = false
  5419. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5420. }
  5421. }
  5422. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5423. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5424. this.pinchValue = 1;
  5425. this.scaleValue = 1;
  5426. }
  5427. @State longItemFilePath: string = ''
  5428. @State tempLyricContent: string = ''
  5429. @State editingItem: VideoItem | null = null
  5430. @Builder
  5431. private MusicItemGrid(item: VideoItem, index: number) {
  5432. Button({ type: ButtonType.Normal, stateEffect: false }) {
  5433. Stack() {
  5434. Column() {
  5435. Image(item.pixelMapPath)
  5436. .height(this.getGridHeight())
  5437. .width(this.getGridWight())
  5438. .draggable(false)
  5439. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  5440. .autoResize(true) // 重采样,可减少内存占用
  5441. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  5442. .clip(true)
  5443. .borderRadius({
  5444. topLeft: 12,
  5445. topRight: 12,
  5446. bottomLeft: 0,
  5447. bottomRight: 0
  5448. })
  5449. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  5450. height: '99%' ,
  5451. dragBar: true,
  5452. onDisappear: () => {
  5453. this.longItemFilePath = '';
  5454. this.tempLyricContent = ''
  5455. },
  5456. showClose: true,
  5457. preferType: SheetType.CENTER ,
  5458. title: { title: '编辑标签' }
  5459. })
  5460. .draggable(false)
  5461. .opacity(this.opacityItem)// 绑定透明度
  5462. .animation({
  5463. duration: 666,
  5464. curve: 'ease-in-out' // 可选动画曲线
  5465. })
  5466. .margin({
  5467. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5468. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5469. })
  5470. Column() {
  5471. Text(this.isShowFileName&&item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5472. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5473. .maxLines(1)
  5474. .fontWeight(FontWeight.Bold)
  5475. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5476. .animation({
  5477. duration: 555,
  5478. curve: 'Linear',
  5479. })
  5480. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  5481. height: '100%',
  5482. dragBar: true,
  5483. showClose: true,
  5484. onDisappear: () => {
  5485. this.longItemFilePathDetail = '';
  5486. },
  5487. blurStyle:BlurStyle.Thin,
  5488. backgroundColor:Color.Transparent,
  5489. preferType: SheetType.CENTER ,
  5490. title: { title: '详情' }
  5491. })
  5492. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5493. $r('app.color.text_color'))
  5494. Column() {
  5495. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  5496. .fontSize(11)
  5497. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  5498. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5499. .fontColor($r('app.color.text_color'))
  5500. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  5501. .fontSize(11)
  5502. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  5503. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5504. .fontColor($r('app.color.text_color'))
  5505. Row(){
  5506. Column(){
  5507. Text(item.md5Str?.includes('Lossless')?
  5508. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5509. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5510. .padding({ top: 3,right:6,left:6,bottom:3 })
  5511. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5512. $r('app.color.text_color'))
  5513. .fontWeight(500)
  5514. .borderRadius(12)
  5515. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5516. .backgroundColor('#FFC107')
  5517. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  5518. }
  5519. .margin({ top: 2 ,right:6})
  5520. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  5521. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  5522. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  5523. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  5524. .maxLines(1)
  5525. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5526. .margin({ top: 2})
  5527. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  5528. || item.type == CommonConstants.TYPE_IS_ALBUM
  5529. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5530. .fontWeight(FontWeight.Medium)
  5531. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5532. $r('app.color.text_color'))
  5533. }
  5534. }
  5535. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  5536. }
  5537. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  5538. .width(this.getGridWight())
  5539. .justifyContent(FlexAlign.Center)
  5540. .margin({
  5541. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5542. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5543. })
  5544. }
  5545. .width(this.getGridWight())
  5546. .borderRadius(12)
  5547. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?$r('app.media.alt'):item.pixelMapPath)
  5548. .backgroundImageSize({ height: '100%', width: '100%' })
  5549. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  5550. .animation({ curve: Curve.Sharp, duration: 300 })
  5551. Checkbox({ name: 'checkbox' + index })
  5552. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  5553. .selectedColor(this.themeColor)
  5554. .shape(CheckBoxShape.CIRCLE)
  5555. .opacity(this.isMultiSelect ? 1 : 0)
  5556. .animation({
  5557. duration: 666,
  5558. curve: 'Smooth' // 可选动画曲线
  5559. })
  5560. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  5561. Visibility.None)
  5562. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5563. .margin({ left: 20, top: 8, bottom: 8 })
  5564. .width(38)
  5565. .height(38)
  5566. }
  5567. }
  5568. .backgroundColor(Color.Transparent)
  5569. .width('100%')
  5570. .padding({ top: 15 })
  5571. .height(this.getGridAllHeight())
  5572. .onClick(() => {
  5573. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5574. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5575. this.handleFileSelection(item, !isChecked);
  5576. } else {
  5577. this.doPlay(item, index)
  5578. }
  5579. })
  5580. }
  5581. getGridAllHeight() {
  5582. let heightG = 222
  5583. switch (this.twoFingerType) {
  5584. case 1:
  5585. heightG = 143
  5586. break;
  5587. case 2:
  5588. heightG = 178
  5589. break;
  5590. case 3:
  5591. heightG = 222
  5592. break;
  5593. }
  5594. return heightG
  5595. }
  5596. getGridHeight() {
  5597. let heightG = 150
  5598. switch (this.twoFingerType) {
  5599. case 1:
  5600. heightG = 80
  5601. break;
  5602. case 2:
  5603. heightG = 110
  5604. break;
  5605. case 3:
  5606. heightG = 150
  5607. break;
  5608. }
  5609. return heightG
  5610. }
  5611. getGridWight() {
  5612. let wightG = 158
  5613. switch (this.twoFingerType) {
  5614. case 1:
  5615. wightG = 80
  5616. break;
  5617. case 2:
  5618. wightG = 110
  5619. break;
  5620. case 3:
  5621. wightG = 158
  5622. break;
  5623. }
  5624. return wightG
  5625. }
  5626. @State isShowDetail:boolean = false
  5627. @State longItemFilePathDetail:string =''
  5628. @Builder
  5629. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  5630. if(
  5631. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  5632. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5633. item.name === LocalMusic.STR_HISTORY_MUSIC)
  5634. ){
  5635. //如果是专辑和艺术家的首页,不能长按
  5636. //如果是我的收藏 最近播放等也不能长按
  5637. }else{
  5638. Scroll() {
  5639. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  5640. Menu() {
  5641. MenuItem({
  5642. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  5643. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  5644. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  5645. })
  5646. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5647. .onClick(() => {
  5648. if (item) {
  5649. this.doFav(item)
  5650. }
  5651. this.longItemFilePath = ''
  5652. })
  5653. MenuItem({
  5654. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  5655. content: '下一首播放'
  5656. })
  5657. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5658. .onClick(() => {
  5659. this.addToNextPlay(item);
  5660. this.longItemFilePath = ''
  5661. })
  5662. MenuItem({
  5663. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  5664. content: '添加到歌单'
  5665. })
  5666. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5667. .onClick(async () => {
  5668. this.longItemFilePath = ''
  5669. await this.openAddToPlaylistDialog(item)
  5670. })
  5671. MenuItem({
  5672. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  5673. content: '编辑标签'
  5674. })
  5675. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  5676. height: '99%',
  5677. dragBar: true,
  5678. showClose: true,
  5679. preferType: SheetType.CENTER ,
  5680. title: { title: '编辑标签' }
  5681. })
  5682. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5683. .onClick(async() => {
  5684. this.initEditFields(item)
  5685. this.tempLyricContent = await this.getLyricContent(item);
  5686. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  5687. this.lyricConStr = this.tempLyricContent
  5688. }
  5689. if(this.isGridMusic||this.twoFingerType==4){
  5690. this.longItemFilePath = item.filePath
  5691. }else{
  5692. this.isShowEdit = !this.isShowEdit;
  5693. }
  5694. })
  5695. MenuItem({
  5696. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  5697. content: $r('app.string.select_all')
  5698. })
  5699. .onClick(() => {
  5700. this.isMultiSelect = !this.isMultiSelect
  5701. this.longItemFilePath = ''
  5702. this.selectedFiles.push(item)
  5703. })
  5704. MenuItem({
  5705. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.cut')),
  5706. content: $r('app.string.edit_audio')
  5707. })
  5708. .bindContentCover($$this.isEditAudio, this.EditAudioBuilder(item), {
  5709. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5710. })
  5711. .onClick(() => {
  5712. this.isEditAudio = !this.isEditAudio
  5713. })
  5714. MenuItem({
  5715. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  5716. content: $r('app.string.extract_accompaniment')
  5717. })
  5718. .bindContentCover($$this.isExtractAcc, this.ExtractAccBuilder(item), {
  5719. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5720. })
  5721. .onClick(() => {
  5722. if (!Utility.isNoble()) {
  5723. this.showVipDialog()
  5724. return
  5725. }
  5726. this.isExtractAcc = !this.isExtractAcc
  5727. })
  5728. MenuItem({
  5729. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.repeat')),
  5730. content: $r('app.string.converter_audio')
  5731. })
  5732. .bindContentCover($$this.isConverter, this.ConverterBuilder(item), {
  5733. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5734. })
  5735. .onClick(() => {
  5736. if (!Utility.isNoble()) {
  5737. this.showVipDialog()
  5738. return
  5739. }
  5740. this.isConverter = !this.isConverter
  5741. })
  5742. MenuItem({
  5743. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.ai_edit')),
  5744. content: $r('app.string.vocal_separation')
  5745. })
  5746. .bindContentCover($$this.isAIVoiceSeparation, this.AiBuilder(item), {
  5747. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5748. })
  5749. .onClick(() => {
  5750. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  5751. })
  5752. MenuItem({
  5753. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_counterclockwise_clock')),
  5754. content: $r('app.string.change_tone')
  5755. })
  5756. .bindContentCover($$this.isChangeTone, this.ChangeToneBuilder(item), {
  5757. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5758. })
  5759. .onClick(() => {
  5760. this.isChangeTone = !this.isChangeTone
  5761. })
  5762. if(Utility.isVideoByExtension(item.filePath)){
  5763. MenuItem({
  5764. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.identify_song')),
  5765. content: $r('app.string.extract_audio')
  5766. })
  5767. .bindContentCover($$this.isExtractAudio, this.extractAudioFromVideoBuilder(item), {
  5768. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5769. })
  5770. .onClick(() => {
  5771. this.isExtractAudio = !this.isExtractAudio
  5772. })
  5773. }
  5774. MenuItem({
  5775. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.phone')),
  5776. content: $r('app.string.set_ring')
  5777. })
  5778. .onClick(async () => {
  5779. await PermissionUtil.activatePermission(item.filePath)
  5780. // if(item.filePath.includes(this.packName)){
  5781. setRingTone(this.context, item.filePath,item.name)
  5782. // }else{
  5783. // ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限设置铃声')
  5784. // }
  5785. this.longItemFilePath = ''
  5786. })
  5787. MenuItem({
  5788. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  5789. content: $r('app.string.rename')
  5790. })
  5791. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  5792. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5793. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  5794. .onClick(() => {
  5795. this.showReNameDialog(item, index + '', filePath)
  5796. this.longItemFilePath = ''
  5797. })
  5798. MenuItem({
  5799. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  5800. content: $r('app.string.delete')
  5801. })
  5802. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  5803. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5804. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  5805. .onClick(() => {
  5806. this.selectedFiles.push(item)
  5807. this.showWarnIsDelete()
  5808. this.longItemFilePath = ''
  5809. })
  5810. MenuItem({
  5811. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  5812. content: $r('app.string.detail')
  5813. })
  5814. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  5815. height:'100%',
  5816. dragBar: true,
  5817. showClose: true,
  5818. blurStyle:BlurStyle.Thin,
  5819. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  5820. backgroundColor:Color.Transparent,
  5821. title: { title: '详情信息' }
  5822. })
  5823. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5824. .onClick(() => {
  5825. if(this.isGridMusic||this.twoFingerType==4){
  5826. this.longItemFilePathDetail = item.filePath
  5827. }else{
  5828. this.isShowDetail = !this.isShowDetail
  5829. }
  5830. })
  5831. MenuItem({
  5832. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  5833. content: $r('app.string.share')
  5834. })
  5835. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5836. .onClick(() => {
  5837. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  5838. this.longItemFilePath = ''
  5839. })
  5840. }
  5841. .font({ size: 14, weight: FontWeight.Normal })
  5842. }
  5843. .width(180)
  5844. }
  5845. .height('auto')
  5846. .enableScrollInteraction(true)
  5847. .scrollBar(this.isGridMusic?BarState.On:BarState.Off)
  5848. }
  5849. }
  5850. private listMaxScrollOffsetY: number = 0
  5851. @State selectedIndex: number = -1
  5852. setlistTwoFingers() {
  5853. this.pinchValue = this.scaleValue;
  5854. Logger.info('this.pinchValue = ' + this.pinchValue);
  5855. if (this.pinchValue >= 1) {
  5856. this.twoFingerType++
  5857. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  5858. if (this.twoFingerType > 3) {
  5859. this.twoFingerType = 1
  5860. this.isGridMusic = true
  5861. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5862. }
  5863. } else {
  5864. this.twoFingerType--
  5865. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  5866. if (this.twoFingerType < 1) {
  5867. this.twoFingerType = 4
  5868. this.columns = 1
  5869. }
  5870. }
  5871. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5872. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5873. this.pinchValue = 1;
  5874. this.scaleValue = 1;
  5875. }
  5876. @Builder
  5877. getList(){
  5878. Stack() {
  5879. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  5880. this.getListView()
  5881. }
  5882. .pullDownRatio(this.ratioL)
  5883. .pullToRefresh(true)
  5884. .refreshOffset(0)
  5885. .onOffsetChange((offset: number) => {
  5886. // 越接近最大距离,下拉跟手系数越小。
  5887. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  5888. })
  5889. .onStateChange((refreshStatus: RefreshStatus) => {
  5890. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  5891. })
  5892. .onRefreshing(async () => {
  5893. if(this.modeType==0){
  5894. this.getHistoryList(false)
  5895. this.asyncCurrentPathOnlyFile()
  5896. }else if(this.modeType == 1){
  5897. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  5898. }else if(this.modeType == 2){
  5899. workerInstance.postMessage({ code: 3, data: this.context });
  5900. }else if(this.modeType == 3){
  5901. workerInstance.postMessage({ code: 4, data: this.context });
  5902. }else if(this.modeType == 4){
  5903. this.doSongListTask()
  5904. }
  5905. console.log('onRefreshing test');
  5906. })
  5907. }
  5908. }
  5909. // 扫描当前目录下的文件,不扫描子目录
  5910. asyncCurrentPathOnlyFile(){
  5911. if(this.modeType==0){
  5912. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  5913. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  5914. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  5915. if(this.modeType==0){
  5916. setTimeout(()=>{
  5917. this.isRefreshing =false
  5918. this.deleteCache(this.currentPath)
  5919. this.getSortedFiles(this.currentPath)
  5920. },500)
  5921. }
  5922. }).catch((e:object)=>{
  5923. this.isRefreshing =false
  5924. console.info("onecold task1 catch e: " + e);
  5925. })
  5926. }
  5927. }
  5928. @Builder
  5929. getListView() {
  5930. List({ scroller: this.listScroller }) {
  5931. // ListItemGroup({ header: this.coverHeader() }) {
  5932. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5933. ListItem() {
  5934. Column() {
  5935. if (item.type === CommonConstants.TYPE_IS_DIR
  5936. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  5937. this.DirItem(item, index)
  5938. } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
  5939. } else {
  5940. this.MusicItem(item, index)
  5941. }
  5942. }
  5943. .shadow(this.scaleItem === index ? {
  5944. radius: 70,
  5945. color: '#15000000',
  5946. offsetX: 0,
  5947. offsetY: 0
  5948. } :
  5949. {
  5950. radius: 0,
  5951. color: '#15000000',
  5952. offsetX: 0,
  5953. offsetY: 0
  5954. })
  5955. .animation({ curve: Curve.Sharp, duration: 300 })
  5956. }
  5957. // .transition(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }))
  5958. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.9, y: 0.9 })
  5959. .animation({ duration: 500 }),
  5960. TransitionEffect.scale({ x: 0, y: 0 })))
  5961. .clickEffect({ level: ClickEffectLevel.LIGHT })
  5962. .swipeAction((
  5963. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  5964. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  5965. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  5966. start:null,edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  5967. .onClick(() => {
  5968. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5969. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5970. this.handleFileSelection(item, !isChecked);
  5971. } else {
  5972. this.doPlay(item, index)
  5973. }
  5974. })
  5975. //拖动List关键代码开始
  5976. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  5977. .zIndex(this.dragItem === index ? 1 : 0)
  5978. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  5979. .gesture(
  5980. GestureGroup(GestureMode.Sequence,
  5981. LongPressGesture({ repeat: true })
  5982. .onAction((event?: GestureEvent) => {
  5983. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5984. this.scaleItem = index
  5985. })
  5986. })
  5987. .onActionEnd(() => {
  5988. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5989. this.scaleItem = -1
  5990. })
  5991. }),
  5992. PanGesture({ fingers: 1, direction: null, distance: 0 })
  5993. .onActionStart(() => {
  5994. this.dragItem = index // 记录当前拖动项索引
  5995. this.dragRefOffset = 0 // 重置偏移基准
  5996. })
  5997. .onActionUpdate((event: GestureEvent) => {
  5998. this.offsetY = event.offsetY - this.dragRefOffset;
  5999. this.neighborItem = -1;
  6000. let indexA = this.videoLocalList.indexOf(item);
  6001. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  6002. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  6003. let value: number = 0;
  6004. if (this.offsetY < 0) {
  6005. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  6006. this.neighborItem = indexA - 1;
  6007. this.neighborScale = 1 - value / 20;
  6008. } else if (this.offsetY > 0) {
  6009. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  6010. this.neighborItem = indexA + 1;
  6011. this.neighborScale = 1 - value / 20;
  6012. }
  6013. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  6014. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6015. this.offsetY -= this.ITEM_INTV;
  6016. this.dragRefOffset += this.ITEM_INTV;
  6017. this.itemMove(indexA, indexA + 1);
  6018. });
  6019. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  6020. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6021. this.offsetY += this.ITEM_INTV;
  6022. this.dragRefOffset -= this.ITEM_INTV;
  6023. this.itemMove(indexA, indexA - 1);
  6024. });
  6025. }
  6026. let curListOffset = this.listScroller.currentOffset()
  6027. // 获取手指信息
  6028. let fingerInfo = event.fingerList[0]
  6029. let clickPercentY =
  6030. (fingerInfo.globalY - Number(this.listArea.globalPosition.y)) / Number(this.listArea.height)
  6031. if (clickPercentY > 0.8 && !this.listScroller.isAtEnd()) {
  6032. let scrollVelocity = clickPercentY > 0.9 ? 4 : 2
  6033. if (this.listMaxScrollOffsetY - curListOffset.yOffset > scrollVelocity + 5) {
  6034. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset += scrollVelocity })
  6035. }
  6036. } else if (clickPercentY < 0.2 && curListOffset.yOffset >= 0) {
  6037. let scrollVelocity = clickPercentY < 0.1 ? 4 : 2
  6038. if (curListOffset.yOffset > scrollVelocity + 5) {
  6039. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset -= scrollVelocity })
  6040. }
  6041. }
  6042. })
  6043. .onActionEnd((event: GestureEvent) => {
  6044. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6045. this.dragItem = -1
  6046. this.neighborItem = -1
  6047. })
  6048. animateTo({
  6049. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  6050. }, () => {
  6051. this.scaleItem = -1
  6052. })
  6053. })
  6054. )
  6055. .onCancel(() => {
  6056. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6057. this.dragItem = -1
  6058. this.neighborItem = -1
  6059. })
  6060. animateTo({
  6061. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  6062. }, () => {
  6063. this.scaleItem = -1
  6064. })
  6065. })
  6066. ) //拖动List关键代码结束
  6067. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  6068. // }
  6069. }
  6070. .onScrollStart(() => {
  6071. this.isScrolling = true
  6072. this.isShowAlphaBet = true
  6073. })
  6074. .onScrollIndex((start: number,center:number,end:number) => {
  6075. this.selectedIndex = start
  6076. if(start >= 0 && start < this.videoLocalList.length){
  6077. this.selectAlphaBetIndex = this.findAlphaBetIndex(this.videoLocalList[start])
  6078. }
  6079. })
  6080. .onScrollStop(() => {
  6081. if(this.isScrolling){
  6082. this.isScrolling = false
  6083. }
  6084. this.isShowAlphaBet = false
  6085. })
  6086. .scrollBar(BarState.Off)
  6087. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  6088. .gesture(PinchGesture({ fingers: 2 })
  6089. .onActionEnd((event: GestureEvent) => {
  6090. this.setlistTwoFingers()
  6091. })
  6092. .onActionUpdate(e => {
  6093. this.scaleValue = this.pinchValue * e.scale
  6094. })
  6095. .onActionStart(e => {
  6096. }))
  6097. .contentStartOffset(this.topSafeHeight + 55)
  6098. .scrollBar(BarState.Off)
  6099. .contentEndOffset(this.bottomBarHeight+this.bottomSafeHeight)
  6100. .cachedCount(10)
  6101. // .reuseId('list_item')
  6102. .borderRadius(20)
  6103. .layoutWeight(1)
  6104. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  6105. .lanes(
  6106. new BreakpointType<number>({
  6107. sm: 1,
  6108. md: 2,
  6109. lg: 2,
  6110. xl: 3,
  6111. xxl: 4
  6112. }).getValue(this.currentBreakpoint),
  6113. new BreakpointType<number>({
  6114. sm: 0,
  6115. md: 12,
  6116. lg: 12,
  6117. xl: 16,
  6118. xxl: 20
  6119. }).getValue(this.currentBreakpoint)
  6120. )
  6121. .onAreaChange((oldValue: Area, newValue: Area) => {
  6122. this.listArea = newValue
  6123. if (this.twoFingerType == 3) {
  6124. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  6125. } else if (this.twoFingerType == 2) {
  6126. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  6127. } else if (this.twoFingerType == 1) {
  6128. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  6129. }
  6130. })
  6131. .onScrollFrameBegin((offset: number) => {
  6132. // 获取当前滚动偏移量
  6133. if(this.autoHideTitle){
  6134. const currentOffsetY = this.listScroller.currentOffset().yOffset;
  6135. // 判断滚动方向
  6136. if (currentOffsetY > this.prevOffsetY) {
  6137. // console.log("onecold 向上滚动");
  6138. this.isShowTitleBar = false
  6139. } else if (currentOffsetY < this.prevOffsetY) {
  6140. // console.log("onecold 向下滚动");
  6141. this.isShowTitleBar = true
  6142. }
  6143. // 更新前一次偏移量
  6144. this.prevOffsetY = currentOffsetY;
  6145. }
  6146. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  6147. // if (this.isPhoneLan()) {
  6148. // this.setBarHeightHide(offset)
  6149. // } else
  6150. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  6151. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  6152. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  6153. if (this.isScrollHide) {
  6154. this.setBarHeightHide2(offset)
  6155. } else {
  6156. this.setBarHeightNormal()
  6157. }
  6158. } else {
  6159. this.setBarHeightHide(offset)
  6160. }
  6161. return { offsetRemain: offset };
  6162. })
  6163. }
  6164. setBarHeightNormal() {
  6165. this.hideDone = false;
  6166. this.getUIContext().animateTo({
  6167. duration: 300
  6168. }, () => {
  6169. this.bottomBarHeight = 68 + 0;
  6170. this.topBarHeight = 50 + 0;
  6171. this.barOpacity = 1;
  6172. this.barBottomOpacity = 1
  6173. this.currentYOffset = 0;
  6174. this.isHiding = false;
  6175. });
  6176. }
  6177. setBarHeightHide(offset: number) {
  6178. if (offset > 0 && !this.hideDone) {
  6179. this.currentYOffset += offset;
  6180. if (this.currentYOffset <= 100) {
  6181. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  6182. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  6183. this.barOpacity = 1 - this.currentYOffset / 100;
  6184. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  6185. } else {
  6186. this.topBarHeight = 0;
  6187. this.bottomBarHeight = 0;
  6188. this.barBottomOpacity = 0
  6189. this.barOpacity = 0;
  6190. this.hideDone = true;
  6191. }
  6192. this.isHiding = true;
  6193. }
  6194. if (offset < 0 && this.isHiding) {
  6195. this.hideDone = false;
  6196. this.getUIContext().animateTo({
  6197. duration: 300
  6198. }, () => {
  6199. this.bottomBarHeight = 68 + 0;
  6200. this.topBarHeight = 50 + 0;
  6201. this.barOpacity = 1;
  6202. this.barBottomOpacity = 1
  6203. this.currentYOffset = 0;
  6204. this.isHiding = false;
  6205. });
  6206. }
  6207. }
  6208. //这个方法没隐藏bottomBar,只隐藏topbar
  6209. setBarHeightHide2(offset: number) {
  6210. if (offset > 0 && !this.hideDone) {
  6211. this.currentYOffset += offset;
  6212. if (this.currentYOffset <= 100) {
  6213. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  6214. this.barOpacity = 1 - this.currentYOffset / 100;
  6215. } else {
  6216. this.topBarHeight = 0;
  6217. this.barOpacity = 0;
  6218. this.hideDone = true;
  6219. }
  6220. this.isHiding = true;
  6221. }
  6222. if (offset < 0 && this.isHiding) {
  6223. this.hideDone = false;
  6224. this.getUIContext().animateTo({
  6225. duration: 300
  6226. }, () => {
  6227. this.topBarHeight = 50 + 0;
  6228. this.barOpacity = 1;
  6229. this.currentYOffset = 0;
  6230. this.isHiding = false;
  6231. });
  6232. }
  6233. }
  6234. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  6235. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  6236. switch (item.type) {
  6237. case CommonConstants.TYPE_IS_DIR:
  6238. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  6239. let offsetB = 0
  6240. if(this.twoFingerType==4){
  6241. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6242. let cur = this.waterScroller.currentOffset()
  6243. if (cur && typeof cur.yOffset === 'number') {
  6244. offsetB = cur.yOffset
  6245. }
  6246. }
  6247. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  6248. }else
  6249. if (this.isGridMusic) {
  6250. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6251. let cur = this.scroller.currentOffset()
  6252. if (cur && typeof cur.yOffset === 'number') {
  6253. offsetB = cur.yOffset
  6254. }
  6255. }
  6256. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  6257. } else {
  6258. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6259. let cur = this.listScroller.currentOffset()
  6260. if (cur && typeof cur.yOffset === 'number') {
  6261. offsetB = cur.yOffset
  6262. }
  6263. }
  6264. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  6265. }
  6266. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  6267. this.showVerifyDialog()
  6268. this.currentTitleName = '私密音频'
  6269. this.currentTitleCover = $r('app.media.alt')
  6270. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  6271. this.titleName = '最近播放'
  6272. this.currentTitleCover = $r('app.media.alt')
  6273. this.currentTitleName = '最近播放'
  6274. //加载动画效果
  6275. this.updateListData(this.historyList, true)
  6276. // this.videoLocalList = this.historyList
  6277. if (ArrayUtil.isEmpty(this.historyList)) {
  6278. ToastUtil.showToast('最近播放记录空空如也')
  6279. } else {
  6280. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  6281. }
  6282. this.isHistory = true
  6283. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  6284. this.titleName = '我的收藏'
  6285. this.currentTitleName = '我的收藏'
  6286. this.currentTitleCover = $r('app.media.alt')
  6287. //加载动画效果
  6288. this.updateListData(this.favList)
  6289. if (ArrayUtil.isEmpty(this.favList)) {
  6290. ToastUtil.showToast('无音乐收藏记录')
  6291. } else {
  6292. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  6293. }
  6294. this.isFavMusic = true
  6295. } else {
  6296. this.currentTitleName = item.name
  6297. this.currentPath = item.filePath
  6298. this.currentTitleCover = $r('app.media.alt')
  6299. this.getSortedFiles(this.currentPath)
  6300. }
  6301. //进入歌单的时候的滚动位置在顶部
  6302. if(this.twoFingerType==4){
  6303. setTimeout(() => {
  6304. this.waterScroller.scrollEdge(Edge.Top)
  6305. this.scroller.scrollEdge(Edge.Top)
  6306. }, 380)
  6307. }else{
  6308. if (this.isGridMusic) {
  6309. this.scroller.scrollEdge(Edge.Top)
  6310. }else{
  6311. this.listScroller.scrollEdge(Edge.Top)
  6312. }
  6313. }
  6314. this.rightTopImage = $r('sys.symbol.chevron_left')
  6315. break;
  6316. case CommonConstants.TYPE_IS_ARTIST:
  6317. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  6318. let offsetA = 0
  6319. if(this.twoFingerType==4){
  6320. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6321. let cur = this.waterScroller.currentOffset()
  6322. if (cur && typeof cur.yOffset === 'number') {
  6323. offsetA = cur.yOffset
  6324. }
  6325. }
  6326. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  6327. }else
  6328. if (this.isGridMusic) {
  6329. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6330. let cur = this.scroller.currentOffset()
  6331. if (cur && typeof cur.yOffset === 'number') {
  6332. offsetA = cur.yOffset
  6333. }
  6334. }
  6335. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  6336. } else {
  6337. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6338. let cur = this.listScroller.currentOffset()
  6339. if (cur && typeof cur.yOffset === 'number') {
  6340. offsetA = cur.yOffset
  6341. }
  6342. }
  6343. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  6344. }
  6345. let mList = this.artistMap.get(item.name)
  6346. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  6347. Utility.doSortListAscending(mList)
  6348. this.isCanBack = true
  6349. this.titleName = item.name
  6350. this.currentTitleName = '艺术家:' + item.name
  6351. if (item.pixelMapPath) {
  6352. this.currentTitleCover = item.pixelMapPath
  6353. }
  6354. this.updateListData(mList)
  6355. }
  6356. this.rightTopImage = $r('sys.symbol.chevron_left')
  6357. //进入歌单的时候的滚动位置在顶部
  6358. if(this.twoFingerType==4){
  6359. setTimeout(() => {
  6360. this.waterScroller.scrollEdge(Edge.Top)
  6361. this.scroller.scrollEdge(Edge.Top)
  6362. }, 380)
  6363. }else{
  6364. if (this.isGridMusic) {
  6365. this.scroller.scrollEdge(Edge.Top)
  6366. }else{
  6367. this.listScroller.scrollEdge(Edge.Top)
  6368. }
  6369. }
  6370. break;
  6371. case CommonConstants.TYPE_IS_ALBUM:
  6372. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  6373. let offset = 0
  6374. if(this.twoFingerType==4){
  6375. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6376. let cur = this.waterScroller.currentOffset()
  6377. if (cur && typeof cur.yOffset === 'number') {
  6378. offset = cur.yOffset
  6379. }
  6380. }
  6381. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  6382. }else
  6383. if (this.isGridMusic) {
  6384. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6385. let cur = this.scroller.currentOffset()
  6386. if (cur && typeof cur.yOffset === 'number') {
  6387. offset = cur.yOffset
  6388. }
  6389. }
  6390. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  6391. } else {
  6392. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6393. let cur = this.listScroller.currentOffset()
  6394. if (cur && typeof cur.yOffset === 'number') {
  6395. offset = cur.yOffset
  6396. }
  6397. }
  6398. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  6399. }
  6400. let albumList = this.albumMap.get(item.name)
  6401. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  6402. Utility.doSortListAscending(albumList)
  6403. this.isCanBack = true
  6404. this.titleName = item.name
  6405. this.currentTitleName = '专辑:' + item.name
  6406. if (item.pixelMapPath) {
  6407. this.currentTitleCover = item.pixelMapPath
  6408. }
  6409. this.updateListData(albumList)
  6410. this.mScrollMap.set(item.name, this.selectedIndex)
  6411. this.rightTopImage = $r('sys.symbol.chevron_left')
  6412. }
  6413. //进入歌单的时候的滚动位置在顶部
  6414. if(this.twoFingerType==4){
  6415. setTimeout(() => {
  6416. this.waterScroller.scrollEdge(Edge.Top)
  6417. this.scroller.scrollEdge(Edge.Top)
  6418. }, 380)
  6419. }else{
  6420. if (this.isGridMusic) {
  6421. this.scroller.scrollEdge(Edge.Top)
  6422. }else{
  6423. this.listScroller.scrollEdge(Edge.Top)
  6424. }
  6425. }
  6426. break;
  6427. case CommonConstants.TYPE_IS_CSJAD:
  6428. return
  6429. break;
  6430. case CommonConstants.TYPE_LOCAL:
  6431. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  6432. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  6433. const cueTracks:CueTrack[] = cueinfo.tracks
  6434. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  6435. if(ArrayUtil.isNotEmpty(cueTracks)){
  6436. this.showCueDialog(cueTracks,cueinfo)
  6437. }
  6438. // this.showCueSheet = !this.showCueSheet
  6439. return
  6440. }
  6441. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6442. this.stop();
  6443. }
  6444. if (isOpen) {
  6445. this.currentSong = item
  6446. if (index !== undefined) {
  6447. this.curIndex = index
  6448. }
  6449. this.songList = []
  6450. this.songList.push(item)
  6451. this.sonDataSource.pushArrayData(this.songList)
  6452. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  6453. this.currentSong = item
  6454. if (index !== undefined) {
  6455. this.curIndex = index
  6456. }
  6457. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  6458. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  6459. }else {
  6460. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  6461. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  6462. this.songList = globalVideoList
  6463. this.sonDataSource.pushArrayData(this.songList)
  6464. this.currentSong = globalVideoList[this.curIndex]
  6465. }
  6466. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  6467. this.videoUrl = this.currentSong.filePath
  6468. this.name = this.currentSong.name
  6469. this.cover = this.currentSong.pixelMapPath
  6470. this.artist = this.currentSong.artist
  6471. LogUtil.info('onecold this.currentSong.cover =' + this.currentSong.pixelMapPath)
  6472. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  6473. this.startPlayOrResumePlay()
  6474. break;
  6475. case CommonConstants.TYPE_WEBDAV:
  6476. case CommonConstants.TYPE_SMB:
  6477. case CommonConstants.TYPE_NAVIDROME:
  6478. case CommonConstants.TYPE_FTP:
  6479. case CommonConstants.TYPE_BAIDU:
  6480. // 处理网络音频播放(WebDAV/SMB)
  6481. Logger.info(`heanup 处理云端音频播放: ${item.name}, URL: ${item.filePath}`)
  6482. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6483. this.stop();
  6484. }
  6485. if (isOpen) {
  6486. this.currentSong = item
  6487. if (index !== undefined) {
  6488. this.curIndex = index
  6489. }
  6490. this.songList = []
  6491. this.songList.push(item)
  6492. this.sonDataSource.pushArrayData(this.songList)
  6493. } else if (isFromSonPlayList) {
  6494. // 点击来自右下角的播放列表
  6495. this.currentSong = item
  6496. if (index !== undefined) {
  6497. this.curIndex = index
  6498. }
  6499. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  6500. Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  6501. } else {
  6502. // 从全局网络音频列表中查找
  6503. let globalVideoList = this.videoLocalList.filter(video => isRemoteCloudType(video.type)) as VideoItem[];
  6504. this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
  6505. if (this.curIndex === -1 && index !== undefined) {
  6506. this.curIndex = index;
  6507. }
  6508. this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
  6509. this.currentSong = this.songList[this.curIndex];
  6510. this.sonDataSource.pushArrayData(this.songList)
  6511. }
  6512. await this.hydrateRemoteSongFromDb(this.currentSong);
  6513. await this.hydrateRemoteSongFromDb(this.currentSong);
  6514. AppStorage.setOrCreate('currentSong', this.currentSong);
  6515. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  6516. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  6517. context: this.context,
  6518. autoParseMusicName: this.autoParseMusicName
  6519. });
  6520. Logger.info(TAG, `WebDAV URL同步构建完成(分支2): ${this.videoUrl}`);
  6521. this.name = this.currentSong.name
  6522. this.cover = this.currentSong.pixelMapPath
  6523. this.artist = this.currentSong.artist
  6524. Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 完整URL: ${this.videoUrl}`)
  6525. this.startPlayOrResumePlay()
  6526. break;
  6527. }
  6528. }
  6529. private cueComponentId: number = 0
  6530. //显示cue分轨列表对话框
  6531. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  6532. this.getUIContext().getPromptAction().openCustomDialog({
  6533. builder: () => {
  6534. this.cueComptentBuilder(cueTracks,cueinfo)
  6535. },
  6536. isModal:true,
  6537. showInSubWindow:false,
  6538. maskColor: Color.Transparent,
  6539. dialogTransition: // 设置弹窗内容显示的过渡效果
  6540. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  6541. .animation({ duration: 600, curve: Curve.Smooth }),
  6542. maskTransition: // 设置蒙层显示的过渡效果
  6543. TransitionEffect.opacity(0.5)
  6544. .animation({ duration: 600, curve: Curve.Smooth })
  6545. }).then((dialogId: number) => {
  6546. this.cueComponentId = dialogId
  6547. })
  6548. .catch((error: BusinessError) => {
  6549. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  6550. })
  6551. }
  6552. @Builder
  6553. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  6554. CueComptent({
  6555. title:cueinfo.title,
  6556. cueTracks:cueTracks,
  6557. isLongNameRoLL:this.isLongNameRoLL,
  6558. onCancel:()=>{
  6559. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  6560. },
  6561. onDoItemClick: async (item: CueTrack, index: number)=>{
  6562. //获取cueinfo对应的filePath
  6563. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  6564. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  6565. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  6566. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  6567. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  6568. if (this.currentSong){
  6569. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6570. this.stop();//播放之前先停止之前播放。
  6571. }
  6572. this.songList = globalVideoList
  6573. this.sonDataSource.pushArrayData(this.songList)
  6574. if (this.currentSong) {
  6575. try {
  6576. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  6577. context: this.context,
  6578. autoParseMusicName: this.autoParseMusicName
  6579. });
  6580. } catch (error) {
  6581. Logger.error(TAG, `CUE 点播构建播放地址失败: ${(error as Error).message}`);
  6582. this.videoUrl = this.currentSong.filePath;
  6583. }
  6584. }
  6585. this.name = item.title||this.currentSong.name
  6586. this.cover = this.currentSong.pixelMapPath
  6587. this.artist = item.performer||this.currentSong.artist
  6588. this.currentSong.name = this.name
  6589. this.currentSong.artist = this.artist
  6590. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  6591. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  6592. }
  6593. }
  6594. })
  6595. }
  6596. @State isFrontWhite: boolean = false
  6597. setShowPlayTrue(){
  6598. this.getUIContext()?.animateTo({
  6599. duration: 500,
  6600. curve: Curve.Friction
  6601. }, () => {
  6602. this.isShowPlay = true;
  6603. });
  6604. }
  6605. setShowPlayFalse(){
  6606. this.getUIContext()?.animateTo({
  6607. duration: 500,
  6608. curve: Curve.Friction
  6609. }, () => {
  6610. this.isShowPlay = false;
  6611. });
  6612. }
  6613. //打开播放页
  6614. showPlayerView() {
  6615. console.info('onecold showPlayerView this.songList'+ JSON.stringify(this.songList))
  6616. if (ArrayUtil.isNotEmpty(this.songList)) {
  6617. // this.setShowPlayTrue()
  6618. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  6619. this.initLyric(lyricPath);
  6620. this.startAutoHide();
  6621. } else {
  6622. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  6623. }
  6624. }
  6625. //打开播放列表
  6626. openPlayList(){
  6627. if (ArrayUtil.isNotEmpty(this.songList)) {
  6628. this.isShowSheet = !this.isShowSheet;
  6629. this.isFrontWhite = false
  6630. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  6631. this.scrollIndex()
  6632. } else {
  6633. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6634. }
  6635. }
  6636. scrollIndex(){
  6637. try {
  6638. setTimeout(() => {
  6639. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  6640. if(this.curIndex>60){
  6641. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  6642. }else{
  6643. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  6644. }
  6645. })
  6646. }, 123)
  6647. }catch (error) {
  6648. console.error(`onecold scrollIndex出错: ${error}`);
  6649. }
  6650. }
  6651. //播放列表布局
  6652. @Builder
  6653. PlayListSheet() {
  6654. Column() {
  6655. this.PlayList()
  6656. }
  6657. .width('100%')
  6658. .height('100%')
  6659. }
  6660. @State titleStr: string = ''
  6661. @State ablumStr: string = ''
  6662. @State artistStr: string = ''
  6663. @State lyricConStr: string = ''
  6664. @State currentEditItem: string = ''
  6665. @State yearStr: string = ''
  6666. @State trackStr: string = ''
  6667. @State genreStr: string = ''
  6668. @State imagePathStr: string = ''
  6669. @State albumArtistStr: string = ''
  6670. @State composerStr: string = ''
  6671. @State lyricistStr: string = ''
  6672. @State commentStr: string = ''
  6673. @State discStr: string = ''
  6674. doUpdateData() {
  6675. setTimeout(() => {
  6676. if (this.modeType === 0) {
  6677. this.deleteCache(this.currentPath)
  6678. this.getSortedFiles(this.currentPath)
  6679. }else if (this.modeType === 1){
  6680. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6681. }
  6682. }, 500)
  6683. }
  6684. doAllUpdateData() {
  6685. setTimeout(() => {
  6686. if (this.modeType === 0) {
  6687. this.deleteCache(this.currentPath)
  6688. this.getSortedFiles(this.currentPath)
  6689. }
  6690. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6691. workerInstance.postMessage({ code: 3, data: this.context });
  6692. workerInstance.postMessage({ code: 4, data: this.context });
  6693. }, 999)
  6694. }
  6695. //编辑信息
  6696. async doEdit(item: VideoItem) {
  6697. if (!item) {
  6698. return
  6699. }
  6700. if (StrUtil.isEmpty(this.titleStr)) {
  6701. ToastUtil.showToast('标题不能为空')
  6702. return
  6703. }
  6704. //内嵌音乐标签不能开启监听
  6705. // this.deletionWatcher?.stop();
  6706. DialogHelper.showLoadingDialog()
  6707. await PermissionUtil.activatePermission(item.filePath)
  6708. let tempOutPath = ''
  6709. // 如果不是 packName 包下的文件,则直接路径用this.currentPath
  6710. if(!item.filePath.toLowerCase().includes(this.packName)){
  6711. tempOutPath = this.currentPath + '/' + item.fileName
  6712. }
  6713. console.info('onecold tempOutPath ='+tempOutPath)
  6714. //用户更改了封面,那就内嵌下封面
  6715. if(StrUtil.isNotEmpty(this.imagePathStr)){
  6716. const resultCover:boolean = await changeMusicCover(this.context,
  6717. item.filePath,this.imagePathStr,true,tempOutPath);
  6718. this.imagePathStr = ''
  6719. if(resultCover){
  6720. ToastUtil.showToast('内嵌封面成功')
  6721. }
  6722. }
  6723. const metadata:FFMpegTags = {
  6724. title: this.titleStr,
  6725. artist: this.artistStr,
  6726. album: this.ablumStr,
  6727. TYER:this.yearStr,
  6728. genre:this.genreStr,
  6729. track:this.trackStr,
  6730. album_artist:this.albumArtistStr,
  6731. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  6732. COMPOSER:this.composerStr,
  6733. lyricist:this.lyricistStr,
  6734. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  6735. comment:this.commentStr,
  6736. disc:this.discStr,
  6737. };
  6738. let newInput = item.filePath
  6739. //内嵌标签歌路径如果不是包含包名,输入newInput要赋值tempOutPath,然后tempOutPath为空
  6740. if(!item.filePath.toLowerCase().includes(this.packName)&&FileUtil.accessSync(tempOutPath)){
  6741. newInput = tempOutPath
  6742. tempOutPath = ''
  6743. }
  6744. const isWav:boolean = newInput.toLowerCase().endsWith('.wav');
  6745. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  6746. const result:boolean = await repairAudioMetadata(
  6747. newInput,
  6748. this.lyricConStr,
  6749. metadata,
  6750. true,
  6751. tempOutPath
  6752. );
  6753. if (result||isWav) {
  6754. if(!item.filePath.includes(this.packName)){
  6755. //内嵌成功的歌路径如果不是包含包名,则要入库
  6756. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newInput,
  6757. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  6758. this.table.insert(newItem, (id: number) => {
  6759. //加入数据库
  6760. if(this.modeType==0){
  6761. this.deleteCache(this.currentPath)
  6762. this.getSortedFiles(this.currentPath)
  6763. }
  6764. });
  6765. }
  6766. const task = new taskpool.Task(
  6767. updateInfoDb,
  6768. this.context,
  6769. item.filePath,
  6770. this.titleStr,
  6771. this.artistStr,
  6772. this.ablumStr,
  6773. this.lyricConStr,
  6774. this.yearStr,this.genreStr,
  6775. this.trackStr,this.albumArtistStr,
  6776. this.composerStr, this.lyricistStr,
  6777. this.commentStr,this.discStr
  6778. );
  6779. taskpool.execute(task, taskpool.Priority.HIGH).then((result) => {
  6780. if (result) {
  6781. console.log(" onecold 编辑信息成功,数据库已同步");
  6782. if(isWav){
  6783. ToastUtil.showToast('wav格式有可能内嵌失败,但是编辑信息成功')
  6784. }else{
  6785. ToastUtil.showToast('内嵌音乐标签成功')
  6786. }
  6787. this.isShowMoreView = false
  6788. this.name = this.titleStr
  6789. this.syncEditedFields(item)
  6790. if (item.filePath == this.currentSong?.filePath) {
  6791. this.currentSong.name = this.titleStr
  6792. this.artist = this.artistStr
  6793. this.currentSong.artist = this.artistStr
  6794. this.currentSong.album = this.ablumStr
  6795. this.currentSong.year = this.yearStr
  6796. this.currentSong.genre = this.genreStr
  6797. this.currentSong.track = this.trackStr
  6798. this.currentSong.lyricContent = this.lyricConStr
  6799. this.currentSong.ALBUMARTIST = this.albumArtistStr
  6800. this.currentSong.COMPOSER = this.composerStr
  6801. this.currentSong.LYRICIST = this.lyricistStr
  6802. this.currentSong.COMMENT = this.commentStr
  6803. }
  6804. this.syncListsAfterEdit(item.filePath)
  6805. this.doUpateEditedFields(item)
  6806. //this.doUpdateData()
  6807. } else {
  6808. // ToastUtil.showToast('保存失败' + error?.toString())
  6809. console.error(" onecold 编辑信息数据库失败 ");
  6810. }
  6811. // 关闭进度条
  6812. DialogHelper.closeLoading();
  6813. }).catch((error: Error) => {
  6814. // 关闭进度条
  6815. DialogHelper.closeLoading();
  6816. console.error('onecold Subtitle sync failed:', error);
  6817. });
  6818. console.log(' onecold 元数据标签更新成功,');
  6819. } else {
  6820. // 关闭进度条
  6821. DialogHelper.closeLoading();
  6822. ToastUtil.showToast('内嵌音乐标签失败')
  6823. console.log('onecold 内嵌音乐标签失败');
  6824. }
  6825. this.longItemFilePath = ''
  6826. this.tempLyricContent = ''
  6827. this.isShowEdit = false
  6828. }
  6829. // 内嵌标签更新当前内嵌的Item
  6830. async doUpateEditedFields(item: VideoItem) {
  6831. // 找到当前项在 videoLocalList 中的索引
  6832. const index = this.videoLocalList.findIndex(video => video.filePath === item.filePath);
  6833. if (index !== -1) {
  6834. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  6835. const updatedItem = await this.table.queryVideoByFilePath(item.filePath)
  6836. // 只有当查询结果不为 null 时才更新列表
  6837. if (updatedItem !== null) {
  6838. // 更新 videoLocalList 中的项(通过创建新数组触发响应式更新)
  6839. this.videoLocalList = [
  6840. ...this.videoLocalList.slice(0, index),
  6841. updatedItem,
  6842. ...this.videoLocalList.slice(index + 1)
  6843. ];
  6844. // 同步更新 LazyDataSource
  6845. this.dataSource.pushArrayData(this.videoLocalList)
  6846. } else {
  6847. ToastUtil.showToast('未找到更新的数据');
  6848. }
  6849. }
  6850. DialogHelper.closeLoading();
  6851. }
  6852. @Builder
  6853. editSheet(item: VideoItem) {
  6854. Scroll() {
  6855. Column() {
  6856. this.editDetail(item)
  6857. }
  6858. }
  6859. .width('100%')
  6860. .height('100%')
  6861. }
  6862. @Builder
  6863. editDetail(item: VideoItem) {
  6864. Column() {
  6865. if (item) {
  6866. Row() {
  6867. Stack() {
  6868. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  6869. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  6870. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  6871. item.pixelMapPath)
  6872. .fillColor(this.themeColor)
  6873. .height(88)
  6874. .width(88)
  6875. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  6876. .borderRadius(12)
  6877. .clip(true)
  6878. .opacity(this.opacityItem)// 绑定透明度
  6879. .margin({ left: 25 })
  6880. }
  6881. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  6882. .onClick(async () => {
  6883. const imagePath:string | undefined = await this.goSelectImage(item);
  6884. if (imagePath) {
  6885. //用户更改过图片
  6886. this.imagePathStr = imagePath
  6887. }
  6888. })
  6889. .width('28%')
  6890. Row() {
  6891. Column() {
  6892. Text(item.name)
  6893. .fontSize(17)
  6894. .maxLines(1)
  6895. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6896. .animation({
  6897. duration: 555,
  6898. curve: 'Linear',
  6899. })
  6900. .fontColor(this.themeColor)
  6901. .margin({ left: 8 })
  6902. Row() {
  6903. Text(item.artist)
  6904. .fontSize(14)
  6905. .maxLines(1)
  6906. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6907. .padding({ top: 8 })
  6908. .fontColor(this.themeColor)
  6909. .margin({ left: 8 })
  6910. }
  6911. }
  6912. .height('100%')
  6913. .width(100)
  6914. .layoutWeight(1)
  6915. .justifyContent(FlexAlign.Center)
  6916. .alignItems(HorizontalAlign.Start)
  6917. Column() {
  6918. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6919. Row(){
  6920. SymbolGlyph($r('sys.symbol.picture'))
  6921. .fontSize(18)
  6922. .fontColor([Color.White])
  6923. Text('获取封面')
  6924. .margin({ left: 4 })
  6925. .fontSize(11)
  6926. .fontColor(Color.White)
  6927. .fontWeight(480)
  6928. .textAlign(TextAlign.Center)
  6929. }
  6930. .justifyContent(FlexAlign.Center)
  6931. }
  6932. .height(38)
  6933. .width(100)
  6934. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6935. .backgroundColor(this.themeColor)
  6936. .stateEffect(true)
  6937. .margin({ right: 35 })
  6938. .onClick(async () => {
  6939. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  6940. this.showTipsDialog();
  6941. return; // Return empty string when no API is configured
  6942. }
  6943. const imagePath:string | undefined = await this.doSearchCover(item,
  6944. this.titleStr,this.artistStr);
  6945. console.info('onecold imagePath = '+imagePath)
  6946. if (StrUtil.isNotEmpty(imagePath)) {
  6947. //用户更改过图片
  6948. this.imagePathStr = imagePath
  6949. ToastUtil.showToast('获取封面成功')
  6950. }else{
  6951. ToastUtil.showToast('获取封面失败,请重试')
  6952. }
  6953. })
  6954. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6955. Row(){
  6956. SymbolGlyph($r('sys.symbol.input_mode'))
  6957. .fontSize(18)
  6958. .fontColor([Color.White])
  6959. Text('获取歌词')
  6960. .margin({ left: 4 })
  6961. .fontSize(11)
  6962. .fontColor(Color.White)
  6963. .fontWeight(480)
  6964. .textAlign(TextAlign.Center)
  6965. }
  6966. .justifyContent(FlexAlign.Center)
  6967. }
  6968. .height(38)
  6969. .width(100)
  6970. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6971. .backgroundColor(this.themeColor)
  6972. .stateEffect(true)
  6973. .margin({ top: 9, right: 35 })
  6974. .onClick(async () => {
  6975. //判断有没有设置api
  6976. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  6977. if (StrUtil.isEmpty(apiUrl)) {
  6978. this.isLyricSetting = false
  6979. this.showTipsDialog()
  6980. return
  6981. }
  6982. let res: string | undefined = await getApiLyric(apiUrl,
  6983. this.titleStr, this.artistStr, false);
  6984. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  6985. this.lyricConStr = res;
  6986. ToastUtil.showToast('获取歌词成功')
  6987. }else{
  6988. ToastUtil.showToast('获取歌词失败,请重试')
  6989. }
  6990. })
  6991. }
  6992. .justifyContent(FlexAlign.Start)
  6993. }
  6994. .height('100%')
  6995. .justifyContent(FlexAlign.Start)
  6996. .layoutWeight(1)
  6997. }
  6998. .width('100%')
  6999. .height(98)
  7000. Row() {
  7001. Text('标题:')
  7002. .fontSize(14)
  7003. .fontColor($r('app.color.text_color'))
  7004. .margin({ left: 22 })
  7005. TextInput({ text: this.titleStr||item.name })
  7006. .height(40)
  7007. .maxLines(1)
  7008. .fontSize(14)
  7009. .layoutWeight(1)
  7010. .fontColor($r('app.color.text_color'))
  7011. .margin({ right: 15, left: 10 })
  7012. .onChange((val: string) => {
  7013. this.titleStr = val
  7014. })
  7015. Button('修复乱码',{ type: ButtonType.Capsule, stateEffect: true})
  7016. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7017. .backgroundColor(this.themeColor)
  7018. .fontSize(10)
  7019. .margin({ right: 20})
  7020. .onClick(async () => {
  7021. let hwTags = await extractHwMediaMetadata(item.filePath)
  7022. let artist = hwTags?.artist|| '';
  7023. let title = hwTags?.title|| '';
  7024. let album = hwTags?.album|| '';
  7025. console.info('onecold 乱码修正 artist='+artist);
  7026. console.info('onecold 乱码修正 title='+title);
  7027. console.info('onecold 乱码修正 album='+album);
  7028. this.titleStr = title;
  7029. this.artistStr = artist;
  7030. this.ablumStr = album;
  7031. })
  7032. }
  7033. .width('100%')
  7034. .margin({ top: 10, bottom: 10 })
  7035. .justifyContent(FlexAlign.Start)
  7036. Row() {
  7037. Text('艺术家:')
  7038. .fontSize(14)
  7039. .fontColor($r('app.color.text_color'))
  7040. .margin({ left: 22 })
  7041. TextInput({ text: this.artistStr||item.artist })
  7042. .height(40)
  7043. .maxLines(1)
  7044. .fontSize(14)
  7045. .layoutWeight(1)
  7046. .fontColor($r('app.color.text_color'))
  7047. .margin({ right: 20, left: 10 })
  7048. .onChange((val: string) => {
  7049. this.artistStr = val
  7050. })
  7051. }
  7052. .width('100%')
  7053. .margin({ top: 10, bottom: 10 })
  7054. .justifyContent(FlexAlign.Start)
  7055. Row() {
  7056. Text('专辑名:')
  7057. .fontSize(14)
  7058. .fontColor($r('app.color.text_color'))
  7059. .margin({ left: 22 })
  7060. TextInput({ text: this.ablumStr||item.album })
  7061. .height(40)
  7062. .maxLines(1)
  7063. .fontSize(14)
  7064. .layoutWeight(1)
  7065. .fontColor($r('app.color.text_color'))
  7066. .margin({ right: 20, left: 10 })
  7067. .onChange((val: string) => {
  7068. this.ablumStr = val
  7069. })
  7070. }
  7071. .width('100%')
  7072. .margin({ top: 10, bottom: 10 })
  7073. .justifyContent(FlexAlign.Start)
  7074. Row() {
  7075. Column(){
  7076. Column(){
  7077. Text('歌词:')
  7078. .fontSize(14)
  7079. .fontColor($r('app.color.text_color'))
  7080. .margin({ top:9,left: 22 })
  7081. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7082. SymbolGlyph($r('sys.symbol.trash_fill'))
  7083. .fontSize(25)
  7084. .alignSelf(ItemAlign.Center)
  7085. .margin({ left: 22,top:25})
  7086. }
  7087. .backgroundColor(Color.Transparent)
  7088. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7089. Visibility.None:Visibility.Visible)
  7090. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7091. .onClick(()=>{
  7092. this.lyricConStr = ''
  7093. this.lyricContent = ''
  7094. this.tempLyricContent = ''
  7095. })
  7096. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7097. SymbolGlyph($r('sys.symbol.plus'))
  7098. .fontSize(25)
  7099. .alignSelf(ItemAlign.Center)
  7100. .margin({ left: 22,top:25})
  7101. }
  7102. .backgroundColor(Color.Transparent)
  7103. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7104. .onClick( ()=>{
  7105. this.callFilePickerSelectFileForLyric()
  7106. })
  7107. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7108. SymbolGlyph($r('sys.symbol.traditional_square'))
  7109. .fontSize(25)
  7110. .alignSelf(ItemAlign.Center)
  7111. .margin({ left: 22,top:25})
  7112. }
  7113. .backgroundColor(Color.Transparent)
  7114. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7115. Visibility.None:Visibility.Visible)
  7116. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7117. .onClick( ()=>{
  7118. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  7119. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  7120. })
  7121. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7122. Image($r('app.media.jianti'))
  7123. .height(25)
  7124. .fillColor($r('app.color.text_color'))
  7125. .alignSelf(ItemAlign.Center)
  7126. .margin({ left: 22,top:25})
  7127. }
  7128. .backgroundColor(Color.Transparent)
  7129. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7130. Visibility.None:Visibility.Visible)
  7131. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7132. .onClick( ()=>{
  7133. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  7134. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  7135. })
  7136. }
  7137. .layoutWeight(1)
  7138. }
  7139. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  7140. this.tempLyricContent })
  7141. .type(TextAreaType.NORMAL)
  7142. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  7143. .fontSize(14)
  7144. .layoutWeight(1)
  7145. .fontColor($r('app.color.text_color'))
  7146. .margin({ right: 20, left: 10 })
  7147. .onChange((val: string) => {
  7148. this.lyricConStr = val
  7149. })
  7150. }
  7151. .width('100%')
  7152. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  7153. .margin({ top: 10, bottom: 10 })
  7154. .justifyContent(FlexAlign.Start)
  7155. Row() {
  7156. Text('年份:')
  7157. .fontSize(14)
  7158. .fontColor($r('app.color.text_color'))
  7159. .margin({ left: 22 })
  7160. TextInput({ text: item.year })
  7161. .height(40)
  7162. .maxLines(1)
  7163. .fontSize(14)
  7164. .type(InputType.Number)
  7165. .layoutWeight(1)
  7166. .fontColor($r('app.color.text_color'))
  7167. .margin({ right: 20, left: 10 })
  7168. .onChange((val: string) => {
  7169. this.yearStr = val
  7170. })
  7171. }
  7172. .width('100%')
  7173. .margin({ top: 10, bottom: 10 })
  7174. .justifyContent(FlexAlign.Start)
  7175. Row() {
  7176. Text('音轨号:')
  7177. .fontSize(14)
  7178. .fontColor($r('app.color.text_color'))
  7179. .margin({ left: 22 })
  7180. TextInput({ text:item.track=='未知'?'': item.track })
  7181. .height(40)
  7182. .maxLines(1)
  7183. .fontSize(14)
  7184. .type(InputType.Number)
  7185. .layoutWeight(1)
  7186. .fontColor($r('app.color.text_color'))
  7187. .margin({ right: 20, left: 10 })
  7188. .onChange((val: string) => {
  7189. this.trackStr = val
  7190. })
  7191. }
  7192. .width('100%')
  7193. .margin({ top: 10, bottom: 10 })
  7194. .justifyContent(FlexAlign.Start)
  7195. Row() {
  7196. Text('碟号:')
  7197. .fontSize(14)
  7198. .fontColor($r('app.color.text_color'))
  7199. .margin({ left: 22 })
  7200. TextInput({ text:item.disc })
  7201. .height(40)
  7202. .maxLines(1)
  7203. .fontSize(14)
  7204. .type(InputType.Number)
  7205. .layoutWeight(1)
  7206. .fontColor($r('app.color.text_color'))
  7207. .margin({ right: 20, left: 10 })
  7208. .onChange((val: string) => {
  7209. this.discStr = val
  7210. })
  7211. }
  7212. .width('100%')
  7213. .margin({ top: 10, bottom: 10 })
  7214. .justifyContent(FlexAlign.Start)
  7215. Row() {
  7216. Text('风格:')
  7217. .fontSize(14)
  7218. .fontColor($r('app.color.text_color'))
  7219. .margin({ left: 22 })
  7220. TextInput({ text: item.genre })
  7221. .height(40)
  7222. .maxLines(1)
  7223. .fontSize(14)
  7224. .layoutWeight(1)
  7225. .fontColor($r('app.color.text_color'))
  7226. .margin({ right: 20, left: 10 })
  7227. .onChange((val: string) => {
  7228. this.genreStr = val
  7229. })
  7230. }
  7231. .width('100%')
  7232. .margin({ top: 10, bottom: 10 })
  7233. .justifyContent(FlexAlign.Start)
  7234. Row() {
  7235. Text('专辑艺术家:')
  7236. .fontSize(14)
  7237. .fontColor($r('app.color.text_color'))
  7238. .margin({ left: 22 })
  7239. TextInput({ text: item.ALBUMARTIST })
  7240. .height(40)
  7241. .maxLines(1)
  7242. .fontSize(14)
  7243. .layoutWeight(1)
  7244. .fontColor($r('app.color.text_color'))
  7245. .margin({ right: 20, left: 10 })
  7246. .onChange((val: string) => {
  7247. this.albumArtistStr = val
  7248. })
  7249. }
  7250. .width('100%')
  7251. .margin({ top: 10, bottom: 10 })
  7252. .justifyContent(FlexAlign.Start)
  7253. Row() {
  7254. Text('作曲:')
  7255. .fontSize(14)
  7256. .fontColor($r('app.color.text_color'))
  7257. .margin({ left: 22 })
  7258. TextInput({ text: item.COMPOSER })
  7259. .height(40)
  7260. .maxLines(1)
  7261. .fontSize(14)
  7262. .layoutWeight(1)
  7263. .fontColor($r('app.color.text_color'))
  7264. .margin({ right: 20, left: 10 })
  7265. .onChange((val: string) => {
  7266. this.composerStr = val
  7267. })
  7268. }
  7269. .width('100%')
  7270. .margin({ top: 10, bottom: 10 })
  7271. .justifyContent(FlexAlign.Start)
  7272. Row() {
  7273. Text('作词:')
  7274. .fontSize(14)
  7275. .fontColor($r('app.color.text_color'))
  7276. .margin({ left: 22 })
  7277. TextInput({ text: item.LYRICIST })
  7278. .height(40)
  7279. .maxLines(1)
  7280. .fontSize(14)
  7281. .layoutWeight(1)
  7282. .fontColor($r('app.color.text_color'))
  7283. .margin({ right: 20, left: 10 })
  7284. .onChange((val: string) => {
  7285. this.lyricistStr = val
  7286. })
  7287. }
  7288. .width('100%')
  7289. .margin({ top: 10, bottom: 10 })
  7290. .justifyContent(FlexAlign.Start)
  7291. Row() {
  7292. Text('注释:')
  7293. .fontSize(14)
  7294. .fontColor($r('app.color.text_color'))
  7295. .margin({ left: 22 })
  7296. TextInput({ text: item.COMMENT })
  7297. .height(40)
  7298. .maxLines(1)
  7299. .fontSize(14)
  7300. .layoutWeight(1)
  7301. .fontColor($r('app.color.text_color'))
  7302. .margin({ right: 20, left: 10 })
  7303. .onChange((val: string) => {
  7304. this.commentStr = val
  7305. })
  7306. }
  7307. .width('100%')
  7308. .margin({ top: 10, bottom: 10 })
  7309. .justifyContent(FlexAlign.Start)
  7310. Row() {
  7311. Button('保存')
  7312. .fontColor(Color.White)
  7313. .layoutWeight(1)
  7314. .height(50)
  7315. .width(100)
  7316. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7317. .backgroundColor(this.themeColor)
  7318. .stateEffect(true)
  7319. .margin({ right: 20, bottom: 20 })
  7320. .onClick(async () => {
  7321. this.doEdit(item)
  7322. })
  7323. Button('取消')
  7324. .fontColor(Color.White)
  7325. .layoutWeight(1)
  7326. .height(50)
  7327. .width(100)
  7328. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7329. .backgroundColor(this.themeColor)
  7330. .stateEffect(true)
  7331. .margin({ left: 20, bottom: 20 })
  7332. .onClick(async () => {
  7333. if(this.isGridMusic){
  7334. this.longItemFilePath =''
  7335. }else{
  7336. this.isShowEdit = false
  7337. }
  7338. this.setEditStrEmpty()
  7339. if(this.isShowPlay){
  7340. this.isShowEdit = false
  7341. }
  7342. })
  7343. }
  7344. .margin({
  7345. left: 38,
  7346. right: 38,
  7347. top: 10,
  7348. bottom: 10
  7349. })
  7350. .width(250)
  7351. .height(60)
  7352. }
  7353. }
  7354. .margin({ bottom: 20 })
  7355. }
  7356. setEditStrEmpty(){
  7357. this.imagePathStr = ''
  7358. this.lyricConStr = ''
  7359. this.artistStr = ''
  7360. this.titleStr = ''
  7361. this.ablumStr = ''
  7362. this.genreStr = ''
  7363. this.yearStr = ''
  7364. this.trackStr = ''
  7365. this.albumArtistStr = ''
  7366. this.composerStr = ''
  7367. this.lyricistStr = ''
  7368. this.commentStr = ''
  7369. this.discStr = ''
  7370. }
  7371. initEditFields(item?: VideoItem) {
  7372. if (!item) {
  7373. this.setEditStrEmpty()
  7374. return
  7375. }
  7376. this.imagePathStr = ''
  7377. this.titleStr = item.name ?? ''
  7378. this.artistStr = item.artist ?? ''
  7379. this.ablumStr = item.album ?? ''
  7380. this.genreStr = item.genre ?? ''
  7381. this.yearStr = item.year ?? ''
  7382. this.trackStr = item.track ?? ''
  7383. this.albumArtistStr = item.ALBUMARTIST ?? ''
  7384. this.composerStr = item.COMPOSER ?? ''
  7385. this.lyricistStr = item.LYRICIST ?? ''
  7386. this.commentStr = item.COMMENT ?? ''
  7387. this.discStr = item.disc ?? ''
  7388. this.lyricConStr = item.lyricContent ?? ''
  7389. }
  7390. private syncEditedFields(target?: VideoItem) {
  7391. if (!target) {
  7392. return
  7393. }
  7394. target.name = this.titleStr
  7395. target.artist = this.artistStr
  7396. target.album = this.ablumStr
  7397. target.lyricContent = this.lyricConStr
  7398. target.year = this.yearStr
  7399. target.genre = this.genreStr
  7400. target.track = this.trackStr
  7401. target.ALBUMARTIST = this.albumArtistStr
  7402. target.COMPOSER = this.composerStr
  7403. target.LYRICIST = this.lyricistStr
  7404. target.COMMENT = this.commentStr
  7405. target.disc = this.discStr
  7406. }
  7407. private replaceItemInList(list: Array<VideoItem> | undefined, filePath: string,
  7408. apply?: (next: Array<VideoItem>) => void) {
  7409. if (!list || ArrayUtil.isEmpty(list)) {
  7410. return
  7411. }
  7412. const index = list.findIndex((video: VideoItem) => video.filePath === filePath)
  7413. if (index < 0) {
  7414. return
  7415. }
  7416. const nextList = [...list]
  7417. this.syncEditedFields(nextList[index])
  7418. apply?.(nextList)
  7419. }
  7420. private syncListsAfterEdit(filePath: string) {
  7421. this.replaceItemInList(this.videoLocalList, filePath, (next: Array<VideoItem>) => {
  7422. this.videoLocalList = next
  7423. this.dataSource.pushArrayData(next)
  7424. })
  7425. this.replaceItemInList(this.songList, filePath, (next: Array<VideoItem>) => {
  7426. this.songList = next
  7427. this.sonDataSource.pushArrayData(next)
  7428. })
  7429. this.replaceItemInList(this.favList, filePath, (next: Array<VideoItem>) => {
  7430. this.favList = next
  7431. })
  7432. this.replaceItemInList(this.historyList, filePath, (next: Array<VideoItem>) => {
  7433. this.historyList = next
  7434. })
  7435. this.replaceItemInList(this.currentSongList, filePath, (next: Array<VideoItem>) => {
  7436. this.currentSongList = next
  7437. })
  7438. this.replaceItemInList(this.mediaKuList, filePath, (next: Array<VideoItem>) => {
  7439. this.mediaKuList = next
  7440. })
  7441. this.replaceItemInList(this.filteredList, filePath, (next: Array<VideoItem>) => {
  7442. this.filteredList = next
  7443. })
  7444. this.replaceItemInList(this.artistList, filePath, (next: Array<VideoItem>) => {
  7445. this.artistList = next
  7446. })
  7447. this.replaceItemInList(this.albumList, filePath, (next: Array<VideoItem>) => {
  7448. this.albumList = next
  7449. })
  7450. this.listRefreshKey++
  7451. }
  7452. private refreshLazyListViews(mainListUpdated: boolean, playlistUpdated: boolean): void {
  7453. if (!mainListUpdated && !playlistUpdated) {
  7454. return;
  7455. }
  7456. this.listRefreshKey++;
  7457. if (mainListUpdated) {
  7458. this.dataSource.notifyDataReload();
  7459. }
  7460. if (playlistUpdated) {
  7461. this.sonDataSource.notifyDataReload();
  7462. }
  7463. }
  7464. @Builder
  7465. detailSheet(item:VideoItem) {
  7466. Scroll() {
  7467. Column() {
  7468. this.songDetail(item)
  7469. }
  7470. }
  7471. .width('100%')
  7472. .height('100%')
  7473. }
  7474. @Builder
  7475. songDetail(currentItem:VideoItem) {
  7476. Column() {
  7477. if (currentItem) {
  7478. Row() {
  7479. Stack() {
  7480. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.alt') :
  7481. currentItem.pixelMapPath)
  7482. .fillColor(this.themeColor)
  7483. .height(80)
  7484. .width(80)
  7485. .borderRadius(10)
  7486. .opacity(this.opacityItem)// 绑定透明度
  7487. .margin({ left: 22 })
  7488. }
  7489. Column() {
  7490. Column() {
  7491. Text(currentItem.name)
  7492. .fontSize(16)
  7493. .maxLines(1)
  7494. .animation({
  7495. duration: 555,
  7496. curve: 'Linear',
  7497. })
  7498. .fontColor($r('app.color.text_color'))
  7499. .margin({ left: 15 })
  7500. }
  7501. .height('100%')
  7502. .width('100%')
  7503. .justifyContent(FlexAlign.Center)
  7504. .alignItems(HorizontalAlign.Start)
  7505. }
  7506. .height('100%')
  7507. }
  7508. .width('100%')
  7509. .height(90)
  7510. .justifyContent(FlexAlign.SpaceBetween)
  7511. Row() {
  7512. Text('艺术家:')
  7513. .fontSize(14)
  7514. .fontColor($r('app.color.text_color'))
  7515. .margin({ left: 22 })
  7516. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  7517. .fontSize(14)
  7518. .fontColor($r('app.color.text_color'))
  7519. .margin({ left: 10 })
  7520. .layoutWeight(1)
  7521. }
  7522. .width('100%')
  7523. .margin({ top: 10, bottom: 10 })
  7524. .justifyContent(FlexAlign.Start)
  7525. Row() {
  7526. Text('专辑名:')
  7527. .fontSize(14)
  7528. .fontColor($r('app.color.text_color'))
  7529. .margin({ left: 22 })
  7530. Text(currentItem?.album ?currentItem.album : '未知专辑')
  7531. .fontSize(14)
  7532. .margin({ left: 10 })
  7533. .fontColor($r('app.color.text_color'))
  7534. .layoutWeight(1)
  7535. }
  7536. .width('100%')
  7537. .margin({ top: 10, bottom: 10 })
  7538. .justifyContent(FlexAlign.Start)
  7539. Row() {
  7540. Text('时长:')
  7541. .fontSize(14)
  7542. .fontColor($r('app.color.text_color'))
  7543. .margin({ left: 22 })
  7544. Text(StrUtil.isEmpty(currentItem.duration)?
  7545. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  7546. .fontSize(14)
  7547. .margin({ left: 10 })
  7548. .fontColor($r('app.color.text_color'))
  7549. .layoutWeight(1)
  7550. }
  7551. .width('100%')
  7552. .margin({ top: 10, bottom: 10 })
  7553. .justifyContent(FlexAlign.Start)
  7554. Row() {
  7555. Text('采样率:')
  7556. .fontSize(14)
  7557. .fontColor($r('app.color.text_color'))
  7558. .margin({ left: 22 })
  7559. Text(Utility.convertToKHz(currentItem.sampleRate))
  7560. .fontSize(14)
  7561. .margin({ left: 10 })
  7562. .fontColor($r('app.color.text_color'))
  7563. .layoutWeight(1)
  7564. }
  7565. .width('100%')
  7566. .margin({ top: 10, bottom: 10 })
  7567. .justifyContent(FlexAlign.Start)
  7568. Row() {
  7569. Text('比特率:')
  7570. .fontSize(14)
  7571. .fontColor($r('app.color.text_color'))
  7572. .margin({ left: 22 })
  7573. Text(currentItem.bit_rate)
  7574. .fontSize(14)
  7575. .margin({ left: 10 })
  7576. .fontColor($r('app.color.text_color'))
  7577. .layoutWeight(1)
  7578. }
  7579. .width('100%')
  7580. .margin({ top: 10, bottom: 10 })
  7581. .justifyContent(FlexAlign.Start)
  7582. Row() {
  7583. Text('位深:')
  7584. .fontSize(14)
  7585. .fontColor($r('app.color.text_color'))
  7586. .margin({ left: 22 })
  7587. Text(`${currentItem.bits_per_raw_sample} bits`)
  7588. .fontSize(14)
  7589. .margin({ left: 10 })
  7590. .fontColor($r('app.color.text_color'))
  7591. .layoutWeight(1)
  7592. }
  7593. .width('100%')
  7594. .margin({ top: 10, bottom: 10 })
  7595. .justifyContent(FlexAlign.Start)
  7596. Row() {
  7597. Text('声道:')
  7598. .fontSize(14)
  7599. .fontColor($r('app.color.text_color'))
  7600. .margin({ left: 22 })
  7601. Text(`${currentItem.channels}`)
  7602. .fontSize(14)
  7603. .margin({ left: 10 })
  7604. .fontColor($r('app.color.text_color'))
  7605. .layoutWeight(1)
  7606. }
  7607. .width('100%')
  7608. .margin({ top: 10, bottom: 10 })
  7609. .justifyContent(FlexAlign.Start)
  7610. Row() {
  7611. Text('声道布局:')
  7612. .fontSize(14)
  7613. .fontColor($r('app.color.text_color'))
  7614. .margin({ left: 22 })
  7615. Text(`${currentItem.channel_layout}`)
  7616. .fontSize(14)
  7617. .margin({ left: 10 })
  7618. .fontColor($r('app.color.text_color'))
  7619. .layoutWeight(1)
  7620. }
  7621. .width('100%')
  7622. .margin({ top: 10, bottom: 10 })
  7623. .justifyContent(FlexAlign.Start)
  7624. Row() {
  7625. Text('起始播放点:')
  7626. .fontSize(14)
  7627. .fontColor($r('app.color.text_color'))
  7628. .margin({ left: 22 })
  7629. Text(`${currentItem.start_time}`)
  7630. .fontSize(14)
  7631. .margin({ left: 10 })
  7632. .fontColor($r('app.color.text_color'))
  7633. .layoutWeight(1)
  7634. }
  7635. .width('100%')
  7636. .margin({ top: 10, bottom: 10 })
  7637. .justifyContent(FlexAlign.Start)
  7638. Row() {
  7639. Text('风格:')
  7640. .fontSize(14)
  7641. .fontColor($r('app.color.text_color'))
  7642. .margin({ left: 22 })
  7643. Text(currentItem.genre)
  7644. .fontSize(14)
  7645. .margin({ left: 10 })
  7646. .fontColor($r('app.color.text_color'))
  7647. .layoutWeight(1)
  7648. }
  7649. .width('100%')
  7650. .margin({ top: 10, bottom: 10 })
  7651. .justifyContent(FlexAlign.Start)
  7652. Row() {
  7653. Text('发行时间:')
  7654. .fontSize(14)
  7655. .fontColor($r('app.color.text_color'))
  7656. .margin({ left: 22 })
  7657. Text(currentItem.year)
  7658. .fontSize(14)
  7659. .margin({ left: 10 })
  7660. .fontColor($r('app.color.text_color'))
  7661. .layoutWeight(1)
  7662. }
  7663. .width('100%')
  7664. .margin({ top: 10, bottom: 10 })
  7665. .justifyContent(FlexAlign.Start)
  7666. Row() {
  7667. Text('质量评分:')
  7668. .fontSize(14)
  7669. .fontColor($r('app.color.text_color'))
  7670. .margin({ left: 22 })
  7671. Text(currentItem.probe_score+"")
  7672. .fontSize(14)
  7673. .margin({ left: 10 })
  7674. .fontColor($r('app.color.text_color'))
  7675. .layoutWeight(1)
  7676. }
  7677. .width('100%')
  7678. .margin({ top: 10, bottom: 10 })
  7679. .justifyContent(FlexAlign.Start)
  7680. Row() {
  7681. Text('音轨号:')
  7682. .fontSize(14)
  7683. .fontColor($r('app.color.text_color'))
  7684. .margin({ left: 22 })
  7685. Text(currentItem.track)
  7686. .fontSize(14)
  7687. .margin({ left: 10 })
  7688. .fontColor($r('app.color.text_color'))
  7689. .layoutWeight(1)
  7690. }
  7691. .width('100%')
  7692. .margin({ top: 10, bottom: 10 })
  7693. .justifyContent(FlexAlign.Start)
  7694. Row() {
  7695. Text('碟号:')
  7696. .fontSize(14)
  7697. .fontColor($r('app.color.text_color'))
  7698. .margin({ left: 22 })
  7699. Text(currentItem.disc)
  7700. .fontSize(14)
  7701. .margin({ left: 10 })
  7702. .fontColor($r('app.color.text_color'))
  7703. .layoutWeight(1)
  7704. }
  7705. .width('100%')
  7706. .margin({ top: 10, bottom: 10 })
  7707. .justifyContent(FlexAlign.Start)
  7708. Row() {
  7709. Text('专辑艺术家:')
  7710. .fontSize(14)
  7711. .fontColor($r('app.color.text_color'))
  7712. .margin({ left: 22 })
  7713. Text(currentItem.ALBUMARTIST)
  7714. .fontSize(14)
  7715. .margin({ left: 10 })
  7716. .fontColor($r('app.color.text_color'))
  7717. .layoutWeight(1)
  7718. }
  7719. .width('100%')
  7720. .margin({ top: 10, bottom: 10 })
  7721. .justifyContent(FlexAlign.Start)
  7722. Row() {
  7723. Text('作曲家:')
  7724. .fontSize(14)
  7725. .fontColor($r('app.color.text_color'))
  7726. .margin({ left: 22 })
  7727. Text(currentItem.COMPOSER)
  7728. .fontSize(14)
  7729. .margin({ left: 10 })
  7730. .fontColor($r('app.color.text_color'))
  7731. .layoutWeight(1)
  7732. }
  7733. .width('100%')
  7734. .margin({ top: 10, bottom: 10 })
  7735. .justifyContent(FlexAlign.Start)
  7736. Row() {
  7737. Text('作词家:')
  7738. .fontSize(14)
  7739. .fontColor($r('app.color.text_color'))
  7740. .margin({ left: 22 })
  7741. Text(currentItem.LYRICIST)
  7742. .fontSize(14)
  7743. .margin({ left: 10 })
  7744. .fontColor($r('app.color.text_color'))
  7745. .layoutWeight(1)
  7746. }
  7747. .width('100%')
  7748. .margin({ top: 10, bottom: 10 })
  7749. .justifyContent(FlexAlign.Start)
  7750. Row() {
  7751. Text('注释:')
  7752. .fontSize(14)
  7753. .fontColor($r('app.color.text_color'))
  7754. .margin({ left: 22 })
  7755. Text(currentItem.COMMENT)
  7756. .fontSize(14)
  7757. .margin({ left: 10 })
  7758. .fontColor($r('app.color.text_color'))
  7759. .layoutWeight(1)
  7760. }
  7761. .width('100%')
  7762. .margin({ top: 10, bottom: 10 })
  7763. .justifyContent(FlexAlign.Start)
  7764. Row() {
  7765. Text('格式:')
  7766. .fontSize(14)
  7767. .fontColor($r('app.color.text_color'))
  7768. .margin({ left: 22 })
  7769. Text(Utility.formatMimeType(currentItem.mimeType))
  7770. .fontSize(14)
  7771. .margin({ left: 10 })
  7772. .fontColor($r('app.color.text_color'))
  7773. .layoutWeight(1)
  7774. }
  7775. .width('100%')
  7776. .margin({ top: 10, bottom: 10 })
  7777. .justifyContent(FlexAlign.Start)
  7778. Row() {
  7779. Text('播放次数:')
  7780. .fontSize(14)
  7781. .fontColor($r('app.color.text_color'))
  7782. .margin({ left: 22 })
  7783. Text(currentItem.playCount?.toString())
  7784. .fontSize(14)
  7785. .margin({ left: 10 })
  7786. .fontColor($r('app.color.text_color'))
  7787. .layoutWeight(1)
  7788. }
  7789. .width('100%')
  7790. .margin({ top: 10, bottom: 10 })
  7791. .justifyContent(FlexAlign.Start)
  7792. Row() {
  7793. Text('流数量:')
  7794. .fontSize(14)
  7795. .fontColor($r('app.color.text_color'))
  7796. .margin({ left: 22 })
  7797. Text(currentItem.nb_streams?.toString())
  7798. .fontSize(14)
  7799. .margin({ left: 10 })
  7800. .fontColor($r('app.color.text_color'))
  7801. .layoutWeight(1)
  7802. }
  7803. .width('100%')
  7804. .margin({ top: 10, bottom: 10 })
  7805. .justifyContent(FlexAlign.Start)
  7806. Row() {
  7807. Text('文件大小:')
  7808. .fontSize(14)
  7809. .fontColor($r('app.color.text_color'))
  7810. .margin({ left: 22 })
  7811. Text(currentItem.size)
  7812. .fontSize(14)
  7813. .margin({ left: 10 })
  7814. .fontColor($r('app.color.text_color'))
  7815. .layoutWeight(1)
  7816. }
  7817. .width('100%')
  7818. .margin({ top: 10, bottom: 10 })
  7819. .justifyContent(FlexAlign.Start)
  7820. Row() {
  7821. Text('文件名:')
  7822. .fontSize(14)
  7823. .fontColor($r('app.color.text_color'))
  7824. .margin({ left: 22 })
  7825. Text(currentItem.fileName)
  7826. .fontSize(14)
  7827. .margin({ left: 10 })
  7828. .fontColor($r('app.color.text_color'))
  7829. .layoutWeight(1)
  7830. }
  7831. .width('100%')
  7832. .margin({ top: 10, bottom: 10 })
  7833. .justifyContent(FlexAlign.Start)
  7834. Row() {
  7835. Text('修改时间:')
  7836. .fontSize(14)
  7837. .fontColor($r('app.color.text_color'))
  7838. .margin({ left: 22 })
  7839. Text(currentItem.cTime)
  7840. .fontSize(14)
  7841. .margin({ left: 10 })
  7842. .fontColor($r('app.color.text_color'))
  7843. .layoutWeight(1)
  7844. }
  7845. .width('100%')
  7846. .margin({ top: 10, bottom: 10 })
  7847. .justifyContent(FlexAlign.Start)
  7848. Row() {
  7849. Text('存放目录:')
  7850. .fontSize(14)
  7851. .fontColor($r('app.color.text_color'))
  7852. .margin({ left: 22 })
  7853. Text(currentItem.filePath)
  7854. .fontSize(12)
  7855. .margin({ left: 10 })
  7856. .fontColor($r('app.color.text_color'))
  7857. .layoutWeight(1)
  7858. }
  7859. .margin({ top: 10, bottom: 10 })
  7860. .width('100%')
  7861. .justifyContent(FlexAlign.Start)
  7862. Row() {
  7863. Text('内嵌歌词:')
  7864. .fontSize(14)
  7865. .fontColor($r('app.color.text_color'))
  7866. .margin({ left: 22 })
  7867. Text(currentItem.lyricContent)
  7868. .fontSize(12)
  7869. .copyOption(CopyOptions.InApp)
  7870. .margin({ left: 10 })
  7871. .fontColor($r('app.color.text_color'))
  7872. .layoutWeight(1)
  7873. }
  7874. .margin({ top: 10, bottom: 10 })
  7875. .width('100%')
  7876. .justifyContent(FlexAlign.Start)
  7877. }
  7878. }
  7879. .margin({ bottom: 20 })
  7880. }
  7881. //定时关闭布局
  7882. @Builder
  7883. TimeCloseSheet() {
  7884. Scroll() {
  7885. Column() {
  7886. this.TimeClose()
  7887. }
  7888. }
  7889. .width('100%')
  7890. .height('100%')
  7891. }
  7892. //倒计时关闭音乐,退出App功能实现。
  7893. @State selectedMinutes: number = 0 // 0表示未开启
  7894. @State remainingSeconds: number = 0
  7895. // 预设时间选项
  7896. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  7897. private formatTime(seconds: number): string {
  7898. const mins = Math.floor(seconds / 60)
  7899. const secs = seconds % 60
  7900. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  7901. }
  7902. // 开始倒计时
  7903. private handleTimeSelect(minutes: number) {
  7904. if (minutes === this.selectedMinutes) {
  7905. this.stopCountdown();
  7906. this.selectedMinutes = 0;
  7907. return;
  7908. }
  7909. this.selectedMinutes = minutes;
  7910. this.remainingSeconds = minutes * 60;
  7911. this.startCountdown(); // 新增调用
  7912. }
  7913. @Builder
  7914. TimeClose() {
  7915. Column() {
  7916. // 倒计时显示区域
  7917. Text(this.selectedMinutes > 0 ?
  7918. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  7919. "定时关闭未开启")
  7920. .fontSize(17)
  7921. .fontColor($r('app.color.text_color'))
  7922. .margin({ top: 2, bottom: 8 });
  7923. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  7924. ForEach(this.presetTimes, (minutes: number, index: number) => {
  7925. // 单行时间选项容器
  7926. Row() {
  7927. // 文字描述区域
  7928. Text(this.getDisplayText(minutes))
  7929. .fontSize(15)
  7930. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  7931. $r('app.color.text_color'))// 选中态颜色变化
  7932. .textAlign(TextAlign.Start)
  7933. .layoutWeight(1); // 占据剩余空间
  7934. // 复选框样式的选择器
  7935. Row() {
  7936. if (minutes === this.selectedMinutes) {
  7937. // 选中状态 - 带勾号的圆形复选框
  7938. Row() {
  7939. // 使用系统内置的勾号图标
  7940. Image($r('sys.media.ohos_ic_public_ok'))
  7941. .width(14)
  7942. .height(14)
  7943. .fillColor(Color.White)
  7944. }
  7945. .width(24)
  7946. .height(24)
  7947. .borderRadius(12)
  7948. .backgroundColor(this.themeColor)
  7949. .justifyContent(FlexAlign.Center)
  7950. .alignItems(VerticalAlign.Center)
  7951. } else {
  7952. // 未选中状态的圆形边框
  7953. Row()
  7954. .width(24)
  7955. .height(24)
  7956. .borderRadius(12)
  7957. .border({
  7958. width: 2,
  7959. color: $r('app.color.text_color'),
  7960. style: BorderStyle.Solid
  7961. })
  7962. .backgroundColor(Color.Transparent)
  7963. }
  7964. }
  7965. .width(24)
  7966. .height(24)
  7967. .margin({ left: 20 })
  7968. .justifyContent(FlexAlign.Center)
  7969. .alignItems(VerticalAlign.Center)
  7970. }
  7971. .width('100%')
  7972. .padding({
  7973. top: 18,
  7974. bottom: 18,
  7975. left: 18,
  7976. right: 18
  7977. })
  7978. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  7979. $r('app.color.bottom_control_background')) // 选中背景高亮
  7980. .borderRadius(12)
  7981. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7982. .margin({ bottom: 18 })
  7983. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  7984. });
  7985. }
  7986. .width('100%')
  7987. .padding(16)
  7988. }
  7989. }
  7990. // 获取显示文本
  7991. private getDisplayText(minutes: number): string {
  7992. if (minutes === -1) {
  7993. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  7994. }
  7995. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  7996. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  7997. }
  7998. // 处理选择事件
  7999. private handleSelect(minutes: number): void {
  8000. if (minutes === -1) { // 自定义
  8001. // 弹出自定义时间对话框
  8002. DialogHelper.showTextInputDialog({
  8003. title: '自定义时间',
  8004. maskColor: Color.Transparent,
  8005. inputType: InputType.Number,
  8006. text: '',
  8007. onChange: (text) => {
  8008. console.error("onChange: " + text);
  8009. },
  8010. onAction: (action, dialogId, content) => {
  8011. if (action == DialogAction.TWO) {
  8012. const customMinutes = Number(content);
  8013. if (customMinutes > 0) {
  8014. this.handleTimeSelect(customMinutes); // 设置自定义时间
  8015. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  8016. }
  8017. }
  8018. }
  8019. });
  8020. } else {
  8021. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  8022. }
  8023. }
  8024. // 添加定时器引用
  8025. private timerId: number = -1;
  8026. // 启动/重置倒计时
  8027. private startCountdown() {
  8028. // 清除旧定时器
  8029. if (this.timerId !== -1) {
  8030. clearInterval(this.timerId);
  8031. }
  8032. // 创建新定时器
  8033. if (this.selectedMinutes > 0) {
  8034. this.timerId = setInterval(() => {
  8035. if (this.remainingSeconds === 15) {
  8036. this.showConfirmationDialog();
  8037. }
  8038. if (this.remainingSeconds > 0) {
  8039. this.remainingSeconds -= 1;
  8040. } else {
  8041. this.stopCountdown();
  8042. this.handleTimeout();
  8043. }
  8044. }, 1000);
  8045. }
  8046. }
  8047. // 15倒计时后再次提示显示确认是否关闭App对话框
  8048. private showConfirmationDialog() {
  8049. DialogHelper.showAlertDialog({
  8050. backgroundColor: $r('app.color.btn_green'),
  8051. title: '确认关闭',
  8052. maskColor: Color.Transparent,
  8053. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  8054. borderStyle: BorderStyle.Dashed,
  8055. primaryButton: '暂不关闭',
  8056. secondaryButton: '确定',
  8057. onAction: (action) => {
  8058. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  8059. this.stopCountdown();
  8060. this.selectedMinutes = 0
  8061. } else if (action == DialogAction.TWO) {
  8062. }
  8063. }
  8064. })
  8065. }
  8066. // 停止倒计时
  8067. private stopCountdown() {
  8068. if (this.timerId !== -1) {
  8069. clearInterval(this.timerId);
  8070. this.timerId = -1;
  8071. }
  8072. }
  8073. // 超时处理
  8074. private handleTimeout() {
  8075. // 执行播放器关闭逻辑
  8076. this.selectedMinutes = 0;
  8077. ToastUtil.showToast(" 定时关闭已完成");
  8078. this.stop(); // 假设存在的播放器实例
  8079. //退出APP
  8080. const mContext = getContext(this) as common.UIAbilityContext
  8081. mContext.terminateSelf();
  8082. AvSessionController.getInstance(true).unregisterSessionListener()
  8083. }
  8084. //倒计时关闭音乐,退出App功能实现结束。
  8085. //播放列表的拖动List 重新排序
  8086. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  8087. //左滑操作 移动文件 重命名 删除等操作
  8088. @Builder
  8089. sonButton(item: VideoItem, index: number, filePath: string) {
  8090. Row() {
  8091. //加入下一首播放
  8092. Button() {
  8093. Image($r('app.media.next_to_play'))
  8094. .fillColor(Color.White)
  8095. .width(20)
  8096. }
  8097. .width(40)
  8098. .height(40)
  8099. .type(ButtonType.Circle)
  8100. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8101. .backgroundColor(this.themeColor)
  8102. .margin(5)
  8103. .onClick(() => {
  8104. this.addToNextPlay(item);
  8105. })
  8106. Button() {
  8107. Image($r('app.media.close'))
  8108. .fillColor(Color.White)
  8109. .width(20)
  8110. }
  8111. .width(40)
  8112. .height(40)
  8113. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8114. .type(ButtonType.Circle)
  8115. .backgroundColor(this.themeColor)
  8116. .margin(5)
  8117. .onClick(() => {
  8118. this.songList.splice(Number(index), 1)
  8119. this.sonDataSource.pushArrayData(this.songList)
  8120. })
  8121. Button() {
  8122. Image($r('app.media.share2'))
  8123. .fillColor(Color.White)
  8124. .width(20)
  8125. }
  8126. .width(40)
  8127. .height(40)
  8128. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8129. .type(ButtonType.Circle)
  8130. .backgroundColor(this.themeColor)
  8131. .margin(5)
  8132. .onClick(() => {
  8133. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  8134. })
  8135. }
  8136. }
  8137. itemMoveSon(index: number, newIndex: number): void {
  8138. if (newIndex < 0 || newIndex >= this.songList.length) {
  8139. return;
  8140. }
  8141. let tmp = this.songList.splice(index, 1);
  8142. this.songList.splice(newIndex, 0, tmp[0]);
  8143. this.sonDataSource.pushArrayData(this.songList)
  8144. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  8145. if(this.modeType==4&&this.playlistTable){
  8146. updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
  8147. }
  8148. }
  8149. @Builder
  8150. PlayList() {
  8151. List({ scroller: this.playListScroller }) {
  8152. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  8153. ListItem() {
  8154. this.MusicItemSon(item, index)
  8155. }
  8156. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  8157. .animation({
  8158. duration: 666,
  8159. curve: 'ease-in-out' // 可选动画曲线
  8160. })
  8161. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 600 }),
  8162. TransitionEffect.scale({ x: 0, y: 0 })))
  8163. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  8164. //拖动List关键代码开始
  8165. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  8166. .zIndex(this.dragItem === index ? 1 : 0)
  8167. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  8168. .gesture(
  8169. GestureGroup(GestureMode.Sequence,
  8170. LongPressGesture({ repeat: true })
  8171. .onAction((event?: GestureEvent) => {
  8172. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  8173. this.scaleItem = index
  8174. })
  8175. })
  8176. .onActionEnd(() => {
  8177. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  8178. this.scaleItem = -1
  8179. })
  8180. }),
  8181. PanGesture({ fingers: 1, direction: null, distance: 0 })
  8182. .onActionStart(() => {
  8183. this.dragItem = index // 记录当前拖动项索引
  8184. this.dragRefOffset = 0 // 重置偏移基准
  8185. })
  8186. .onActionUpdate((event: GestureEvent) => {
  8187. this.offsetY = event.offsetY - this.dragRefOffset;
  8188. this.neighborItem = -1;
  8189. let indexA = this.songList.indexOf(item);
  8190. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  8191. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  8192. let value: number = 0;
  8193. if (this.offsetY < 0) {
  8194. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  8195. this.neighborItem = indexA - 1;
  8196. this.neighborScale = 1 - value / 20;
  8197. } else if (this.offsetY > 0) {
  8198. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  8199. this.neighborItem = indexA + 1;
  8200. this.neighborScale = 1 - value / 20;
  8201. }
  8202. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  8203. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8204. this.offsetY -= this.ITEM_INTV;
  8205. this.dragRefOffset += this.ITEM_INTV;
  8206. this.itemMoveSon(indexA, indexA + 1);
  8207. });
  8208. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  8209. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8210. this.offsetY += this.ITEM_INTV;
  8211. this.dragRefOffset -= this.ITEM_INTV;
  8212. this.itemMoveSon(indexA, indexA - 1);
  8213. });
  8214. }
  8215. })
  8216. .onActionEnd((event: GestureEvent) => {
  8217. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8218. this.dragItem = -1
  8219. this.neighborItem = -1
  8220. })
  8221. animateTo({
  8222. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  8223. }, () => {
  8224. this.scaleItem = -1
  8225. })
  8226. })
  8227. )
  8228. .onCancel(() => {
  8229. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8230. this.dragItem = -1
  8231. this.neighborItem = -1
  8232. })
  8233. animateTo({
  8234. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  8235. }, () => {
  8236. this.scaleItem = -1
  8237. })
  8238. })
  8239. ) //拖动List关键代码结束
  8240. .onClick(() => {
  8241. this.doPlay(item, index, true)
  8242. })
  8243. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  8244. }
  8245. .width('100%')
  8246. .height('100%')
  8247. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  8248. // .animation({ duration: 500, curve: Curve.Ease }))
  8249. .cachedCount(10)
  8250. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  8251. .gesture(PinchGesture({ fingers: 2 })
  8252. .onActionEnd((event: GestureEvent) => {
  8253. this.setSonListTwoFingers()
  8254. })
  8255. .onActionUpdate(e => {
  8256. this.scaleValue = this.pinchValue * e.scale
  8257. })
  8258. .onActionStart(e => {
  8259. }))
  8260. .padding({
  8261. bottom: 0
  8262. })
  8263. }
  8264. setSonListTwoFingers() {
  8265. this.pinchValue = this.scaleValue;
  8266. Logger.info('this.pinchValue = ' + this.pinchValue);
  8267. if (this.pinchValue >= 1) {
  8268. this.sonTwoFingerType++
  8269. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  8270. if (this.sonTwoFingerType > 3) {
  8271. this.sonTwoFingerType = 1
  8272. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  8273. }
  8274. } else {
  8275. this.sonTwoFingerType--
  8276. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  8277. if (this.sonTwoFingerType < 1) {
  8278. this.sonTwoFingerType = 1
  8279. }
  8280. }
  8281. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  8282. this.pinchValue = 1;
  8283. this.scaleValue = 1;
  8284. }
  8285. @State sonTwoFingerType:number = 3
  8286. @Builder
  8287. private MusicItemSon(item: VideoItem, index?: number) {
  8288. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8289. Row() {
  8290. Stack() {
  8291. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  8292. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  8293. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  8294. .alt($r('app.media.alt'))
  8295. .fillColor(this.themeColor)
  8296. .borderRadius(this.isCoverRectangle?11:'100%')
  8297. .clip(true)
  8298. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  8299. .draggable(false)// 禁止长按手势拖动
  8300. .autoResize(true) // 重采样,可减少内存占用
  8301. .margin({ left: 20 })
  8302. }
  8303. .width('15%')
  8304. Column() {
  8305. Column() {
  8306. Text(this.isShowFileName?item.fileName :item.name)
  8307. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  8308. .fontColor(this.curIndex === index ? this.themeColor :
  8309. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  8310. .maxLines(1)
  8311. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  8312. Row() {
  8313. Column(){
  8314. Text(item.md5Str?.includes('Lossless')?
  8315. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  8316. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  8317. .padding({ top: 3,right:6,left:6,bottom:3 })
  8318. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  8319. $r('app.color.text_color'))
  8320. .fontWeight(500)
  8321. .borderRadius(12)
  8322. .visibility(StrUtil.isEmpty(item.md5Str) ? Visibility.None : Visibility.Visible)
  8323. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  8324. .backgroundColor('#FFC107')
  8325. }
  8326. .padding({ top: 8 })
  8327. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  8328. item.artist + ' ' + item?.duration)
  8329. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  8330. .padding({ top: 8 })
  8331. .maxLines(1)
  8332. .fontColor(this.curIndex === index ? this.themeColor :
  8333. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  8334. .margin({ left: StrUtil.isEmpty(item.md5Str)? 12 :this.sonTwoFingerType == 3 ? 5 : 3 })
  8335. Blank()
  8336. Text(item.size)
  8337. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  8338. .padding({ top: 8 })
  8339. .maxLines(1)
  8340. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  8341. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  8342. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  8343. .margin({ left: 10 })
  8344. }
  8345. }
  8346. .height('100%')
  8347. .width('100%')
  8348. .justifyContent(FlexAlign.Center)
  8349. .alignItems(HorizontalAlign.Start)
  8350. }
  8351. .height('100%')
  8352. .width('65%')
  8353. Column() {
  8354. ImageAnimator()
  8355. .images(this.imagesF)// 动画数组
  8356. .duration(1000)// 持续
  8357. .state(this.animationState)// 动画状态
  8358. .fillMode(FillMode.Forwards)
  8359. .width(18)
  8360. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  8361. Visibility.None)
  8362. .height(18)
  8363. .iterations(-1) // 播放次数
  8364. }
  8365. .width('20%')
  8366. }
  8367. }
  8368. .backgroundColor(Color.Transparent)
  8369. .width('100%')
  8370. .reuseId('son_item')
  8371. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  8372. .shadow(this.scaleItem === index ? {
  8373. radius: 70,
  8374. color: '#15000000',
  8375. offsetX: 0,
  8376. offsetY: 0
  8377. } :
  8378. {
  8379. radius: 0,
  8380. color: '#15000000',
  8381. offsetX: 0,
  8382. offsetY: 0
  8383. })
  8384. .animation({ curve: Curve.Sharp, duration: 300 })
  8385. }
  8386. @Builder
  8387. MusicPlayBuilder() {
  8388. Column() {
  8389. this.IjkMusicPlayerView()
  8390. }
  8391. .transition(TransitionEffect.asymmetric(
  8392. TransitionEffect.opacity(1),
  8393. TransitionEffect.OPACITY
  8394. ))
  8395. .visualEffect(deviceInfo.sdkApiVersion>=20&&this.bgController?
  8396. new hdsEffect.HdsEffectBuilder()
  8397. .shaderEffect({
  8398. effectType: hdsEffect.EffectType.UV_BACKGROUND_FLOW_LIGHT,
  8399. animation: {
  8400. duration: 10000,
  8401. iterations: -1,
  8402. autoPlay: true,
  8403. onFinish: ()=> {
  8404. console.info('Succeeded in finishing');
  8405. }
  8406. },
  8407. controller: this.bgController,
  8408. })
  8409. .buildEffect():null)
  8410. .height('100%')
  8411. .width('100%')
  8412. .onDisAppear(() => {
  8413. this.translateY = 0;
  8414. })
  8415. .translate({ y: this.translateY })
  8416. .gesture(
  8417. PanGesture(this.panOption)
  8418. .onActionUpdate((event?: GestureEvent) => {
  8419. if (event) {
  8420. // 只允许向下滑动,向上滑动时限制为0
  8421. this.translateY = Math.max(0, event.offsetY);
  8422. this.getUIContext().animateTo({
  8423. duration: 500,
  8424. curve: Curve.Sharp
  8425. }, () => {
  8426. this.scaleValueImage = Math.min(1, Math.max(0.38, 1 - event.offsetY / 500));
  8427. console.info('onecold scaleValueImage:', this.scaleValueImage)
  8428. this.scaleValueText =Math.min(1, Math.max(0.6, 1 - event.offsetY / 700));
  8429. })
  8430. }
  8431. })
  8432. .onActionEnd((event?: GestureEvent) => {
  8433. // 使用更低的阈值和滑动速度判断
  8434. const minDistance = 300; // 最小滑动距离 100vp
  8435. const minVelocity = 500; // 最小滑动速度
  8436. // 获取滑动速度(如果可用)
  8437. const velocity = event?.velocityY || 0;
  8438. // 判断是否应该关闭:距离足够 或者 速度足够快
  8439. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  8440. if (shouldClose) {
  8441. // 添加关闭动画
  8442. this.getUIContext().animateTo({
  8443. duration: 600,
  8444. curve: Curve.Friction
  8445. }, () => {
  8446. this.isShowPlay = false;
  8447. this.scaleValueImage = 1
  8448. this.scaleValueText = 1
  8449. this.translateY = 0;
  8450. })
  8451. } else {
  8452. // 回弹动画
  8453. this.getUIContext().animateTo({
  8454. duration: 600,
  8455. curve: Curve.Friction
  8456. }, () => {
  8457. this.scaleValueImage = 1
  8458. this.scaleValueText = 1
  8459. this.translateY = 0;
  8460. })
  8461. }
  8462. })
  8463. )
  8464. }
  8465. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  8466. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  8467. HeightBreakpoint.HEIGHT_LG;
  8468. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  8469. @State topBarHeight: number = 50
  8470. @State barOpacity: number = 1
  8471. @State barBottomOpacity: number = 1
  8472. private hideDone: boolean = false;
  8473. @State currentYOffset: number = 0;
  8474. @State bottomBarHeight: number = 68;
  8475. private isHiding: boolean = false;
  8476. //是否是Pura X外屏,或者小屏幕
  8477. isPuraWP() {
  8478. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  8479. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  8480. }
  8481. //是否是Pura X外屏,或者小屏幕,手机横屏
  8482. /**
  8483. * 是否是Pura X外屏,或者小屏幕,手机横屏
  8484. * @returns
  8485. */
  8486. isCoverOpacity() {
  8487. if (this.isPuraWP()) {
  8488. return true
  8489. }
  8490. if (this.isPhoneLan()) {
  8491. return true
  8492. }
  8493. if (deviceInfo.marketName.includes('Pura X')
  8494. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  8495. return true
  8496. }
  8497. return false
  8498. }
  8499. //是不是手机横屏
  8500. isPhoneLan() {
  8501. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  8502. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  8503. logHiCarWindow(`isPhoneLan width=${this.windowWidth}`);
  8504. logHiCarWindow(`isPhoneLan height=${this.windowHeight}`);
  8505. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarStatus=${this.isHiCarStatus}`);
  8506. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, curDisplayIsHiCar=${this.curDisplayIsHiCar}`);
  8507. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall=${this.isHiCarSmall()}`);
  8508. if (this.isHiCarKuanBianPing()) {
  8509. return true
  8510. }
  8511. if (this.isHiCar()) {
  8512. return false
  8513. }
  8514. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8515. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  8516. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  8517. return true
  8518. }
  8519. return false
  8520. }
  8521. //是不是1920x720的hicar的屏幕分辨率
  8522. isHiCarKuanBianPing(){
  8523. if(!this.isHiCar()){
  8524. return false
  8525. }
  8526. const hiCarAspectRatios: HiCarAspectRatio[] = [
  8527. { ratio: 1920 / 720, name: "1920x720" },
  8528. ];
  8529. const currentRatio: number = this.windowWidth / this.windowHeight;
  8530. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  8531. logHiCarWindow(`HiCarKuanBianPing currentRatio=${currentRatio}`)
  8532. for (const hiCarRatio of hiCarAspectRatios) {
  8533. logHiCarWindow(`HiCarKuanBianPing hiCarRatio=${hiCarRatio.ratio}`)
  8534. logHiCarWindow(`HiCarKuanBianPing diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  8535. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  8536. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  8537. //宽扁平的尺寸设置列表展示
  8538. this.twoFingerType ==3
  8539. this.isGridMusic = false
  8540. return true;
  8541. }
  8542. }
  8543. return false;
  8544. }
  8545. //是不是hicar的屏幕分辨率
  8546. isHiCarSmall() {
  8547. if(!this.isHiCar()){
  8548. return false
  8549. }
  8550. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  8551. {
  8552. this.columns = 6
  8553. return false
  8554. }
  8555. const hiCarAspectRatios: HiCarAspectRatio[] = [
  8556. { ratio: 800 / 480, name: "800x480" },
  8557. { ratio: 1280 / 720, name: "1280x720" },
  8558. { ratio: 1920 / 1080, name: "1920x1080" },
  8559. ];
  8560. const currentRatio: number = this.windowWidth / this.windowHeight;
  8561. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  8562. logHiCarWindow(`HiCarSmall currentRatio=${currentRatio}`)
  8563. for (const hiCarRatio of hiCarAspectRatios) {
  8564. logHiCarWindow(`HiCarSmall hiCarRatio=${hiCarRatio.ratio}`)
  8565. logHiCarWindow(`HiCarSmall diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  8566. logHiCarWindow(`HiCarSmall isHiCarStatus=${this.isHiCarStatus}`);
  8567. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  8568. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  8569. //宽扁平的尺寸设置列表展示
  8570. return true;
  8571. }
  8572. }
  8573. return false;
  8574. }
  8575. isHiCar() {
  8576. return this.curDisplayIsHiCar;
  8577. }
  8578. //是不是正常的手机竖屏
  8579. isPhonePortrait() {
  8580. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  8581. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  8582. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  8583. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8584. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  8585. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  8586. return true
  8587. }
  8588. return false
  8589. }
  8590. @State showSpeedDialog: boolean = false
  8591. @State longPressSpeed: number = 3 //长按默认倍数
  8592. @Builder
  8593. SpeedDialog() {
  8594. Stack() {
  8595. Column() {
  8596. Text('已切换至' + this.longPressSpeed + '倍速播放')
  8597. .fontColor(Color.White)
  8598. .visibility(Visibility.Hidden)
  8599. }
  8600. .backgroundColor(Color.Black)
  8601. .borderRadius(20)
  8602. .padding({
  8603. top: 10,
  8604. right: 20,
  8605. left: 15,
  8606. bottom: 20
  8607. })
  8608. .opacity(0.6)
  8609. Text('已切换至' + this.longPressSpeed + '倍速播放')
  8610. .fontColor(Color.White)
  8611. }
  8612. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  8613. .zIndex(5)
  8614. .margin({ top: 80 })
  8615. }
  8616. @Builder
  8617. IjkMusicPlayerView() {
  8618. Stack() {
  8619. if(canIUse("SystemCapability.UIDesign.HDSComponent.Core")
  8620. &&deviceInfo.sdkApiVersion>=20&&this.sceneBgController){
  8621. HdsVisualComponent()
  8622. .scene(HdsSceneType.DUAL_EDGE_FLOW_LIGHT_WITH_BACKGROUND_MASK, this.sceneBgController, () => {
  8623. console.info('Succeeded in finishing');
  8624. })
  8625. .width('100%')
  8626. .height('100%')
  8627. .visibility(this.isShowBgLiuGUANG?Visibility.Visible:Visibility.None)
  8628. }
  8629. Column() {
  8630. Column() {
  8631. //播放标题
  8632. Column() {
  8633. this.PlayTitle()
  8634. }
  8635. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  8636. .width('100%')
  8637. .margin({ top: 0 })
  8638. .height(PlayConstants.HEIGHT)
  8639. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  8640. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  8641. if (this.showSpeedDialog) {
  8642. this.SpeedDialog()
  8643. }
  8644. Stack() {
  8645. //手势拖动快进
  8646. Column()
  8647. .width(CommonConstants.FULL_PERCENT)
  8648. .height('100%')
  8649. .gesture(
  8650. GestureGroup(GestureMode.Parallel,
  8651. // 长按屏幕倍数播放
  8652. LongPressGesture({ repeat: true })
  8653. .onAction(() => {
  8654. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8655. this.showSpeedDialog = true;
  8656. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  8657. }
  8658. })
  8659. .onActionEnd(() => {
  8660. this.showSpeedDialog = false;
  8661. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  8662. }),
  8663. //双击屏幕暂停或者播放
  8664. TapGesture({ count: 2 })
  8665. .onAction((event: GestureEvent) => {
  8666. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8667. ToastUtil.showToast('已暂停')
  8668. }
  8669. console.info('onecold playOrPause 6693')
  8670. this.playOrPause()
  8671. })
  8672. )
  8673. )
  8674. }
  8675. .height('65%')
  8676. Swiper() {
  8677. this.CoverInfo()
  8678. this.PlayerLyrics()
  8679. }
  8680. .onChange((index: number) => {
  8681. this.currentSwiperIndex = index
  8682. })
  8683. .indicator(false)
  8684. .displayCount(new BreakpointType({
  8685. sm: 1,
  8686. md: 2,
  8687. lg: 2,
  8688. xl: 2,
  8689. xxl: 2
  8690. }).getValue(this.currentBreakpoint))
  8691. .clip(false)
  8692. .loop(false)
  8693. .autoPlay(false)
  8694. // .interval(8000)
  8695. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  8696. .height('100%')
  8697. .hitTestBehavior(HitTestMode.Transparent)
  8698. Image($r('app.media.icon_replay'))
  8699. .objectFit(ImageFit.Auto)
  8700. .width('120px')
  8701. .height('120px')
  8702. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  8703. .border({ width: 0 })
  8704. .visibility(Visibility.None)
  8705. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  8706. .onClick(() => {
  8707. console.info('onecold startPlayOrResumePlay 6744')
  8708. this.startPlayOrResumePlay();
  8709. })
  8710. }
  8711. .width(CommonConstants.FULL_PERCENT)
  8712. .height(CommonConstants.FULL_PERCENT)
  8713. .justifyContent(FlexAlign.End)
  8714. }
  8715. .justifyContent(FlexAlign.End)
  8716. .margin({ bottom: 8 })
  8717. }
  8718. .backgroundImage(!this.isMusicBGCover||StrUtil.isEmpty(this.cover)?null: this.cover)
  8719. .backgroundImageSize(this.isPuraWP()||!this.isMusicBGCover ? { width: '100%' } : { height: '150%', width: '100%' })
  8720. .animation({
  8721. duration: 666,
  8722. curve: 'ease-in-out' // 可选动画曲线
  8723. })
  8724. .backgroundBlurStyle((this.isPuraWP() && this.currentSwiperIndex === 0) ||!this.isMusicBGCover
  8725. ? BlurStyle.NONE :
  8726. BlurStyle.BACKGROUND_ULTRA_THICK)
  8727. .hitTestBehavior(HitTestMode.Transparent)
  8728. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  8729. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  8730. .onClick(() => {
  8731. if(this.isHiCar())
  8732. return
  8733. if(this.is_auto_hide_progress){
  8734. this.is_auto_hide_progress = false
  8735. }
  8736. this.startAutoHide()
  8737. })
  8738. }
  8739. @Consume progressValue: number ;
  8740. @State currentTime: string = "00:00";
  8741. @State totalTime: string = "00:00";
  8742. @State loadingVisible: Visibility = Visibility.None;
  8743. @State replayVisible: Visibility = Visibility.None;
  8744. @State slideEnable: boolean = false;
  8745. @State aspRatio: number = 0.5;
  8746. @State mContext: object | undefined = undefined;
  8747. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  8748. @State mFirst: boolean = true;
  8749. @State mDestroyPage: boolean = false;
  8750. @State playSpeed: number = 1;
  8751. @State oldSeconds: number = 0;
  8752. @State isSeekTo: boolean = false;
  8753. @State isCurrentTime: boolean = false;
  8754. @State videoWidth: string = '100%';
  8755. @State videoHeight: string = '100%';
  8756. @State initAspectRatio: number = 1;
  8757. @State videoAspectRatio: number = this.initAspectRatio;
  8758. @State videoUrl: string = '';
  8759. private last: number = 0;
  8760. @State videoParentAspectRatio: number = this.initAspectRatio;
  8761. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  8762. @Consume CONTROL_PlayStatus: number ;
  8763. @State PROGRESS_MAX_VALUE: number = 100;
  8764. @State updateProgressTimer: number = 0;
  8765. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  8766. @State name: string = '';
  8767. // @State loop: boolean = false;
  8768. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  8769. @State multiple: string = '1.0X';
  8770. xcomponentController: XComponentController = new XComponentController()
  8771. private panOptionBright: PanGestureOptions =
  8772. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  8773. private panOptionVolume: PanGestureOptions =
  8774. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  8775. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  8776. //手势的音量控制和亮度控制
  8777. private positionX: number = PlayConstants.POSITION_X;
  8778. private positionY: number = PlayConstants.POSITION_Y;
  8779. private windowClass: window.Window = globalThis.windowClass
  8780. @State volume: number = 0.5;
  8781. @State volumeSmall: boolean = false
  8782. @State autoParseMusicName: boolean = true
  8783. @State isShowFileName: boolean = false
  8784. @State isLongNameRoLL: boolean = true//长歌名滚动
  8785. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  8786. @State bright: number = PlayConstants.BRIGHT;
  8787. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  8788. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  8789. @State screenWidth: number = 0
  8790. @State screenHeight: number = 0
  8791. @State statusBarHeight: number = 0
  8792. @State isYesFull: boolean = false
  8793. private seekValue: number = 0
  8794. @State isVideoLock: boolean = false; // Whether the video playback is locked
  8795. eventHub = getContext().eventHub;
  8796. //投播组件
  8797. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  8798. private castController: avSession.AVCastController | undefined = undefined;
  8799. @State isCastPlaying: boolean = false;
  8800. @State currentTime2: number = 0;
  8801. @State currentStringTime: string = '00:00';
  8802. @State duration: number = 0;
  8803. @State isReady: boolean = false;
  8804. @State durationTime: number = 0;
  8805. @State durationStringTime: string = '00:00';
  8806. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  8807. // @State isPlaying: boolean = false;
  8808. private castSeek: boolean = false;
  8809. private castItem: avSession.AVQueueItem | undefined = undefined;
  8810. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  8811. @State rotateAngle2: number = -9
  8812. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  8813. @Consume cover: string | undefined ;
  8814. @State artist: string | undefined = ''
  8815. // 1.初始化controller
  8816. private lyricController: LyricController = new LyricController()
  8817. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  8818. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  8819. private parser = new LyricParser()
  8820. @State randomColor: string = 'rgb(0,0,0)'
  8821. @State randomShakenX: number = 0
  8822. @State randomShakenY: number = 0
  8823. @State lyricTextSize: number = 24
  8824. @State lyricContent: string = ''
  8825. @State isDebug: boolean = false
  8826. @State isHightLightCenter: boolean = true
  8827. /**
  8828. * 初始化歌词加载与展示逻辑
  8829. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  8830. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  8831. * @param isApi2 是否使用API2获取歌词(可选)
  8832. *
  8833. * 主要流程:
  8834. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  8835. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  8836. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  8837. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  8838. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  8839. * 6. 解析失败或读取失败时,清空歌词显示。
  8840. *
  8841. * 注意事项:
  8842. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  8843. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  8844. * - 歌词内容解析后通过lyricController驱动UI渲染。
  8845. */
  8846. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  8847. if (StrUtil.isEmpty(lyricPath)) {
  8848. return
  8849. }
  8850. this.initPipLyricSetting()
  8851. this.lyricControllerSingle
  8852. .setTextSize(15)
  8853. .setCacheSize(4)
  8854. .setTextColor("#FFFFFF")
  8855. .setHighlightColor("#FFFFFF")
  8856. .setHighlightScale(1.2)
  8857. .setEmptyHint("")
  8858. .setAlignMode('center')
  8859. .setAnimationDuration(500)
  8860. .setSingleLine(true)
  8861. this.lyricContent = ''
  8862. this.lyricController
  8863. .setTextSize(this.currentLyricSize)
  8864. .setCacheSize(4)
  8865. .setTextColor("#DDDDDD")
  8866. .setHighlightColor("#FFFFFF")
  8867. .setEmptyHint("")
  8868. .setAnimationDuration(1000)
  8869. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  8870. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  8871. this.setBlurDegree(this.blurDegree, false)
  8872. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  8873. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  8874. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  8875. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  8876. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  8877. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  8878. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  8879. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  8880. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  8881. this.lyricController.setTextWeight(this.lyricTextWeight)
  8882. this.showSingleLyric = false
  8883. this.timeOffset = 0
  8884. this.lyricController.setLyric(null)
  8885. this.lyricControllerSingle.setLyric(null)
  8886. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  8887. console.log("onecold lyricPath =" + lyricPath)
  8888. let neiqianLrc = ''
  8889. let lyContent = this.currentSong?.lyricContent
  8890. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  8891. neiqianLrc = lyContent
  8892. }
  8893. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast&&!isLocal&&!isLocal) {
  8894. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  8895. //赋值给this.lyricContent,播控中心才可以显示歌词
  8896. this.lyricContent = neiqianLrc
  8897. // 将文件内容按行分割成字符串数组
  8898. let lines = neiqianLrc.split('\n').map(line => line.trim());
  8899. // 3.解析歌词
  8900. let lyric = this.parser.parse(lines);
  8901. // 4.设置歌词
  8902. this.lyricController.setLyric(lyric);
  8903. this.lyricControllerXF.setLyric(lyric)
  8904. this.lyricControllerSingle.setLyric(lyric)
  8905. return
  8906. }
  8907. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  8908. && !Utility.isVideoByExtension(this.videoUrl))) {
  8909. if (this.currentSong !== undefined) {
  8910. // ToastUtil.showShort('正在为你搜索在线歌词!')
  8911. //判断是不是赞助会员,是会员的话才开启歌词功能
  8912. // if (!this.isDebug) {
  8913. // if (!Utility.isNoble()) {
  8914. // LogUtil.debug("onecold 不是赞助会员")
  8915. // return
  8916. // }
  8917. // if(!Utility.isPassInstallTime(33)){
  8918. // LogUtil.debug("onecold not pass time")
  8919. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  8920. // return
  8921. // }
  8922. // }
  8923. let artist = this.currentSong?.artist
  8924. if (artist === undefined) {
  8925. artist = ''
  8926. }
  8927. if (isApi2 === undefined) {
  8928. isApi2 = false
  8929. }
  8930. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  8931. // LogUtil.debug("onecold res =" + res)
  8932. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  8933. if (StrUtil.isNotEmpty(res)) {
  8934. this.lyricContent = res
  8935. let lines = res.split('\n').map(line => line.trim());
  8936. // 3.解析歌词
  8937. let lyric = this.parser.parse(lines);
  8938. // 4.设置歌词
  8939. this.lyricController.setLyric(lyric);
  8940. this.lyricControllerXF.setLyric(lyric)
  8941. this.lyricControllerSingle.setLyric(lyric)
  8942. this.showSingleLyric = true
  8943. // 4.保存歌词文件lyric到本地
  8944. //2025年8月28日歌词不再加密下载
  8945. this.saveDataToFile(res, lyricPath, false)
  8946. } else {
  8947. this.lyricController.setLyric(null)
  8948. this.lyricControllerXF.setLyric(null)
  8949. this.lyricControllerSingle.setLyric(null)
  8950. if (isOnLineAndToast) {
  8951. ToastUtil.showShort('未获取到歌词!')
  8952. }
  8953. }
  8954. } else {
  8955. this.lyricController.setLyric(null)
  8956. this.lyricControllerXF.setLyric(null)
  8957. this.lyricControllerSingle.setLyric(null)
  8958. if (isOnLineAndToast) {
  8959. ToastUtil.showShort('未获取到歌词!')
  8960. }
  8961. }
  8962. })
  8963. } else {
  8964. this.lyricController.setLyric(null)
  8965. this.lyricControllerXF.setLyric(null)
  8966. this.lyricControllerSingle.setLyric(null)
  8967. if (isOnLineAndToast) {
  8968. ToastUtil.showShort('未获取到歌词!')
  8969. }
  8970. }
  8971. return
  8972. }
  8973. try {
  8974. let isJiaMi = false;
  8975. let realLyricPath = lyricPath
  8976. if (FileUtil.accessSync(jiaMilyricPath)) {
  8977. isJiaMi = true
  8978. realLyricPath = jiaMilyricPath
  8979. console.info("onecold 找到加密本地歌词 ");
  8980. } else {
  8981. isJiaMi = false
  8982. realLyricPath = lyricPath
  8983. console.info("onecold 找到本地歌词 ");
  8984. }
  8985. // 3.读取文件内容并指定编码为 UTF-8
  8986. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  8987. const stat = await fileIo.stat(file.fd);
  8988. const arrayBuffer = new ArrayBuffer(stat.size);
  8989. fs.read(file.fd, arrayBuffer)
  8990. .then((readLen: number) => {
  8991. console.info("read file data succeed");
  8992. // let buf = buffer.from(arrayBuffer, 0, readLen);
  8993. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  8994. // 检查 buf 是否为空
  8995. if (buf.length === 0) {
  8996. throw new Error("Buffer is empty after reading the file");
  8997. }
  8998. try {
  8999. // 检测文件编码
  9000. // let detectedEncoding = chardet.detect(buf);
  9001. // console.info("onecoldT Detected encoding: " + detectedEncoding);
  9002. let detectedEncoding = this.detect(arrayBuffer)
  9003. console.info("onecoldT Detected encoding: " + detectedEncoding);
  9004. // 使用检测到的编码解码,解决中文乱码问题
  9005. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  9006. console.info("onecoldT Detected textDecoder: " + textDecoder);
  9007. let fileContent = textDecoder.decode(buf);
  9008. console.info(`onecoldT The content of file1: ${fileContent}`);
  9009. //解密
  9010. if (isJiaMi) {
  9011. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  9012. }
  9013. console.info(`onecold The content of file2: ${fileContent}`);
  9014. this.lyricContent = fileContent
  9015. if(isLocal){//编辑标签选择本地歌词需要赋值给this.lyricConStr
  9016. this.lyricConStr = fileContent
  9017. }
  9018. // 将文件内容按行分割成字符串数组
  9019. let lines = fileContent.split('\n').map(line => line.trim());
  9020. console.info(`onecold The content of file: ${fileContent}`);
  9021. // 3.解析歌词
  9022. let lyric = this.parser.parse(lines);
  9023. // 4.设置歌词
  9024. this.lyricController.setLyric(lyric);
  9025. this.lyricControllerXF.setLyric(lyric)
  9026. this.lyricControllerSingle.setLyric(lyric)
  9027. this.showSingleLyric = true
  9028. console.info(`The content of file: ${fileContent}`);
  9029. } catch (chardetError) {
  9030. console.error("chardet.detect failed with error: " + chardetError.message);
  9031. this.lyricController.setLyric(null);
  9032. this.lyricControllerXF.setLyric(null)
  9033. this.lyricControllerSingle.setLyric(null)
  9034. }
  9035. })
  9036. .catch((err: BusinessError) => {
  9037. this.lyricController.setLyric(null)
  9038. this.lyricControllerXF.setLyric(null)
  9039. this.lyricControllerSingle.setLyric(null)
  9040. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  9041. })
  9042. .catch((err: Error) => {
  9043. this.lyricController.setLyric(null)
  9044. this.lyricControllerXF.setLyric(null)
  9045. this.lyricControllerSingle.setLyric(null)
  9046. console.error("read file 2 data failed with error message: " + err.message);
  9047. })
  9048. .finally(() => {
  9049. fs.closeSync(file);
  9050. });
  9051. } catch (error) {
  9052. this.lyricController.setLyric(null)
  9053. this.lyricControllerSingle.setLyric(null)
  9054. this.lyricControllerXF.setLyric(null)
  9055. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  9056. }
  9057. }
  9058. detect(data: ArrayBuffer): string {
  9059. //创建检测对象
  9060. let detector: UniversalDetector = new UniversalDetector();
  9061. // 传入检测数据并实时判断编码格式
  9062. detector.handleData(data, 0, data.byteLength);
  9063. // 标记检测数据 读取结束
  9064. detector.dataEnd();
  9065. // 获取检测结果
  9066. let detected: string = detector.getDetectedCharset();
  9067. // 释放资源
  9068. detector.reset();
  9069. return detected;
  9070. }
  9071. //初始化悬浮歌词的自定义设置
  9072. initPipLyricSetting() {
  9073. this.lyricControllerXF
  9074. .setTextSize(this.currentLyricSize)
  9075. .setCacheSize(4)
  9076. .setTextColor("#DDDDDD")
  9077. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  9078. .setEmptyHint("")
  9079. .setAnimationDuration(1000)
  9080. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  9081. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  9082. this.setBlurDegree(this.blurDegreePip, true)
  9083. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  9084. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  9085. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  9086. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  9087. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  9088. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  9089. this.lyricControllerXF.setHightLightCenter(true)
  9090. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  9091. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  9092. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  9093. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  9094. if (this.pipBgIndex === 0) {
  9095. if (this.cover) {
  9096. this.pipBg = this.cover
  9097. } else {
  9098. this.pipBg = this.imageColor
  9099. }
  9100. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  9101. }
  9102. }
  9103. //根据item返回歌词内容
  9104. async getLyricContent(item: VideoItem): Promise<string> {
  9105. let neiqianLrc = ''
  9106. let lyContent = item?.lyricContent
  9107. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  9108. neiqianLrc = lyContent
  9109. return neiqianLrc
  9110. }
  9111. try {
  9112. //取数据库里面的歌词lyContent
  9113. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  9114. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  9115. console.log("onecold Lyrics:", lyricContent);
  9116. neiqianLrc = lyricContent
  9117. return neiqianLrc
  9118. }
  9119. } catch (error) {
  9120. console.error("Error fetching lyrics:", error);
  9121. }
  9122. try {
  9123. let filePath = item.filePath;
  9124. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  9125. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  9126. let isJiaMi = false;
  9127. let realLyricPath = lyricPath;
  9128. if (FileUtil.accessSync(jiaMilyricPath)) {
  9129. isJiaMi = true;
  9130. realLyricPath = jiaMilyricPath;
  9131. console.info("onecold 找到加密本地歌词");
  9132. } else {
  9133. console.info("onecold 找到本地歌词");
  9134. }
  9135. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  9136. const stat = await fileIo.stat(file.fd);
  9137. const arrayBuffer = new ArrayBuffer(stat.size);
  9138. const readLen = await fs.read(file.fd, arrayBuffer);
  9139. console.info("read file data succeed");
  9140. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  9141. if (buf.length === 0) {
  9142. throw new Error("Buffer is empty after reading the file");
  9143. }
  9144. // let detectedEncoding = chardet.detect(buf);
  9145. let detectedEncoding = this.detect(arrayBuffer)
  9146. console.info("Detected encoding: " + detectedEncoding);
  9147. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  9148. let fileContent = textDecoder.decode(buf);
  9149. console.info(`onecold The content of file1: ${fileContent}`);
  9150. if (isJiaMi) {
  9151. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  9152. }
  9153. console.info(`onecold The content of file2: ${fileContent}`);
  9154. fs.closeSync(file);
  9155. return fileContent;
  9156. } catch (error) {
  9157. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  9158. return '';
  9159. }
  9160. }
  9161. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  9162. if (StrUtil.isEmpty(filePath)) {
  9163. return
  9164. }
  9165. try {
  9166. //将content进行加密
  9167. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  9168. let lyricContent = ''
  9169. if (isJiaMi) {
  9170. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  9171. } else {
  9172. lyricContent = content
  9173. }
  9174. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  9175. // 清空文件内容
  9176. await fileIo.truncate(file.fd, 0);
  9177. await fileIo.write(file.fd, lyricContent);
  9178. await fileIo.close(file);
  9179. console.log('onecold lyric file Data saved successfully.');
  9180. } catch (error) {
  9181. console.error('onecold lyric file Failed to save data:', error);
  9182. }
  9183. }
  9184. // 定义开始旋转的方法
  9185. // 定时器用于一百毫秒执行一次旋转角度
  9186. @State timer: number = 0
  9187. @State rotateAngle: number = 0
  9188. //封面旋转动画
  9189. animationRoFun() {
  9190. if (this.isPlaying && !this.isCoverRectangle) {
  9191. this.timer = setInterval(() => {
  9192. this.rotateAngle += 1
  9193. }, 100)
  9194. this.startRotation()
  9195. } else {
  9196. clearInterval(this.timer)
  9197. this.stopRotation()
  9198. }
  9199. }
  9200. // 定义开始旋转的方法
  9201. startRotation() {
  9202. if (this.isPlaying) {
  9203. animateTo({
  9204. duration: 777,
  9205. iterations: 1,
  9206. curve: Curve.Linear
  9207. }, () => {
  9208. this.rotateAngle2 = -9
  9209. })
  9210. }
  9211. }
  9212. // 回调,暂停和播放按钮回调,下一首和上一首
  9213. playChange() {
  9214. // if(this.isCoverRectangle){
  9215. // return
  9216. // }
  9217. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  9218. this.setIsPlaying(true)
  9219. this.animationState = AnimationStatus.Running
  9220. } else {
  9221. this.setIsPlaying(false)
  9222. this.animationState = AnimationStatus.Paused
  9223. }
  9224. AppStorage.setOrCreate('animationState', this.animationState);
  9225. }
  9226. // 定义停止旋转的方法
  9227. stopRotation() {
  9228. if (this.isCoverRectangle) {
  9229. this.rotateAngle = 0
  9230. } else {
  9231. //唱针以左上角为点选择逆时针40度
  9232. animateTo({
  9233. duration: 1000,
  9234. curve: Curve.Linear,
  9235. iterations: 1,
  9236. }, () => {
  9237. this.rotateAngle2 = -45;
  9238. });
  9239. }
  9240. }
  9241. @Builder
  9242. private LyricsTopItem() {
  9243. Row() {
  9244. Stack() {
  9245. Image(this.cover)
  9246. .height(58)
  9247. .width(58)
  9248. .alt($r('app.media.alt'))
  9249. .borderRadius(8)
  9250. .clickEffect({ level: ClickEffectLevel.HEAVY })
  9251. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  9252. .shadow({
  9253. radius: 22,
  9254. type: ShadowType.BLUR,
  9255. color: 'on_primary'
  9256. })
  9257. }
  9258. .width('18%')
  9259. Column() {
  9260. Column() {
  9261. Text(this.name)
  9262. .fontSize(16)
  9263. .maxLines(1)
  9264. .fontWeight(FontWeight.Bolder)
  9265. .fontColor(this.currentLyricColor)
  9266. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  9267. Row() {
  9268. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  9269. .fontSize(13)
  9270. .fontWeight(FontWeight.Bold)
  9271. .padding({ top: 8 })
  9272. .fontColor(this.currentLyricColor)
  9273. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  9274. Blank()
  9275. }
  9276. }
  9277. .height('100%')
  9278. .width('100%')
  9279. .justifyContent(FlexAlign.Center)
  9280. .alignItems(HorizontalAlign.Start)
  9281. }
  9282. .height('100%')
  9283. .width('65%')
  9284. Column() {
  9285. Image($r('app.media.lyric'))
  9286. .width(28)
  9287. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9288. .margin({ right: 30 })
  9289. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9290. .onClick(() => {
  9291. this.isLyricSetting = !this.isLyricSetting;
  9292. })
  9293. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  9294. height: '99%',
  9295. dragBar: true,
  9296. preferType: SheetType.CENTER,
  9297. showClose: true,
  9298. blurStyle: BlurStyle.Thin,
  9299. backgroundColor: Color.Transparent,
  9300. title: { title: $r('app.string.lyric_setting') }
  9301. })
  9302. }
  9303. .width('18%')
  9304. }
  9305. .width('82%')
  9306. .height(58)
  9307. .justifyContent(FlexAlign.SpaceBetween)
  9308. }
  9309. //歌词显示
  9310. @Builder
  9311. PlayerLyrics() {
  9312. Column() {
  9313. Column() {
  9314. this.LyricsTopItem()
  9315. }
  9316. .height(this.isPuraWP() ? 15 : 58)
  9317. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  9318. Visibility.None : Visibility.Visible)
  9319. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  9320. .width("100%")
  9321. Column() {
  9322. LyricView2({
  9323. controller: this.lyricController,
  9324. enableSeek: true,
  9325. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  9326. seekLineColor: "#80ffffff", // 滑动定位线颜色
  9327. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  9328. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  9329. if (!this.isPlaying) {
  9330. console.info('onecold startPlayOrResumePlay 7527')
  9331. this.startPlayOrResumePlay()
  9332. }
  9333. else {
  9334. this.isSeekTo = true;
  9335. this.mDestroyPage = false;
  9336. this.showLoadIng();
  9337. this.seekTo(position + "");
  9338. this.isSeekTo = false;
  9339. }
  9340. return true
  9341. }
  9342. })
  9343. .width("100%")
  9344. .layoutWeight(1)
  9345. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  9346. if (this.isPhoneLan()) {
  9347. Column() {
  9348. this.playProgressView()
  9349. // this.playCenterView()
  9350. }
  9351. .margin({ bottom: 30, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  9352. }
  9353. }
  9354. .position({
  9355. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  9356. (this.isPuraWP() ? 58 : 99)
  9357. })
  9358. .justifyContent(FlexAlign.Center)
  9359. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  9360. }
  9361. }
  9362. @Builder
  9363. SingleLyricView() {
  9364. Column() {
  9365. Column() {
  9366. LyricView2({
  9367. controller: this.lyricControllerSingle,
  9368. enableSeek: false,
  9369. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  9370. seekLineColor: "#80ffffff", // 滑动定位线颜色
  9371. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  9372. })
  9373. }
  9374. .height(66)
  9375. .margin({ bottom: 20 })
  9376. }
  9377. }
  9378. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  9379. @Builder
  9380. BottomControl() {
  9381. Column() {
  9382. this.TopPlayProgressView()
  9383. //播放 暂停,下一首,上一首
  9384. this.playCenterView()
  9385. if(!this.curDisplayIsHiCar){
  9386. //播放进度条
  9387. this.BottomView()
  9388. }
  9389. }
  9390. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  9391. }
  9392. //播放控制上一首 下一首 暂停和播放
  9393. @Builder
  9394. playCenterView(){
  9395. Row() {
  9396. Button({type:ButtonType.Circle,stateEffect:true}){
  9397. //更多功能
  9398. Image($r('app.media.menu'))
  9399. .width(24)
  9400. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9401. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  9402. height: '99%',
  9403. preferType:SheetType.CENTER,
  9404. dragBar: true,
  9405. showClose: true,
  9406. blurStyle: BlurStyle.Thin,
  9407. title: { title: $r('app.string.more') },
  9408. backgroundColor: Color.Transparent,
  9409. })
  9410. }
  9411. .height(45)
  9412. .width(45)
  9413. .margin({ left: 5 })
  9414. .backgroundColor(Color.Transparent)
  9415. .onClick(() => {
  9416. this.isShowMoreView = !this.isShowMoreView;
  9417. })
  9418. Button({type:ButtonType.Circle,stateEffect:true}){
  9419. Image($r('app.media.ic_previous'))
  9420. .width(33)
  9421. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9422. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9423. }
  9424. .height(45)
  9425. .width(45)
  9426. .onClick(async () => {
  9427. await this.playPrevious()
  9428. })
  9429. .backgroundColor(Color.Transparent)
  9430. Button({type:ButtonType.Circle,stateEffect:true}){
  9431. Column() {
  9432. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  9433. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  9434. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  9435. .width(this.isPhoneLan()?45:55)
  9436. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9437. .fillColor(Color.White)
  9438. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9439. }
  9440. }
  9441. .onClick(async () => {
  9442. this.playOrPause()
  9443. })
  9444. .backgroundColor(Color.Transparent)
  9445. .layoutWeight(1)
  9446. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9447. Image($r('app.media.ic_next'))
  9448. .width(33)
  9449. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9450. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9451. }
  9452. .height(45)
  9453. .width(45)
  9454. .backgroundColor(Color.Transparent)
  9455. .onClick(async () => {
  9456. await this.playNext();
  9457. })
  9458. if(this.curDisplayIsHiCar){
  9459. this.playModeButton()
  9460. }else{
  9461. this.fullButton()
  9462. }
  9463. }
  9464. .width('95%')
  9465. .margin({ bottom:this.isCoverOpacity()?0:15 })
  9466. .justifyContent(FlexAlign.SpaceEvenly)
  9467. }
  9468. @Builder
  9469. TopPlayProgressView(){
  9470. Column() {
  9471. Row(){
  9472. Stack(){
  9473. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  9474. .fontColor([Color.White])
  9475. .fontSize(21)
  9476. .effectStrategy(1)
  9477. Text(this.fastForwardSeconds)
  9478. .fontColor(Color.White)
  9479. .fontSize(10)
  9480. .fontWeight(FontWeight.Bold)
  9481. }
  9482. .padding({left:12,bottom:6})
  9483. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  9484. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9485. .onClick(()=>{
  9486. this.backForward()
  9487. })
  9488. Slider({
  9489. value: this.progressValue,
  9490. min: 0,
  9491. max: this.PROGRESS_MAX_VALUE,
  9492. step: 1,
  9493. style: SliderStyle.InSet
  9494. })
  9495. .height(20)
  9496. .blockColor('rgba(255,255,255,1)')
  9497. .trackColor('rgba(255,255,255,0.3)')
  9498. .selectedColor(Color.White)
  9499. .trackThickness(4)
  9500. .showSteps(false)
  9501. .showTips(true)
  9502. .layoutWeight(1)
  9503. .enabled(this.slideEnable)
  9504. .onChange((value: number, mode: SliderChangeMode) => {
  9505. // if (mode == 2) {
  9506. this.isSeekTo = true;
  9507. this.mDestroyPage = false;
  9508. this.showLoadIng();
  9509. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  9510. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  9511. this.seekTo(seekValue + "");
  9512. // this.setProgress()
  9513. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  9514. this.isSeekTo = false;
  9515. // }
  9516. })
  9517. Stack(){
  9518. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  9519. .fontColor([Color.White])
  9520. .fontSize(21)
  9521. .effectStrategy(1)
  9522. Text(this.fastForwardSeconds)
  9523. .fontColor(Color.White)
  9524. .fontSize(10)
  9525. .fontWeight(FontWeight.Bold)
  9526. }
  9527. .padding({right:10,bottom:6})
  9528. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  9529. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9530. .onClick(()=>{
  9531. this.fastForward()
  9532. })
  9533. }
  9534. .justifyContent(FlexAlign.Center)
  9535. .padding({left:20,right:20})
  9536. .width(this.isLandscape?'88%':'95%')
  9537. Row() {
  9538. Text(this.currentTime)
  9539. .fontSize(10)
  9540. .fontColor(Color.White)
  9541. .margin({left:25})
  9542. Blank()
  9543. Text(this.totalTime)
  9544. .fontSize(10)
  9545. .fontColor(Color.White)
  9546. .margin({right:25})
  9547. }
  9548. .width(this.isLandscape?'85%':'90%')
  9549. .height(10)
  9550. }
  9551. .width('100%')
  9552. .alignItems(HorizontalAlign.Center)
  9553. }
  9554. @Builder
  9555. playModeButton(){
  9556. Button({type:ButtonType.Circle,stateEffect:true}){
  9557. Column() {
  9558. if (this.playType === 0) {
  9559. Image($r('app.media.loop'))
  9560. .width(27)
  9561. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9562. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9563. } else if (this.playType === 1) {
  9564. Image($r('app.media.single'))
  9565. .width(27)
  9566. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9567. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9568. } else if (this.playType === 2) {
  9569. Image($r('app.media.normal_play'))
  9570. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9571. .width(27)
  9572. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9573. } else if (this.playType === 3) {
  9574. Image($r('app.media.random'))
  9575. .width(27)
  9576. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9577. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9578. }
  9579. }
  9580. }
  9581. .layoutWeight(1)
  9582. .margin({ left: 5 })
  9583. .height(45)
  9584. .width(45)
  9585. .backgroundColor(Color.Transparent)
  9586. .onClick(async () => {
  9587. this.setLoopMode()
  9588. })
  9589. }
  9590. //播放进度条
  9591. @Builder
  9592. BottomView(){
  9593. Row() {
  9594. this.playModeButton()
  9595. if(this.currentSong){
  9596. Button({type:ButtonType.Circle,stateEffect:true}){
  9597. Column() {
  9598. Image($r('app.media.rename2'))
  9599. .width(21)
  9600. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9601. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9602. }
  9603. }
  9604. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  9605. height: '99%',
  9606. dragBar: true,
  9607. showClose: true,
  9608. preferType: SheetType.BOTTOM,
  9609. title: { title: '编辑标签' }
  9610. })
  9611. .height(45)
  9612. .width(45)
  9613. .layoutWeight(1)
  9614. .backgroundColor(Color.Transparent)
  9615. .onClick(async () => {
  9616. this.initEditFields(this.currentSong)
  9617. this.tempLyricContent = this.lyricContent
  9618. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  9619. this.lyricConStr = this.tempLyricContent
  9620. }
  9621. this.isShowEdit = !this.isShowEdit;
  9622. })
  9623. }
  9624. Button({type:ButtonType.Circle,stateEffect:true}){
  9625. Column() {
  9626. Image($r('app.media.lyric'))
  9627. .width(26)
  9628. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9629. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9630. }
  9631. }
  9632. .height(45)
  9633. .width(45)
  9634. .layoutWeight(1)
  9635. .backgroundColor(Color.Transparent)
  9636. .onClick(async () => {
  9637. this.isLyricSetting = !this.isLyricSetting;
  9638. })
  9639. //播放列表
  9640. Button({type:ButtonType.Circle,stateEffect:true}){
  9641. Image($r('app.media.hm_playlist'))
  9642. .width(24)
  9643. .fillColor(Color.White)
  9644. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9645. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9646. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  9647. height: '95%',
  9648. dragBar: true,
  9649. showClose: true,
  9650. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9651. blurStyle: BlurStyle.Thin,
  9652. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  9653. title: {
  9654. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  9655. + `(${this.songList.length}首)`
  9656. }
  9657. })
  9658. }
  9659. .layoutWeight(1)
  9660. .height(45)
  9661. .width(45)
  9662. .backgroundColor(Color.Transparent)
  9663. .onClick(() => {
  9664. this.isShowSheetView = !this.isShowSheetView;
  9665. if(this.isPlayListBgGrass){
  9666. this.isFrontWhite = true
  9667. }else{
  9668. this.isFrontWhite = false
  9669. }
  9670. this.scrollIndex()
  9671. })
  9672. }
  9673. .width(this.isLandscape?'88%':'95%')
  9674. .justifyContent(FlexAlign.SpaceAround)
  9675. .height(30)
  9676. .animation({
  9677. duration: 666,
  9678. curve: 'ease-in-out' // 可选动画曲线
  9679. })
  9680. }
  9681. @Builder
  9682. fullButton(){
  9683. Button({type:ButtonType.Circle,stateEffect:true}){
  9684. Column() {
  9685. Image($r('app.media.full_4'))
  9686. .width(25)
  9687. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9688. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9689. }
  9690. }
  9691. .layoutWeight(1)
  9692. .backgroundColor(Color.Transparent)
  9693. .height(45)
  9694. .width(45)
  9695. .onClick(async () => {
  9696. if (this.isLandscape) {
  9697. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  9698. } else {
  9699. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  9700. }
  9701. })
  9702. }
  9703. //旧版本播放进度条
  9704. @Builder
  9705. playProgressView() {
  9706. Row() {
  9707. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9708. Column() {
  9709. if (this.playType === 0) {
  9710. Image($r('app.media.loop'))
  9711. .width($r('app.float.control_image_width'))
  9712. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9713. } else if (this.playType === 1) {
  9714. Image($r('app.media.single'))
  9715. .width($r('app.float.control_image_width'))
  9716. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9717. } else if (this.playType === 2) {
  9718. Image($r('app.media.normal_play'))
  9719. .width($r('app.float.control_image_width'))
  9720. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9721. } else if (this.playType === 3) {
  9722. Image($r('app.media.random'))
  9723. .width($r('app.float.control_image_width'))
  9724. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9725. }
  9726. }
  9727. }
  9728. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  9729. .animation({
  9730. duration: 666,
  9731. curve: 'ease-in-out' // 可选动画曲线
  9732. })
  9733. .backgroundColor(Color.Transparent)
  9734. .margin({ right: 10 })
  9735. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9736. .onClick(async () => {
  9737. this.setLoopMode()
  9738. })
  9739. Text(this.currentTime)
  9740. .fontSize($r('app.float.slider_font_size'))
  9741. .fontColor(Color.White)
  9742. .margin(3)
  9743. Slider({
  9744. value: this.progressValue,
  9745. min: 0,
  9746. max: this.PROGRESS_MAX_VALUE,
  9747. step: 1,
  9748. style: SliderStyle.OutSet
  9749. })
  9750. .width('600px')
  9751. .blockColor('rgba(255,255,255,1)')
  9752. .trackColor('rgba(255,255,255,0.3)')
  9753. .selectedColor(Color.White)
  9754. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  9755. .layoutWeight(1)
  9756. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  9757. .showSteps(false)
  9758. .showTips(true)
  9759. .enabled(this.slideEnable)
  9760. .onChange((value: number, mode: SliderChangeMode) => {
  9761. // if (mode == 2) {
  9762. this.isSeekTo = true;
  9763. this.mDestroyPage = false;
  9764. this.showLoadIng();
  9765. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  9766. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  9767. this.seekTo(seekValue + "");
  9768. // this.setProgress()
  9769. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  9770. this.isSeekTo = false;
  9771. // }
  9772. })
  9773. Text(this.totalTime)
  9774. .fontSize($r('app.float.slider_font_size'))
  9775. .fontColor(Color.White)
  9776. .margin(3)
  9777. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  9778. //播放列表
  9779. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9780. Image($r('app.media.hm_playlist'))
  9781. .width($r('app.float.control_image_width'))
  9782. .fillColor(Color.White)
  9783. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9784. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  9785. height: '95%',
  9786. dragBar: true,
  9787. showClose: true,
  9788. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9789. blurStyle: BlurStyle.Thin,
  9790. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  9791. title: {
  9792. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  9793. + `(${this.songList.length}首)`
  9794. }
  9795. })
  9796. }
  9797. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  9798. .animation({
  9799. duration: 666,
  9800. curve: 'ease-in-out' // 可选动画曲线
  9801. })
  9802. .backgroundColor(Color.Transparent)
  9803. .margin({ right: 20, left: 10 })
  9804. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9805. .onClick(() => {
  9806. this.isShowSheetView = !this.isShowSheetView;
  9807. if (this.isPlayListBgGrass) {
  9808. this.isFrontWhite = true
  9809. } else {
  9810. this.isFrontWhite = false
  9811. }
  9812. this.scrollIndex()
  9813. })
  9814. }
  9815. //x5的竖屏模式需要99%
  9816. .width(this.isPhonePortrait() ? '93.4%'
  9817. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  9818. .height(this.isPhoneLan() ? 25 : 33)
  9819. .animation({
  9820. duration: 666,
  9821. curve: 'ease-in-out' // 可选动画曲线
  9822. })
  9823. }
  9824. isBigScreen() {
  9825. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  9826. return true
  9827. }
  9828. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  9829. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  9830. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  9831. return false
  9832. } else {
  9833. return true
  9834. }
  9835. return false
  9836. }
  9837. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  9838. @State isCoverRectangle: boolean = false
  9839. // 添加控制缩放的状态变量
  9840. @State scaleValueImage: number = 1
  9841. @State scaleValueText: number = 1
  9842. @Builder
  9843. CoverInfo() {
  9844. Column() {
  9845. Stack() {
  9846. Column() {
  9847. //方形封面布局
  9848. if (this.isCoverRectangle) {
  9849. this.RectangleCoverView()
  9850. } else {
  9851. //圆形封面布局
  9852. this.CicleCoverView()
  9853. }
  9854. this.musicNameInfo(false)
  9855. if (this.isPhoneLan()) {
  9856. Text(this.name)
  9857. .fontSize(18)
  9858. .fontWeight(FontWeight.Bold)
  9859. .margin({ top: 13 })
  9860. .textOverflow({ overflow: TextOverflow.Ellipsis })
  9861. .maxLines(1)
  9862. .width('99%')
  9863. .textAlign(TextAlign.Center)
  9864. .fontColor(Color.White)
  9865. }
  9866. }
  9867. .width('100%')
  9868. Column({ space: 8 }) {
  9869. Text(this.name)
  9870. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  9871. .fontWeight(FontWeight.Bold)
  9872. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9873. .maxLines(1)
  9874. .width('85%')
  9875. .textAlign(TextAlign.Center)
  9876. .fontColor(Color.White)
  9877. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  9878. Text(this.artist)
  9879. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  9880. .fontColor(Color.White)
  9881. .fontWeight(FontWeight.Bold)
  9882. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  9883. }
  9884. .justifyContent(FlexAlign.Start)
  9885. .zIndex(1)
  9886. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  9887. }
  9888. .margin({
  9889. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  9890. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  9891. top: this.isCoverOpacity() ? 0 : 20
  9892. })
  9893. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  9894. this.SingleLyricView()
  9895. }
  9896. if (this.isPhoneLan()) {
  9897. Column() {
  9898. this.playCenterView()
  9899. // this.playProgressView()
  9900. }
  9901. .position({ left: 28, bottom: 38 })
  9902. } else {
  9903. this.BottomControl()
  9904. }
  9905. }
  9906. .width(CommonConstants.FULL_PERCENT)
  9907. .clip(true)
  9908. }
  9909. //方形封面布局
  9910. @Builder
  9911. RectangleCoverView(){
  9912. Stack({alignContent:Alignment.Center}){
  9913. Image(this.cover)
  9914. .height(this.isHiCar()?(px2vp(this.windowHeight)*0.43):
  9915. this.isCoverOpacity()?(px2vp(this.windowHeight)*0.54):'auto')
  9916. .width(this.isHiCar()||this.isCoverOpacity()?'auto':this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '88%')
  9917. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  9918. .alt($r('app.media.alt'))
  9919. .margin({ right: 8, left: 8, top: 8 })
  9920. .aspectRatio(1)
  9921. .geometryTransition('cover') // 绑定标识符
  9922. .opacity(this.opacityValueImage)
  9923. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  9924. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  9925. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  9926. .clip(true)
  9927. .rotate({
  9928. x: 0,
  9929. y: 0,
  9930. z: 1,
  9931. angle: this.rotateAngle
  9932. })
  9933. .shadow({
  9934. radius: 22,
  9935. type: ShadowType.BLUR,
  9936. color: 'on_primary'
  9937. })
  9938. .onClick(() => {
  9939. this.isMusicBGCover = !this.isMusicBGCover
  9940. })
  9941. }
  9942. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  9943. // 设置左下角为缩放中心点
  9944. centerX: '0%',
  9945. centerY: '100%' })
  9946. }
  9947. @Builder
  9948. CicleCoverView() {
  9949. //圆形封面布局
  9950. Stack({alignContent:Alignment.Center}) {
  9951. Image($r('app.media.ic_music_disc'))
  9952. .width(245)
  9953. .height(245)
  9954. .margin({ right: 20, left: 20 ,top:this.isCoverRectangle||this.isLandscape?0:50 })
  9955. .aspectRatio(1)
  9956. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  9957. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  9958. .borderRadius('100%')
  9959. .align(Alignment.Center)
  9960. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  9961. .rotate({
  9962. angle: this.rotateAngle,
  9963. centerX: "50%",
  9964. centerY: "50%",
  9965. })
  9966. .animation({
  9967. duration: 100,
  9968. curve: Curve.Linear
  9969. })
  9970. .shadow({
  9971. radius: 22,
  9972. type: ShadowType.BLUR,
  9973. color: 'on_primary'
  9974. })
  9975. Image(this.cover)
  9976. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  9977. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 168))
  9978. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  9979. .alt($r('app.media.alt'))
  9980. // .geometryTransition('cover') // 绑定标识符
  9981. .margin({ right: 20, left: 20,
  9982. top:this.isCoverRectangle||this.isLandscape?0:50})
  9983. .aspectRatio(1)
  9984. .opacity(this.opacityValueImage)
  9985. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  9986. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  9987. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  9988. .align(Alignment.Center)//
  9989. .clip(true)
  9990. .shadow({
  9991. radius: 22,
  9992. type: ShadowType.BLUR,
  9993. color: 'on_primary'
  9994. })
  9995. .rotate({
  9996. x: 0,
  9997. y: 0,
  9998. z: 1,
  9999. angle: this.rotateAngle
  10000. })
  10001. .onClick(() => {
  10002. this.isMusicBGCover = !this.isMusicBGCover
  10003. })
  10004. // 唱针以左上角为点选择逆时针40度
  10005. Image($r('app.media.ic_music_cover_hand'))
  10006. .height(130)
  10007. .margin({ bottom: 200, top: 0 })
  10008. // .position({ x: this.windowWidth/2, y: 0 })
  10009. .align(Alignment.Top)
  10010. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  10011. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  10012. .visibility(this.isHiCar()||this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  10013. }
  10014. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  10015. // 设置左下角为缩放中心点
  10016. centerX: '0%',
  10017. centerY: '100%' })
  10018. }
  10019. @Builder
  10020. private musicNameInfo(isHidden: boolean) {
  10021. Row(){
  10022. Column({ space: 8 }) {
  10023. Text(this.name)
  10024. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 20)
  10025. .fontWeight(FontWeight.Bold)
  10026. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  10027. .maxLines(1)
  10028. .width('99%')
  10029. .textAlign(TextAlign.Start)
  10030. .fontColor(Color.White)
  10031. Text(this.artist + ' ' + this.currentSong?.album)
  10032. .fontSize(this.isCoverOpacity() ? 12 : 15)
  10033. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  10034. .fontColor(Color.White)
  10035. .textAlign(TextAlign.Start)
  10036. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  10037. .width('99%')
  10038. .maxLines(1)
  10039. }
  10040. .zIndex(1)
  10041. .layoutWeight(1)
  10042. .margin({ left: 15 })
  10043. Blank()
  10044. Row(){
  10045. Button({type:ButtonType.Circle,stateEffect:true}){
  10046. //添加或取消收藏
  10047. SymbolGlyph(Utility.getIsFav(this.favList,this.currentSong)?
  10048. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'))
  10049. .fontSize(22)
  10050. .fontColor([Color.White])
  10051. .alignSelf(ItemAlign.Center)
  10052. // .width(24)
  10053. .clickEffect({level:ClickEffectLevel.MIDDLE})
  10054. .aspectRatio(CommonConstants.ASPECT_RATIO)
  10055. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  10056. .onClick(async () => {
  10057. if(this.currentSong){
  10058. this.doFav(this.currentSong)
  10059. }
  10060. })
  10061. }
  10062. .margin({ left: 8,right:8 })
  10063. .backgroundColor(Color.Transparent)
  10064. .width(45)
  10065. .height(45)
  10066. }
  10067. }
  10068. .width(this.isLandscape?'83%':'90%')
  10069. .scale({ x: this.scaleValueText, y: this.scaleValueText }) // 添加缩放效果
  10070. .margin({ top:this.isCoverRectangle?10: 0 })
  10071. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  10072. }
  10073. @Builder
  10074. private PlayTitle() {
  10075. Row() {
  10076. Row() {
  10077. Image($r('app.media.ic_back_down'))
  10078. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  10079. .hitTestBehavior(HitTestMode.Transparent)
  10080. Text(this.name + ' ' + this.artist)
  10081. .fontColor(Color.White)
  10082. .fontSize($r('app.float.title_font_size'))
  10083. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  10084. .maxLines(1)
  10085. .visibility(Visibility.None)
  10086. .margin({ left: 2, right: 30 })
  10087. }
  10088. .layoutWeight(1)
  10089. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10090. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  10091. .onClick(() => {
  10092. this.setShowPlayFalse()
  10093. })
  10094. Column() {
  10095. AVCastPicker({
  10096. normalColor: Color.White,
  10097. onStateChange: this.onStateVastChange
  10098. })
  10099. .width(24)
  10100. .height(24)
  10101. }
  10102. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  10103. }
  10104. .width(PlayConstants.ROW_WIDTH)
  10105. }
  10106. @Builder
  10107. lyricSettingSheet(isPip: boolean) {
  10108. Scroll() {
  10109. this.lyricSetting(isPip)
  10110. }
  10111. .width('100%')
  10112. .height('100%')
  10113. }
  10114. @Builder
  10115. lyricSetting(isPip: boolean) {
  10116. Column() {
  10117. // 时间调节模块
  10118. if (!isPip) {
  10119. this.BuildTimeControls()
  10120. }
  10121. // 字号控制模块
  10122. this.BuildFontControls(isPip)
  10123. }
  10124. }
  10125. // 歌词时间偏移状态
  10126. @State timeOffset: number = 0.0
  10127. @State currentLyricColor: string = '#FFFFFF'
  10128. @State currentLyricColorPip: string = '#FFFFFF'
  10129. @State currentHighLightLyricColor: string = '#FF4081'
  10130. @State currentHighLightLyricColorPip: string = '#FF4081'
  10131. // 歌词字号状态
  10132. @State currentLyricSize: number = 20
  10133. @State currentLyricSizePip: number = 20
  10134. // 高亮歌词放大倍数
  10135. @State currentHightLyricSize: number = 1.2
  10136. @State currentHightLyricSizePip: number = 1.2
  10137. @State currentLyricLineSpace: number = 10
  10138. @State currentLyricLineSpacePip: number = 10
  10139. @State currentLyricAlignMode: number = 1
  10140. @State currentLyricAlignModePip: number = 1
  10141. @State blurDegree: number = 2
  10142. @State blurDegreePip: number = 2
  10143. @State isShowSelectColor: boolean = false
  10144. @State isShowHLSelectColor: boolean = false
  10145. @State isShowPipBgSelectColor: boolean = false
  10146. @State pipLyWidth: number = 330
  10147. @State pipLyHeight: number = 120
  10148. // 构建颜色选择器
  10149. @Builder
  10150. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  10151. Row({ space: 10 }) {
  10152. HSBColorPicker({
  10153. color: '#FFFFFF',
  10154. radius: 8,
  10155. layout: HSBColorPickerLayout.COLUMN,
  10156. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  10157. '#fa7105'],
  10158. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  10159. this.changeLyricColor(value, isPip, isBGPip)
  10160. })
  10161. .height(250)
  10162. .layoutWeight(1)
  10163. .padding(25)
  10164. }
  10165. .width('66%')
  10166. }
  10167. @State isOpenPip: boolean = false
  10168. @State pipBgIndex: number = 0
  10169. // 构建字号控制器
  10170. @Builder
  10171. BuildFontControls(isPip: boolean) {
  10172. Column() {
  10173. if (isPip) {
  10174. Column() {
  10175. Row() {
  10176. Text('悬浮歌词')
  10177. .margin({ left: 18 })
  10178. .fontSize(15)
  10179. .fontColor(Color.White)
  10180. .fontWeight(480)
  10181. .layoutWeight(1)
  10182. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  10183. .selectedColor(this.themeColor)
  10184. .switchPointColor(Color.White)
  10185. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10186. .margin({ right: 18 })
  10187. .onChange((checked: boolean) => {
  10188. this.isOpenPip = checked;
  10189. if (this.isOpenPip) {
  10190. this.startPip()
  10191. } else {
  10192. this.stopPip()
  10193. }
  10194. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  10195. })
  10196. .width(50)
  10197. .height(30);
  10198. }
  10199. .height(55)
  10200. }
  10201. .backgroundColor(Color.Transparent)
  10202. .borderRadius(15)
  10203. .margin({
  10204. left: 30,
  10205. right: 30,
  10206. top: 0,
  10207. bottom: 20
  10208. })
  10209. .padding(0)
  10210. .border({
  10211. color: Color.White,
  10212. width: 1.8
  10213. })
  10214. }else{
  10215. Column() {
  10216. Row() {
  10217. Text('单行歌词')
  10218. .margin({ left: 18 })
  10219. .fontSize(15)
  10220. .fontColor(Color.White)
  10221. .fontWeight(480)
  10222. .layoutWeight(1)
  10223. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  10224. .selectedColor(this.themeColor)
  10225. .switchPointColor(Color.White)
  10226. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10227. .margin({ right: 18 })
  10228. .onChange((checked: boolean) => {
  10229. this.isShowSingleLineLyric = checked;
  10230. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  10231. })
  10232. .width(50)
  10233. .height(30);
  10234. }
  10235. .height(55)
  10236. }
  10237. .backgroundColor(Color.Transparent)
  10238. .borderRadius(15)
  10239. .margin({
  10240. left: 30,
  10241. right: 30,
  10242. top: 10,
  10243. bottom: 10
  10244. })
  10245. .padding(0)
  10246. .border({
  10247. color: Color.White,
  10248. width: 1.8
  10249. })
  10250. }
  10251. Row() {
  10252. Text(`歌词居中:`)
  10253. .fontSize(14)
  10254. .fontColor(Color.White)
  10255. .margin({ left: 2 })
  10256. Row() {
  10257. ForEach(['居中', '居左'], (size: string, index: number) => {
  10258. Button(size)
  10259. .width(60)
  10260. .height(28)
  10261. .fontSize(12)
  10262. .fontColor('#FFFFFF')
  10263. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  10264. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  10265. .border({
  10266. color: (!isPip && this.currentLyricAlignMode === index) ||
  10267. (isPip && this.currentLyricAlignModePip === index) ?
  10268. '#007DFF' : '#DDDDDD',
  10269. width: 1.8
  10270. })
  10271. .onClick(() => {
  10272. this.setLyricAlignMode(index, isPip)
  10273. })
  10274. .margin({ left: 10, right: 8 })
  10275. })
  10276. }
  10277. .width('76%')
  10278. Blank()
  10279. }
  10280. .margin({
  10281. top: 10,
  10282. bottom: 10,
  10283. right: 20,
  10284. left: 20
  10285. })
  10286. if (isPip) {
  10287. Row() {
  10288. Text(`悬浮背景:`)
  10289. .fontSize(14)
  10290. .fontColor(Color.White)
  10291. Select([
  10292. { value: CommonConstants.PIP_LYRIC_BG[0] },
  10293. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  10294. .font({ size: 13, weight: FontWeight.Medium })
  10295. .fontColor(Color.White)
  10296. .margin({ left: 10 })
  10297. .selected(this.pipBgIndex)
  10298. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  10299. .onSelect(async (_index: number, text?: string | undefined) => {
  10300. this.pipBgIndex = _index
  10301. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  10302. if (this.pipBgIndex === 0) {
  10303. if (this.cover) {
  10304. this.pipBg = this.cover
  10305. } else {
  10306. this.pipBg = this.imageColor
  10307. }
  10308. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  10309. } else {
  10310. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  10311. }
  10312. })
  10313. Column() {
  10314. }
  10315. .backgroundColor(this.pipBg)
  10316. .margin({ left: 10, right: 10 })
  10317. .borderRadius(20)
  10318. .height(28)
  10319. .width(28)
  10320. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10321. Row() {
  10322. SymbolGlyph($r('sys.symbol.paintbrush'))
  10323. .fontColor([Color.White])
  10324. .effectStrategy(1)
  10325. Text(`选择颜色`)
  10326. .fontSize(13)
  10327. .margin({ left: 10 })
  10328. .fontColor(Color.White)
  10329. }
  10330. }
  10331. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  10332. .backgroundColor(Color.Transparent)
  10333. .border({
  10334. color: '#FFFFFF',
  10335. radius: 20,
  10336. width: 1.8
  10337. })
  10338. .height(36)
  10339. .width(110)
  10340. .onClick(() => {
  10341. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  10342. })
  10343. .bindPopup(this.isShowPipBgSelectColor, {
  10344. builder: this.SelectColor(false, isPip, true),
  10345. placement: Placement.Top,
  10346. mask: { color: '#33000000' },
  10347. enableArrow: false, //是否显示箭头
  10348. showInSubWindow: false,
  10349. onStateChange: (e) => {
  10350. if (!e.isVisible) {
  10351. this.isShowPipBgSelectColor = false
  10352. }
  10353. }
  10354. })
  10355. }
  10356. .width('76%')
  10357. .margin({ bottom: 5, right: 45, left: 20 })
  10358. }
  10359. if (!isPip) {
  10360. Row() {
  10361. Text(`高亮居中:`)
  10362. .fontSize(14)
  10363. .fontColor(Color.White)
  10364. Column() {
  10365. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  10366. .selectedColor(this.themeColor)
  10367. .switchPointColor(Color.White)
  10368. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10369. .onChange((checked: boolean) => {
  10370. this.isHightLightCenter = checked;
  10371. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  10372. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  10373. })
  10374. .width(50)
  10375. .height(30)
  10376. .alignSelf(ItemAlign.Start)
  10377. .margin({ left: 12 })
  10378. Blank()
  10379. }
  10380. .width('76%')
  10381. }
  10382. .margin({
  10383. left: 20,
  10384. right: 15,
  10385. top: 10,
  10386. bottom: 10
  10387. })
  10388. }
  10389. Row() {
  10390. Text(`歌词颜色:`)
  10391. .fontSize(14)
  10392. .fontColor(Color.White)
  10393. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  10394. .fontSize(15)
  10395. .fontColor(Color.White)
  10396. .margin({ left: 12, right: 12 })
  10397. Column() {
  10398. }
  10399. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  10400. .margin({ right: 12 })
  10401. .borderRadius(20)
  10402. .height(28)
  10403. .width(28)
  10404. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10405. Row() {
  10406. SymbolGlyph($r('sys.symbol.paintbrush'))
  10407. .fontColor([Color.White])
  10408. .effectStrategy(1)
  10409. Text(`选择颜色`)
  10410. .fontSize(13)
  10411. .margin({ left: 10 })
  10412. .fontColor(Color.White)
  10413. }
  10414. }
  10415. .backgroundColor(Color.Transparent)
  10416. .border({
  10417. color: '#FFFFFF',
  10418. radius: 20,
  10419. width: 1.8
  10420. })
  10421. .height(36)
  10422. .width(110)
  10423. .onClick(() => {
  10424. this.isShowSelectColor = !this.isShowSelectColor
  10425. })
  10426. .bindPopup(this.isShowSelectColor, {
  10427. builder: this.SelectColor(false, isPip),
  10428. placement: Placement.Top,
  10429. mask: { color: '#33000000' },
  10430. enableArrow: false, //是否显示箭头
  10431. showInSubWindow: false,
  10432. onStateChange: (e) => {
  10433. if (!e.isVisible) {
  10434. this.isShowSelectColor = false
  10435. }
  10436. }
  10437. })
  10438. }
  10439. .width('76%')
  10440. .margin({
  10441. top: 10,
  10442. bottom: 10,
  10443. right: 45,
  10444. left: 20
  10445. })
  10446. Row() {
  10447. Text(`高亮颜色:`)
  10448. .fontSize(14)
  10449. .fontColor(Color.White)
  10450. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  10451. .fontSize(15)
  10452. .fontColor(Color.White)
  10453. .margin({ left: 12, right: 12 })
  10454. Column() {
  10455. }
  10456. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  10457. .margin({ right: 12 })
  10458. .borderRadius(20)
  10459. .height(28)
  10460. .width(28)
  10461. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10462. Row() {
  10463. SymbolGlyph($r('sys.symbol.paintbrush'))
  10464. .fontColor([Color.White])
  10465. .effectStrategy(1)
  10466. Text(`选择颜色`)
  10467. .fontSize(13)
  10468. .margin({ left: 10 })
  10469. .fontColor(Color.White)
  10470. }
  10471. }
  10472. .backgroundColor(Color.Transparent)
  10473. .border({
  10474. color: '#FFFFFF',
  10475. radius: 20,
  10476. width: 1.8
  10477. })
  10478. .height(36)
  10479. .width(110)
  10480. .onClick(() => {
  10481. this.isShowHLSelectColor = !this.isShowHLSelectColor
  10482. })
  10483. .bindPopup(this.isShowHLSelectColor, {
  10484. builder: this.SelectColor(true, isPip),
  10485. placement: Placement.Top,
  10486. mask: { color: '#33000000' },
  10487. enableArrow: false, //是否显示箭头
  10488. showInSubWindow: false,
  10489. onStateChange: (e) => {
  10490. if (!e.isVisible) {
  10491. this.isShowHLSelectColor = false
  10492. }
  10493. }
  10494. })
  10495. }
  10496. .width('76%')
  10497. .margin({
  10498. top: 10,
  10499. bottom: 10,
  10500. right: 45,
  10501. left: 20
  10502. })
  10503. if (isPip) {
  10504. Row() {
  10505. Text(`显示宽度:`)
  10506. .fontSize(14)
  10507. .fontColor(Color.White)
  10508. Slider({
  10509. value: this.pipLyWidth,
  10510. min: 10,
  10511. max: 800,
  10512. step: 1,
  10513. style: SliderStyle.OutSet
  10514. })
  10515. .blockColor(this.themeColor)
  10516. .trackColor($r('app.color.speed_text_color'))
  10517. .selectedColor(Color.White)
  10518. .trackThickness(6)
  10519. .onChange((value: number) => {
  10520. this.pipLyWidth = value
  10521. if (this.pipController) {
  10522. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10523. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  10524. }
  10525. })
  10526. .width('76%')
  10527. }
  10528. .margin({
  10529. left: 20,
  10530. right: 15,
  10531. top: 5,
  10532. bottom: 5
  10533. })
  10534. Row() {
  10535. Text(`显示高度:`)
  10536. .fontSize(14)
  10537. .fontColor(Color.White)
  10538. Slider({
  10539. value: this.pipLyHeight,
  10540. min: 10,
  10541. max: 1000,
  10542. step: 1,
  10543. style: SliderStyle.OutSet
  10544. })
  10545. .blockColor(this.themeColor)
  10546. .trackColor($r('app.color.speed_text_color'))
  10547. .selectedColor(Color.White)
  10548. .trackThickness(6)
  10549. .onChange((value: number) => {
  10550. this.pipLyHeight = value
  10551. if (this.pipController) {
  10552. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10553. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  10554. }
  10555. })
  10556. .width('76%')
  10557. }
  10558. .margin({
  10559. left: 20,
  10560. right: 15,
  10561. top: 5,
  10562. bottom: 5
  10563. })
  10564. }
  10565. Row() {
  10566. Text(`歌词字号:`)
  10567. .fontSize(14)
  10568. .fontColor(Color.White)
  10569. Slider({
  10570. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  10571. min: 12,
  10572. max: 30,
  10573. step: 0.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.setLyricTextSize(value, isPip)
  10582. })
  10583. .width('76%')
  10584. }
  10585. .margin({
  10586. left: 20,
  10587. right: 15,
  10588. top: 5,
  10589. bottom: 5
  10590. })
  10591. Row() {
  10592. Text(`高亮倍数:`)
  10593. .fontSize(14)
  10594. .fontColor(Color.White)
  10595. Slider({
  10596. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  10597. min: 1,
  10598. max: 2,
  10599. step: 0.1,
  10600. style: SliderStyle.OutSet
  10601. })
  10602. .blockColor(this.themeColor)
  10603. .trackColor($r('app.color.speed_text_color'))
  10604. .selectedColor(Color.White)
  10605. .trackThickness(6)
  10606. .onChange((value: number) => {
  10607. this.setHighLyricTextSize(value, isPip)
  10608. })
  10609. .width('76%')
  10610. }
  10611. .margin({
  10612. left: 20,
  10613. right: 15,
  10614. top: 5,
  10615. bottom: 5
  10616. })
  10617. Row() {
  10618. Text(`歌词间隙:`)
  10619. .fontSize(14)
  10620. .fontColor(Color.White)
  10621. Slider({
  10622. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  10623. min: 0,
  10624. max: 100,
  10625. step: 1,
  10626. style: SliderStyle.OutSet
  10627. })
  10628. .blockColor(this.themeColor)
  10629. .trackColor($r('app.color.speed_text_color'))
  10630. .selectedColor(Color.White)
  10631. .trackThickness(6)
  10632. .onChange((value: number) => {
  10633. this.setLyricLineSpace(value, isPip)
  10634. })
  10635. .width('76%')
  10636. }
  10637. .margin({
  10638. left: 20,
  10639. right: 15,
  10640. top: 5,
  10641. bottom: 5
  10642. })
  10643. //取值间隔为100,默认为400,取值越大,字体越粗
  10644. Row() {
  10645. Text(`歌词字重:`)
  10646. .fontSize(14)
  10647. .fontColor(Color.White)
  10648. Slider({
  10649. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  10650. min: 100,
  10651. max: 900,
  10652. step: 100,
  10653. style: SliderStyle.OutSet
  10654. })
  10655. .blockColor(this.themeColor)
  10656. .trackColor($r('app.color.speed_text_color'))
  10657. .selectedColor(Color.White)
  10658. .trackThickness(6)
  10659. .onChange((value: number) => {
  10660. if (isPip) {
  10661. this.lyricTextWeightPip = value
  10662. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  10663. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  10664. } else {
  10665. this.lyricTextWeight = value
  10666. this.lyricController.setTextWeight(this.lyricTextWeight)
  10667. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  10668. }
  10669. })
  10670. .width('76%')
  10671. }
  10672. .margin({
  10673. left: 20,
  10674. right: 15,
  10675. top: 5,
  10676. bottom: 5
  10677. })
  10678. if (!isPip) {
  10679. Row() {
  10680. Text(`歌词模糊:`)
  10681. .fontSize(14)
  10682. .fontColor(Color.White)
  10683. Slider({
  10684. value: isPip ? this.blurDegreePip : this.blurDegree,
  10685. min: 0,
  10686. max: 5,
  10687. step: 0.1,
  10688. style: SliderStyle.OutSet
  10689. })
  10690. .blockColor(this.themeColor)
  10691. .trackColor($r('app.color.speed_text_color'))
  10692. .selectedColor(Color.White)
  10693. .trackThickness(6)
  10694. .onChange((value: number) => {
  10695. this.setBlurDegree(value, isPip)
  10696. })
  10697. .width('76%')
  10698. }
  10699. .margin({
  10700. left: 20,
  10701. right: 15,
  10702. top: 5,
  10703. bottom: 15
  10704. })
  10705. }
  10706. Row() {
  10707. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  10708. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  10709. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  10710. }
  10711. .justifyContent(FlexAlign.Center)
  10712. .margin({ top: 3, bottom: 10 })
  10713. }
  10714. }
  10715. private setBlurDegree(index: number, isPip: boolean) {
  10716. if (isPip) {
  10717. this.blurDegreePip = index
  10718. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  10719. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  10720. } else {
  10721. this.blurDegree = index
  10722. this.lyricController.setBlurDegree(this.blurDegree)
  10723. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  10724. }
  10725. }
  10726. private setLyricAlignMode(index: number, isPip: boolean) {
  10727. if (isPip) {
  10728. this.currentLyricAlignModePip = index
  10729. if (this.currentLyricAlignModePip === 1) {
  10730. this.lyricControllerXF.setAlignMode("left")
  10731. } else {
  10732. this.lyricControllerXF.setAlignMode("center")
  10733. }
  10734. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  10735. } else {
  10736. this.currentLyricAlignMode = index
  10737. if (this.currentLyricAlignMode === 1) {
  10738. this.lyricController.setAlignMode("left")
  10739. } else {
  10740. this.lyricController.setAlignMode("center")
  10741. }
  10742. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  10743. }
  10744. }
  10745. private setLyricTextSize(index: number, isPip: boolean) {
  10746. if (isPip) {
  10747. this.currentLyricSizePip = index
  10748. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  10749. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  10750. } else {
  10751. this.currentLyricSize = index
  10752. this.lyricController.setTextSize(this.currentLyricSize)
  10753. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  10754. }
  10755. }
  10756. private setHighLyricTextSize(scale: number, isPip: boolean) {
  10757. if (isPip) {
  10758. this.currentHightLyricSizePip = scale
  10759. this.lyricControllerXF
  10760. .setHighlightScale(this.currentHightLyricSizePip)
  10761. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  10762. } else {
  10763. this.currentHightLyricSize = scale
  10764. this.lyricController
  10765. .setHighlightScale(this.currentHightLyricSize)
  10766. PreferencesUtil.putSync('HighLyricTextSize', scale)
  10767. }
  10768. }
  10769. private setLyricLineSpace(index: number, isPip: boolean) {
  10770. if (isPip) {
  10771. this.currentLyricLineSpacePip = index
  10772. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  10773. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  10774. } else {
  10775. this.currentLyricLineSpace = index
  10776. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  10777. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  10778. }
  10779. }
  10780. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  10781. LogUtil.info('onecold isBG = ' + isBG)
  10782. if (isBG) { //如果是设置悬浮背景
  10783. this.pipBg = color
  10784. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  10785. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  10786. return
  10787. }
  10788. if (isPip) {
  10789. this.currentLyricColorPip = color
  10790. this.lyricControllerXF
  10791. .setTextColor(this.currentLyricColorPip)
  10792. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  10793. } else {
  10794. this.currentLyricColor = color
  10795. this.lyricController
  10796. .setTextColor(this.currentLyricColor)
  10797. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  10798. }
  10799. }
  10800. private changeLyricHightLightColor(color: string, isPip: boolean) {
  10801. if (isPip) {
  10802. this.currentHighLightLyricColorPip = color
  10803. this.lyricControllerXF
  10804. .setHighlightColor(this.currentHighLightLyricColorPip)
  10805. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  10806. } else {
  10807. this.currentHighLightLyricColor = color
  10808. this.lyricController
  10809. .setHighlightColor(this.currentHighLightLyricColor)
  10810. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  10811. }
  10812. }
  10813. // 构建时间控制器
  10814. @Builder
  10815. BuildTimeControls() {
  10816. Column() {
  10817. // 时间显示
  10818. Text(this.getTimeText())
  10819. .fontSize(18)
  10820. .fontColor(Color.White)
  10821. .margin({ bottom: 10 })
  10822. Row() {
  10823. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  10824. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  10825. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  10826. }
  10827. .justifyContent(FlexAlign.Center)
  10828. }
  10829. .margin({ top: 12, bottom: 8 })
  10830. }
  10831. // 精度按钮组件
  10832. @Builder
  10833. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  10834. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10835. Column() {
  10836. Image(icon)
  10837. .width(28)
  10838. .margin({ bottom: 5 })
  10839. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  10840. Text(label)
  10841. .fontSize(12)
  10842. .fontColor('#FFFFFF')
  10843. }
  10844. }
  10845. .backgroundColor(Color.Transparent)
  10846. .enabled(!this.isButtonDisabled(step))
  10847. .onClick(() => this.handlePrecisionAdjust(step))
  10848. .padding(5)
  10849. .width(66)
  10850. .height(66)
  10851. .margin({ left: 18, right: 18 })
  10852. .border({
  10853. color: '#FFFFFF',
  10854. width: 1.8
  10855. })
  10856. }
  10857. private handlePrecisionAdjust(step: number) {
  10858. if (step === 0) {
  10859. this.timeOffset = 0
  10860. return
  10861. }
  10862. // 精度处理:保留1位小数
  10863. const newOffset = Number((this.timeOffset + step).toFixed(5))
  10864. // 边界保护(±15.0秒)
  10865. if (newOffset < -30.0 || newOffset > 30.0) {
  10866. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  10867. return
  10868. }
  10869. // 状态更新
  10870. this.timeOffset = newOffset
  10871. }
  10872. // 按钮禁用逻辑
  10873. private isButtonDisabled(step: number): boolean {
  10874. const futureOffset = this.timeOffset + step
  10875. return (futureOffset < -30.0) || (futureOffset > 30.0)
  10876. }
  10877. // 时间显示文本升级
  10878. private getTimeText(): string {
  10879. const absValue = Math.abs(this.timeOffset)
  10880. return this.timeOffset === 0
  10881. ? '歌词时间已重置'
  10882. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  10883. }
  10884. // 导入 本地歌词 搜索歌词
  10885. @Builder
  10886. pushLyricButton(icon: Resource, step: number, label: string) {
  10887. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10888. Row() {
  10889. Image(icon)
  10890. .width(14)
  10891. .margin({ left: 13 })
  10892. Text(label)
  10893. .fontSize(12)
  10894. .margin({ left: 6 })
  10895. .fontColor('#FFFFFF')
  10896. }
  10897. }
  10898. .onClick(() => {
  10899. switch (step) {
  10900. case 0:
  10901. this.callFilePickerSelectFileForLyric()
  10902. break;
  10903. case 1:
  10904. //判断有没有设置api
  10905. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  10906. this.isLyricSetting = false
  10907. this.showTipsDialog()
  10908. return
  10909. }
  10910. if (StrUtil.isNotEmpty(this.videoUrl)) {
  10911. ToastUtil.showToast('正在获取')
  10912. this.isLyricSetting = false
  10913. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  10914. this.initLyric(lyricPath, true);
  10915. }
  10916. break;
  10917. }
  10918. })
  10919. .padding(5)
  10920. .width(110)
  10921. .backgroundColor(Color.Transparent)
  10922. .height(40)
  10923. .margin({ left: 6, right: 6 })
  10924. .border({
  10925. color: '#FFFFFF',
  10926. radius: 20,
  10927. width: 1.8
  10928. })
  10929. }
  10930. showVipDialog() {
  10931. DialogHelper.showCustomContentDialog({
  10932. dialogId: 'vip',
  10933. title: "友情提示",
  10934. autoCancel: false, //点击遮障层时,不关闭弹窗
  10935. backCancel: true, //点击返回键,不关闭弹窗
  10936. contentBuilder: () => {
  10937. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  10938. },
  10939. buttons: [],
  10940. })
  10941. }
  10942. //去赞助的自定义内容
  10943. @Builder
  10944. customVipBuilder(content: string) {
  10945. Column() {
  10946. Text(content)
  10947. .fontColor(Color.Gray)
  10948. .fontSize(16)
  10949. .alignSelf(ItemAlign.Start)
  10950. .margin({ bottom: 15 })
  10951. .fontSize(16)
  10952. Row() {
  10953. Button('取消')
  10954. .fontColor(Color.White)
  10955. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  10956. .height(50)
  10957. .layoutWeight(1)
  10958. .stateEffect(true)
  10959. .margin({ right: 6 })
  10960. .onClick(() => {
  10961. DialogHelper.closeDialog('vip'); //关闭弹框
  10962. })
  10963. Button('开通')
  10964. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  10965. .layoutWeight(1)
  10966. .height(50)
  10967. .backgroundColor(this.themeColor)
  10968. .stateEffect(true)
  10969. .margin({ left: 6 })
  10970. .onClick(() => {
  10971. DialogHelper.closeDialog('vip'); //关闭弹框
  10972. this.isShowPlay = false
  10973. this.mType = 1 //跳转到用户中心
  10974. // router.pushUrl({
  10975. // url: 'pages/VipPage'
  10976. // }, router.RouterMode.Single);
  10977. })
  10978. }
  10979. }
  10980. .width("100%")
  10981. .padding(10)
  10982. }
  10983. showTipsDialog() {
  10984. DialogHelper.showCustomContentDialog({
  10985. dialogId: 'tips',
  10986. title: "友情提示",
  10987. autoCancel: false, //点击遮障层时,不关闭弹窗
  10988. backCancel: true, //点击返回键,不关闭弹窗
  10989. contentBuilder: () => {
  10990. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  10991. },
  10992. buttons: [],
  10993. })
  10994. }
  10995. @Builder
  10996. customTipsBuilder(content: string) {
  10997. Column() {
  10998. Text(content)
  10999. .fontColor(Color.Gray)
  11000. .fontSize(16)
  11001. .alignSelf(ItemAlign.Start)
  11002. .margin({ bottom: 15 })
  11003. .fontSize(16)
  11004. Row() {
  11005. Button('取消')
  11006. .fontColor(Color.White)
  11007. .backgroundColor(this.themeColor)
  11008. .height(50)
  11009. .layoutWeight(1)
  11010. .stateEffect(true)
  11011. .margin({ right: 6 })
  11012. .onClick(() => {
  11013. DialogHelper.closeDialog('tips'); //关闭弹框
  11014. })
  11015. Button('跳转')
  11016. .fontColor(Color.White)//
  11017. .layoutWeight(1)
  11018. .height(50)
  11019. .backgroundColor(this.themeColor)
  11020. .stateEffect(true)
  11021. .margin({ left: 6 })
  11022. .onClick(() => {
  11023. DialogHelper.closeDialog('tips'); //关闭弹框
  11024. this.isShowEdit = false
  11025. this.longItemFilePath = ''
  11026. // if(this.isGridMusic&&!this.isShowPlay){
  11027. // this.longItemFilePath== ''
  11028. // }else{
  11029. // this.isShowEdit = false
  11030. // }
  11031. this.isShowMoreView = false;
  11032. this.isShowPlay = false
  11033. this.mType = 4
  11034. // router.pushUrl({
  11035. // url: 'pages/SettingPage'
  11036. // }, router.RouterMode.Single);
  11037. })
  11038. }
  11039. }
  11040. .width("100%")
  11041. .padding(10)
  11042. }
  11043. @Builder
  11044. PlayMoreSheet() {
  11045. Column() {
  11046. this.MoreList()
  11047. }
  11048. .width('100%')
  11049. .height('100%')
  11050. }
  11051. @Builder
  11052. MoreList() {
  11053. Scroll() {
  11054. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  11055. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  11056. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  11057. Row() {
  11058. if (more.id === 3&&this.currentSong) {
  11059. Image(more.image)
  11060. .width(24)
  11061. .height(24)
  11062. .margin({ left: 10, right: 10 })
  11063. Text(more.title)
  11064. .fontSize(16)
  11065. .fontColor(Color.White)
  11066. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  11067. height: '99%',
  11068. dragBar: true,
  11069. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11070. showClose: true,
  11071. blurStyle: BlurStyle.Thin,
  11072. backgroundColor: Color.Transparent,
  11073. title: { title: '歌曲信息' }
  11074. })
  11075. } else if (more.id === 15 && this.currentSong) { //编辑标签
  11076. Image(more.image)
  11077. .width(24)
  11078. .height(24)
  11079. .margin({ left: 10, right: 10 })
  11080. Text(more.title)
  11081. .fontSize(16)
  11082. .fontColor(Color.White)
  11083. } else if (more.id === 5) { //定时关闭
  11084. Image(more.image)
  11085. .width(24)
  11086. .height(24)
  11087. .margin({ left: 10, right: 10 })
  11088. Text(more.title)
  11089. .fontSize(16)
  11090. .fontColor(Color.White)
  11091. .onClick(() => {
  11092. this.doMore(more.id)
  11093. })
  11094. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  11095. height: this.isCoverOpacity() ? '95%' : '95%',
  11096. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11097. dragBar: true,
  11098. showClose: true,
  11099. title: { title: $r('app.string.time_close') }
  11100. })
  11101. } else if (more.id === 2) { //歌词设置
  11102. Image(more.image)
  11103. .width(24)
  11104. .height(24)
  11105. .margin({ left: 10, right: 10 })
  11106. Text(more.title)
  11107. .fontSize(16)
  11108. .fontColor(Color.White)
  11109. } else if (more.id === 16) { //悬浮歌词设置
  11110. Image(more.image)
  11111. .width(24)
  11112. .height(24)
  11113. .margin({ left: 10, right: 10 })
  11114. Text(more.title)
  11115. .fontSize(16)
  11116. .fontColor(Color.White)
  11117. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  11118. height: '99%',
  11119. dragBar: true,
  11120. preferType: SheetType.CENTER,
  11121. showClose: true,
  11122. blurStyle: BlurStyle.Thin,
  11123. backgroundColor: Color.Transparent,
  11124. title: { title: '悬浮歌词' }
  11125. })
  11126. } else if (more.id === 11) {
  11127. Image(more.image)
  11128. .width(24)
  11129. .height(24)
  11130. .margin({ left: 10, right: 10 })
  11131. Text(more.title)
  11132. .fontSize(16)
  11133. .fontColor(Color.White)
  11134. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  11135. height: this.isCoverOpacity() ? '95%' : '60%',
  11136. dragBar: true,
  11137. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11138. showClose: true,
  11139. blurStyle: BlurStyle.Thin,
  11140. backgroundColor: Color.Transparent,
  11141. title: { title: '跳过头尾' }
  11142. })
  11143. } else if (more.id === 12) { //投播
  11144. AVCastPicker({
  11145. customPicker: (): void => this.TPImageBuilder(more),
  11146. onStateChange: (state) => {
  11147. if (state == AVCastPickerState.STATE_APPEARING) {
  11148. console.log(' The picker starts showing.');
  11149. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  11150. console.log(' The picker finishes presenting.');
  11151. }
  11152. },
  11153. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  11154. sessionType: 'video'
  11155. })
  11156. .id('AVCastPicker')
  11157. } else {
  11158. Image(more.image)
  11159. .width(24)
  11160. .height(24)
  11161. .fillColor(Color.White)
  11162. .margin({ left: 10, right: 10 })
  11163. .onClick(() => {
  11164. this.doMore(more.id)
  11165. })
  11166. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  11167. .fontSize(16)
  11168. .fontColor(Color.White)
  11169. .onClick(() => {
  11170. this.doMore(more.id)
  11171. })
  11172. Select([//倍速
  11173. { value: '0.25x' },
  11174. { value: '0.5x' },
  11175. { value: '0.75x' },
  11176. { value: '1x' },
  11177. { value: '1.25x' },
  11178. { value: '1.5x' },
  11179. { value: '1.75x' },
  11180. { value: '2x' },
  11181. { value: '3x' }])
  11182. .font({ size: 16, weight: FontWeight.Medium })
  11183. .fontColor($r('sys.color.white'))
  11184. .margin({ left: 25 })
  11185. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  11186. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  11187. .value(Utility.optimizedFormat(this.playSpeed))
  11188. .onSelect(async (_index: number, text?: string | undefined) => {
  11189. let speed = parseFloat(text?.replace('x', '') || '1');
  11190. if (!CommonConstants.video_speed_list.includes(speed)) {
  11191. speed = 1;
  11192. }
  11193. this.playSpeed = speed
  11194. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  11195. })
  11196. Slider({
  11197. value: this.volume,
  11198. min: 0,
  11199. max: 1,
  11200. step: 0.1,
  11201. style: SliderStyle.OutSet
  11202. })
  11203. .margin({ left: 18, right: 8 })
  11204. .blockColor(this.themeColor)
  11205. .trackColor($r('app.color.speed_text_color'))
  11206. .selectedColor(Color.White)
  11207. .trackThickness(9)
  11208. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  11209. .onChange((value: number) => {
  11210. this.volume = value;
  11211. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  11212. PreferencesUtil.putSync('DefalutVolume',this.volume)
  11213. })
  11214. .layoutWeight(1)
  11215. Blank()
  11216. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  11217. .selectedColor(this.themeColor)
  11218. .switchPointColor(Color.White)
  11219. .margin({ right: 15 })
  11220. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11221. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  11222. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11223. if (more.id == 6) {
  11224. this.isMusicMemoryPlay = checked;
  11225. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  11226. if (this.isMusicMemoryPlay) {
  11227. ToastUtil.showToast('记忆播放已开启')
  11228. } else {
  11229. ToastUtil.showToast('记忆播放已关闭')
  11230. }
  11231. }
  11232. })
  11233. .width(48)
  11234. .height(24);
  11235. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  11236. .selectedColor(this.themeColor)
  11237. .switchPointColor(Color.White)
  11238. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11239. .margin({ right: 15 })
  11240. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  11241. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11242. if (more.id == 7) {
  11243. this.isMusicBGCover = checked;
  11244. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  11245. if (this.isMusicBGCover) {
  11246. ToastUtil.showToast('播放背景随音乐封面已开启')
  11247. } else {
  11248. ToastUtil.showToast('播放背景随音乐封面已关闭')
  11249. }
  11250. }
  11251. })
  11252. .width(48)
  11253. .height(24);
  11254. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  11255. .selectedColor(this.themeColor)
  11256. .switchPointColor(Color.White)
  11257. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11258. .margin({ right: 15 })
  11259. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  11260. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11261. if (more.id == 8) {
  11262. this.isSavePlayMode = checked;
  11263. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  11264. if (this.isSavePlayMode) {
  11265. ToastUtil.showToast('保存播放模式已开启')
  11266. } else {
  11267. ToastUtil.showToast('保存播放模式已关闭')
  11268. }
  11269. }
  11270. })
  11271. .width(48)
  11272. .height(24);
  11273. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  11274. .selectedColor(this.themeColor)
  11275. .switchPointColor(Color.White)
  11276. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11277. .margin({ right: 15 })
  11278. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  11279. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11280. if (more.id == 13) {
  11281. this.isCoverRectangle = checked;
  11282. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  11283. if (this.isCoverRectangle) {
  11284. ToastUtil.showToast('封面方形已开启')
  11285. this.animationRoFun()
  11286. } else {
  11287. ToastUtil.showToast('封面圆形已开启')
  11288. this.animationRoFun()
  11289. }
  11290. }
  11291. })
  11292. .width(48)
  11293. .height(24);
  11294. Toggle({ type: ToggleType.Switch, isOn: this.isShowBgLiuGUANG })
  11295. .selectedColor(this.themeColor)
  11296. .switchPointColor(Color.White)
  11297. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11298. .margin({ right: 15 })
  11299. .visibility(more.id == 21 ? Visibility.Visible : Visibility.None)
  11300. .onChange((checked: boolean) => { // 是否开启背景流光效果
  11301. if (more.id == 21) {
  11302. this.isShowBgLiuGUANG = checked;
  11303. PreferencesUtil.putSync('isShowBgLiuGUANG',this.isShowBgLiuGUANG)
  11304. }
  11305. })
  11306. .width(48)
  11307. .height(24);
  11308. }
  11309. }
  11310. .width('100%')
  11311. .height(45)
  11312. .padding(15)
  11313. .backgroundColor(Color.Transparent)
  11314. .borderRadius(12)
  11315. .margin({ bottom: 6 })
  11316. }
  11317. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  11318. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  11319. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  11320. .backgroundColor(Color.Transparent)
  11321. .onClick(() => {
  11322. this.doMore(more.id)
  11323. })
  11324. });
  11325. }
  11326. .width('100%')
  11327. .padding(16)
  11328. }.margin({ bottom: 18 })
  11329. }
  11330. @Builder
  11331. TPImageBuilder(more: MoreItem): void {
  11332. Row() {
  11333. Image($r('app.media.tuoping'))
  11334. .width(22)
  11335. .height(22)
  11336. .margin({ left: 10, right: 10 })
  11337. Text(more.title)
  11338. .fontSize(16)
  11339. .fontColor(Color.White)
  11340. }
  11341. .width('100%')
  11342. .layoutWeight(1)
  11343. .alignItems(VerticalAlign.Center)
  11344. .justifyContent(FlexAlign.Start)
  11345. }
  11346. private moreItems: MoreItem[] = [
  11347. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  11348. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  11349. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  11350. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  11351. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  11352. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  11353. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  11354. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  11355. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  11356. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  11357. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  11358. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  11359. { id: 4, image: $r('app.media.share2'), title: '分享' },
  11360. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  11361. // { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  11362. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  11363. { id : 21, image: $r('app.media.kp_music'), title: '开启背景流光' },
  11364. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  11365. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  11366. ];
  11367. @State isShowBgLiuGUANG: boolean = false;
  11368. @State isShowMoreView: boolean = false;
  11369. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  11370. @State isShowTimeCloseMore: boolean = false
  11371. @State isShowDetailMore: boolean = false
  11372. @State isMusicBGCover: boolean = true
  11373. @State isSavePlayMode: boolean = true
  11374. @State isLyricSetting: boolean = false
  11375. @State isJumpSetting: boolean = false
  11376. @State isShowEdit: boolean = false
  11377. @State showPipLyric: boolean = false
  11378. async setRingTone() {
  11379. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  11380. return
  11381. }
  11382. // 确定后的逻辑
  11383. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  11384. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  11385. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  11386. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  11387. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  11388. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  11389. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  11390. , this.videoUrl, this.name).then(res => {
  11391. LogUtil.info('onecold setFlag :' + res);
  11392. });
  11393. }
  11394. doMore(moreId: number) {
  11395. switch (moreId) {
  11396. case 2: //歌词
  11397. this.isLyricSetting = !this.isLyricSetting;
  11398. this.isShowMoreView = false
  11399. break;
  11400. case 3: //详情
  11401. this.isShowDetailMore = !this.isShowDetailMore;
  11402. break;
  11403. case 4: //分享
  11404. if (this.currentSong !== undefined) {
  11405. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  11406. }
  11407. this.isShowMoreView = false
  11408. break;
  11409. case 5: //定时关闭
  11410. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  11411. break;
  11412. case 10: //设为铃声
  11413. this.setRingTone()
  11414. this.isShowMoreView = false
  11415. break;
  11416. case 11: //跳过头尾
  11417. this.isJumpSetting = !this.isJumpSetting;
  11418. break;
  11419. case 13: //倍速
  11420. break;
  11421. case 14: //搜索封面
  11422. if (this.currentSong !== undefined) {
  11423. this.doSearchCover(this.currentSong)
  11424. }
  11425. this.isShowMoreView = false
  11426. break;
  11427. case 15: //编辑标签
  11428. this.initEditFields(this.currentSong)
  11429. this.tempLyricContent = this.lyricContent
  11430. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  11431. this.lyricConStr = this.tempLyricContent
  11432. }
  11433. this.isShowEdit = !this.isShowEdit;
  11434. break;
  11435. case 16: //悬浮歌词
  11436. this.showPipLyric = !this.showPipLyric;
  11437. break;
  11438. case 17: //横屏模式
  11439. if (this.isLandscape) {
  11440. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  11441. } else {
  11442. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  11443. }
  11444. this.isShowMoreView = false
  11445. break;
  11446. case 20://AB循环
  11447. this.isABSheet = !this.isABSheet
  11448. break;
  11449. }
  11450. }
  11451. //AB循环
  11452. @State isOpenAB:boolean = false
  11453. @State jumpATime:number = 0
  11454. @State jumpBTime:number = 0
  11455. @State isABSheet:boolean = false
  11456. @Builder
  11457. ABLoopSheet() {
  11458. ABLoopComptent({
  11459. jumpATime:this.jumpATime,
  11460. jumpBTime:this.jumpBTime,
  11461. onClickAItem: async ()=>{
  11462. if(this.mIjkMediaPlayer){
  11463. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  11464. }
  11465. },
  11466. onClickBItem: async ()=>{
  11467. if(this.mIjkMediaPlayer){
  11468. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  11469. if(this.jumpBTime<=this.jumpATime){
  11470. ToastUtil.showToast('设置B点时间不能小于A点时间')
  11471. this.jumpBTime = 0
  11472. }
  11473. }
  11474. },
  11475. onCancleButtonClick: async ()=>{
  11476. this.isOpenAB = false
  11477. this.isABSheet = false
  11478. },
  11479. onStartButtonClick: async ()=>{
  11480. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  11481. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  11482. return
  11483. }
  11484. this.isABSheet = false
  11485. this.startABLoop()
  11486. },
  11487. })
  11488. }
  11489. //开始AB循环
  11490. startABLoop(){
  11491. if(this.mIjkMediaPlayer){
  11492. this.seekTo(this.jumpATime+'')
  11493. this.isOpenAB = true
  11494. }
  11495. }
  11496. /**
  11497. * 切换横竖屏
  11498. *
  11499. */
  11500. setOrientation(orientation: number) {
  11501. this.windowClass.setPreferredOrientation(orientation).then(() => {
  11502. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  11503. }).catch((err: BusinessError) => {
  11504. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  11505. });
  11506. }
  11507. /**
  11508. * 画中画功能(悬浮歌词功能)
  11509. *
  11510. */
  11511. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  11512. pipController?: PiPWindow.PiPController;
  11513. navigationId: string = '';
  11514. @State curState: string = '';
  11515. @State curError: ResourceStr = '';
  11516. @State pipBg: string = '#E8E8E8'
  11517. @State buttonAction: string = '';
  11518. //开启画中画功能
  11519. async startPip() {
  11520. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  11521. if (!this.pipController) {
  11522. await this.createPipController();
  11523. }
  11524. if (!this.pipController) {
  11525. Logger.info(`[${TAG}] pipController create error`);
  11526. return;
  11527. }
  11528. await this.pipController.startPiP();
  11529. }
  11530. async stopPip() {
  11531. if (!this.pipController) {
  11532. Logger.info(`[${TAG}] pipController is not exist`);
  11533. return;
  11534. }
  11535. this.isOpenPip = false
  11536. await this.pipController.stopPiP();
  11537. }
  11538. async createPipController() {
  11539. this.pipController = await PiPWindow.create({
  11540. context: getContext(this),
  11541. componentController: this.xcomponentController,
  11542. navigationId: this.navigationId,
  11543. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  11544. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  11545. customUIController: this.nodeController,
  11546. });
  11547. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  11548. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  11549. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  11550. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  11551. this.onStateChange(state, reason);
  11552. });
  11553. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  11554. this.onActionEvent(event, status);
  11555. });
  11556. }
  11557. destroyPipController() {
  11558. if (!this.pipController) {
  11559. return;
  11560. }
  11561. this.pipController.off('stateChange');
  11562. this.pipController.off('controlPanelActionEvent');
  11563. this.pipController = undefined;
  11564. }
  11565. onStateChange(state: PiPWindow.PiPState, reason: string) {
  11566. switch (state) {
  11567. case PiPWindow.PiPState.ABOUT_TO_START:
  11568. this.curState = 'ABOUT_TO_START';
  11569. this.curError = $r('app.string.current_error_hint');
  11570. break;
  11571. case PiPWindow.PiPState.STARTED:
  11572. this.curState = 'STARTED';
  11573. this.curError = $r('app.string.current_error_hint');
  11574. break;
  11575. case PiPWindow.PiPState.ABOUT_TO_STOP:
  11576. this.curState = 'ABOUT_TO_STOP';
  11577. this.curError = $r('app.string.current_error_hint');
  11578. break;
  11579. case PiPWindow.PiPState.STOPPED:
  11580. this.curState = 'STOPPED';
  11581. this.curError = $r('app.string.current_error_hint');
  11582. this.stopPip()
  11583. this.destroyPipController()
  11584. break;
  11585. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  11586. this.curState = 'ABOUT_TO_RESTORE';
  11587. this.curError = $r('app.string.current_error_hint');
  11588. break;
  11589. case PiPWindow.PiPState.ERROR:
  11590. this.curState = 'ERROR';
  11591. this.curError = reason;
  11592. break;
  11593. default:
  11594. break;
  11595. }
  11596. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  11597. }
  11598. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  11599. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  11600. switch (event) {
  11601. case 'playbackStateChanged':
  11602. if (status === 0) {
  11603. this.pause();
  11604. } else {
  11605. console.info('onecold startPlayOrResumePlay 9869')
  11606. this.startPlayOrResumePlay();
  11607. }
  11608. break;
  11609. case 'nextVideo':
  11610. // 切换到下一个视频
  11611. this.playNext().catch(() => {
  11612. Logger.error('heanup onActionEvent playNext', `播放下一首失败`);
  11613. });
  11614. break;
  11615. case 'previousVideo':
  11616. // 切换到上一个视频
  11617. this.playPrevious().catch(() => {
  11618. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败`);
  11619. });
  11620. break;
  11621. case 'previousVideo':
  11622. // 切换到上一个视频
  11623. this.playPrevious().catch(() => {
  11624. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败:`);
  11625. });
  11626. break;
  11627. default:
  11628. }
  11629. this.buttonAction = event + `-status:${status}`;
  11630. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  11631. }
  11632. /**
  11633. * 画中画功能(悬浮歌词功能)结束
  11634. *
  11635. */
  11636. async doSearchCover(item: VideoItem,title?:string,artist?:string): Promise<string> {
  11637. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  11638. this.isShowMoreView = false;
  11639. this.showTipsDialog();
  11640. return ''; // Return empty string when no API is configured
  11641. }
  11642. if (!item) {
  11643. return ''; // Return empty string if item is undefined
  11644. }
  11645. const titleS = title||item?.name || '';
  11646. const artistS = artist||item?.artist || ''; // Use empty string if artist is missing
  11647. return this.searchCover(item, titleS, artistS); // Await is not needed here as we return the promise directly
  11648. }
  11649. /**
  11650. *api搜索封面
  11651. *item,根据title和artist
  11652. */
  11653. searchCover(item: VideoItem, title: string, artist: string): Promise<string> {
  11654. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  11655. LogUtil.debug("onecold res =" + res);
  11656. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  11657. if (item.filePath == this.currentSong?.filePath) {
  11658. this.cover = res;
  11659. if (this.currentSong) {
  11660. this.currentSong.pixelMapPath = res;
  11661. }
  11662. }
  11663. // Update pixel map path but always return res regardless of success
  11664. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  11665. if (success) {
  11666. this.doUpdateData();
  11667. console.log("onecold 更新音乐封面成功,数据库已同步");
  11668. } else {
  11669. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  11670. }
  11671. // Note: We don't resolve/reject here because we already returned res
  11672. });
  11673. LogUtil.debug("onecold this.cover =" + this.cover);
  11674. }
  11675. return res; // Always return res regardless of updatePixelMapPath result
  11676. });
  11677. }
  11678. @State jumpTopTime: number = 0
  11679. @State jumpEndTime: number = 0
  11680. @State isOpenJump: boolean = false
  11681. @Builder
  11682. JumpTopEndSheet() {
  11683. Scroll() {
  11684. Column() {
  11685. Column() {
  11686. Text('仅对本播放列表有效')
  11687. .fontSize(16)
  11688. .fontColor($r('app.color.text_color'))
  11689. // 跳过头尾
  11690. Column() {
  11691. Row() {
  11692. Text('跳过片头:')
  11693. .fontSize(16)
  11694. .fontColor($r('app.color.text_color'))
  11695. Text(this.jumpTopTime + 's')
  11696. .fontSize(16)
  11697. .fontColor($r('app.color.text_color'))
  11698. }
  11699. .margin({ bottom: 5 })
  11700. Row() {
  11701. Slider({
  11702. value: this.jumpTopTime,
  11703. min: 0,
  11704. max: 120,
  11705. step: 1,
  11706. style: SliderStyle.OutSet
  11707. })
  11708. .blockColor(this.themeColor)
  11709. .trackColor($r('app.color.speed_text_color'))
  11710. .selectedColor(Color.White)
  11711. .trackThickness(8)
  11712. .onChange((value: number) => {
  11713. this.jumpTopTime = value;
  11714. })
  11715. .width('85%')
  11716. }
  11717. .alignItems(VerticalAlign.Top)
  11718. }
  11719. .margin({ top: 10, bottom: 10 })
  11720. // 跳过头尾
  11721. Column() {
  11722. Row() {
  11723. Text('跳过片尾:')
  11724. .fontSize(16)
  11725. .fontColor($r('app.color.text_color'))
  11726. Text(this.jumpEndTime + 's')
  11727. .fontSize(16)
  11728. .fontColor($r('app.color.text_color'))
  11729. }
  11730. .margin({ bottom: 5 })
  11731. Row() {
  11732. Slider({
  11733. value: this.jumpEndTime,
  11734. min: 0,
  11735. max: 120,
  11736. step: 1,
  11737. style: SliderStyle.OutSet
  11738. })
  11739. .blockColor(this.themeColor)
  11740. .trackColor($r('app.color.speed_text_color'))
  11741. .selectedColor(Color.White)
  11742. .trackThickness(8)
  11743. .onChange((value: number) => {
  11744. this.jumpEndTime = value;
  11745. })
  11746. .width('85%')
  11747. }
  11748. .alignItems(VerticalAlign.Top)
  11749. }
  11750. .margin({ top: 10, bottom: 10 })
  11751. Row() {
  11752. Button('保存设置')
  11753. .fontColor(Color.White)
  11754. .layoutWeight(1)
  11755. .height(40)
  11756. .width(80)
  11757. .backgroundColor(this.themeColor)
  11758. .stateEffect(true)
  11759. .margin({ left: 0, bottom: 20 })
  11760. .onClick(async () => {
  11761. if (!Utility.isNoble()) {
  11762. this.isJumpSetting = false
  11763. this.isShowMoreView = false
  11764. this.showVipDialog()
  11765. return
  11766. }
  11767. if (this.currentSong === undefined) {
  11768. return
  11769. }
  11770. if (this.modeType === 0) {
  11771. let parentPath = FileUtil.getParentPath(this.videoUrl)
  11772. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  11773. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  11774. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  11775. } else if (this.modeType === 1) { //媒体库
  11776. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  11777. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  11778. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  11779. } else if (this.modeType === 2) { //艺术家
  11780. if (this.currentSong?.artist) {
  11781. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  11782. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  11783. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  11784. }
  11785. } else if (this.modeType === 3) { //专辑
  11786. if (this.currentSong?.album) {
  11787. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  11788. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  11789. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  11790. }
  11791. }
  11792. ToastUtil.showShort("保存成功")
  11793. this.isJumpSetting = false
  11794. })
  11795. }
  11796. .margin({
  11797. left: 38,
  11798. right: 38,
  11799. top: 10,
  11800. bottom: 10
  11801. })
  11802. .width(120)
  11803. .height(50)
  11804. }
  11805. }
  11806. }
  11807. .width('100%')
  11808. .height('100%')
  11809. }
  11810. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  11811. private onStateVastChange(state: AVCastPickerState) {
  11812. if (state == AVCastPickerState.STATE_APPEARING) {
  11813. console.log('The picker starts showing.');
  11814. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  11815. console.log('The picker finishes presenting.');
  11816. }
  11817. }
  11818. private showSelectLyric() {
  11819. DialogHelper.showActionSheetDialog({
  11820. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  11821. // sheets: ["本地歌词", "搜索歌词"],
  11822. sheets: [
  11823. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  11824. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  11825. ],
  11826. maskColor: Color.Transparent,
  11827. backgroundColor: $r('app.color.bg_card'),
  11828. transition: AnimationHelper.transitionInDown(666),
  11829. onAction: (index) => {
  11830. switch (index) {
  11831. case 0:
  11832. this.callFilePickerSelectFileForLyric()
  11833. break;
  11834. case 1:
  11835. if (StrUtil.isNotEmpty(this.videoUrl)) {
  11836. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  11837. this.initLyric(lyricPath);
  11838. }
  11839. break;
  11840. }
  11841. }
  11842. })
  11843. }
  11844. // 拉起picker选择文件管理器
  11845. async callFilePickerSelectFileForLyric(): Promise<void> {
  11846. try {
  11847. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  11848. DocumentSelectOptions.maxSelectNumber = 1
  11849. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  11850. let documentPicker = new picker.DocumentViewPicker();
  11851. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  11852. Logger.info(TAG,
  11853. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  11854. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  11855. this.saveVideoDatasLyric(DocumentSelectResult)
  11856. }
  11857. }).catch((err: BusinessError) => {
  11858. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  11859. });
  11860. } catch (err) {
  11861. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  11862. }
  11863. }
  11864. async saveVideoDatasLyric(uris: string[]) {
  11865. if (ArrayUtil.isEmpty(uris)) {
  11866. return
  11867. }
  11868. let newUris: string[] = [];
  11869. for (let i = 0; i < uris.length; i++) {
  11870. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  11871. Logger.info(TAG, 'filePath uri: ' + filePath);
  11872. newUris.push(filePath)
  11873. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  11874. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  11875. fileIo.copyFileSync(file.fd, file2.fd)
  11876. fileIo.closeSync(file);
  11877. fileIo.closeSync(file2);
  11878. this.initLyric(filePath,false,false,true)
  11879. }
  11880. }
  11881. private initDelayPlay(context: object) {
  11882. this.mContext = context;
  11883. }
  11884. startPipLyric() {
  11885. if (this.pipController) {
  11886. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  11887. PiPWindow.PiPControlStatus.PLAY);
  11888. }
  11889. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  11890. if (this.isOpenPip) {
  11891. this.startPip()
  11892. } else {
  11893. this.stopPip()
  11894. }
  11895. }
  11896. //startOffset 从cue分轨时间开始播
  11897. private startPlayOrResumePlay(startOffset?:number) {
  11898. //针对dsf文件高采样率,统一转wav播放
  11899. const sampleRate = this.currentSong?.sampleRate||0
  11900. if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  11901. console.info('onecold 采样率 ='+sampleRate)
  11902. let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  11903. console.info('onecold newDsfPath ='+newDsfPath)
  11904. if(!FileUtil.accessSync(newDsfPath)){
  11905. const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  11906. taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  11907. this.videoUrl = newDsfPath
  11908. this.startPlay(startOffset)
  11909. }).catch((e:object)=>{
  11910. console.info("task1 catch e: " + e);
  11911. })
  11912. }else{
  11913. this.videoUrl = newDsfPath
  11914. this.startPlay(startOffset)
  11915. }
  11916. }else{
  11917. this.startPlay(startOffset)
  11918. }
  11919. }
  11920. startPlay(startOffset?:number) {
  11921. this.startPipLyric()
  11922. this.mDestroyPage = false;
  11923. this.animationState = AnimationStatus.Running
  11924. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  11925. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  11926. this.stopProgressTask();
  11927. this.startProgressTask();
  11928. this.play(this.videoUrl.toString(),startOffset);
  11929. }
  11930. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  11931. this.mIjkMediaPlayer.start();
  11932. this.setProgress()
  11933. this.CONTROL_PlayStatus = PlayStatus.PLAY
  11934. }
  11935. this.setIsPlaying(true)
  11936. this.updateSessionPlayState(true)
  11937. this.watchStatus();
  11938. this.updateLastPlayTimeStr(this.videoUrl)
  11939. }
  11940. updateLastPlayTimeStr(filePath: string) {
  11941. // 检查是否为网络音频(WebDAV),如果是则不更新本地数据库
  11942. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  11943. Logger.info(`heanup 检测到网络音频播放,跳过数据库更新: ${filePath}`)
  11944. return;
  11945. }
  11946. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  11947. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  11948. if (success) {
  11949. this.getHistoryList(false)
  11950. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  11951. } else {
  11952. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  11953. }
  11954. });
  11955. }
  11956. private completionNum(num: number): string | number {
  11957. if (num < 10) {
  11958. return '0' + num;
  11959. } else {
  11960. return num;
  11961. }
  11962. }
  11963. private stringForTime(timeMs: number): string {
  11964. let totalSeconds: number | string = (timeMs / 1000);
  11965. let newSeconds: number | string = totalSeconds % 60;
  11966. let minutes: number | string = (totalSeconds / 60) % 60;
  11967. let hours: number | string = totalSeconds / 3600;
  11968. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  11969. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  11970. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  11971. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  11972. if (this.isCurrentTime) {
  11973. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  11974. this.oldSeconds = newSeconds
  11975. } else {
  11976. newSeconds = this.oldSeconds
  11977. }
  11978. }
  11979. newSeconds = this.completionNum(newSeconds);
  11980. if (hours > 0) {
  11981. return hours + ":" + minutes + ":" + newSeconds;
  11982. } else {
  11983. return minutes + ":" + newSeconds;
  11984. }
  11985. }
  11986. private setProgress() {
  11987. let position = this.mIjkMediaPlayer.getCurrentPosition();
  11988. let duration = this.mIjkMediaPlayer.getDuration();
  11989. if (duration <= 0 && this.duration > 0) {
  11990. duration = this.duration;
  11991. }
  11992. let pos = 0;
  11993. if (duration > 0) {
  11994. this.slideEnable = true;
  11995. let curPercent = position / duration;
  11996. pos = curPercent * 100;
  11997. if (pos > this.PROGRESS_MAX_VALUE) {
  11998. this.progressValue = this.PROGRESS_MAX_VALUE
  11999. } else {
  12000. this.progressValue = pos;
  12001. }
  12002. }
  12003. // LogUtils.getInstance()
  12004. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  12005. this.totalTime = this.stringForTime(duration);
  12006. if (position > duration) {
  12007. position = duration;
  12008. }
  12009. this.isCurrentTime = true;
  12010. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  12011. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  12012. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  12013. this.currentTime = this.stringForTime(position);
  12014. this.isCurrentTime = false
  12015. if (this.mIjkMediaPlayer.isPlaying()) {
  12016. this.randomColor =
  12017. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  12018. //如果是开启AB循环
  12019. if(this.isOpenAB){
  12020. if(position >=this.jumpBTime){
  12021. this.seekTo(this.jumpATime+'')
  12022. return
  12023. }
  12024. }
  12025. // 判断是否播放到结束时间
  12026. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  12027. if (position >= duration - this.jumpEndTime * 1000) {
  12028. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  12029. this.CONTROL_PlayStatus = PlayStatus.INIT
  12030. this.startPlayOrResumePlay();
  12031. }else if (this.playType == 2) { //2:正常播放,单曲播完
  12032. this.showRePlay();
  12033. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  12034. this.progressValue = this.PROGRESS_MAX_VALUE;
  12035. this.slideEnable = false;
  12036. this.stop();
  12037. // ToastUtil.showToast('开始重新播放')
  12038. }else{
  12039. this.playNext().catch(() => {
  12040. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  12041. });
  12042. }
  12043. }
  12044. }
  12045. } else {
  12046. this.randomColor = 'rbg(0,0,0)'
  12047. }
  12048. }
  12049. private startProgressTask() {
  12050. let that = this;
  12051. this.updateProgressTimer = setInterval(() => {
  12052. //LogUtils.getInstance().LOGI("startProgressTask");
  12053. if (!that.mDestroyPage) {
  12054. that.setProgress();
  12055. }
  12056. }, 300);
  12057. }
  12058. private stopProgressTask() {
  12059. LogUtils.getInstance().LOGI("stopProgressTask");
  12060. clearInterval(this.updateProgressTimer);
  12061. }
  12062. private showLoadIng() {
  12063. this.loadingVisible = Visibility.Visible;
  12064. this.replayVisible = Visibility.None;
  12065. }
  12066. private hideLoadIng() {
  12067. this.loadingVisible = Visibility.None;
  12068. this.replayVisible = Visibility.None;
  12069. }
  12070. private showRePlay() {
  12071. this.loadingVisible = Visibility.None;
  12072. this.replayVisible = Visibility.Visible;
  12073. }
  12074. private async play(url: string,startOffset?:number) {
  12075. this.isShowBgLiuGUANG = PreferencesUtil.getBooleanSync('isShowBgLiuGUANG', false)
  12076. console.info('onecold this.url 1= '+url)
  12077. if(!url.toLowerCase().startsWith('http')){
  12078. let hasPermission = await PermissionUtil.activatePermission(url)
  12079. console.info('onecold this.hasPermission 1= '+hasPermission)
  12080. if(!url.includes(this.packName)){
  12081. const file = fs.openSync(url)
  12082. this.videoUrl = file.path
  12083. url= this.videoUrl
  12084. }
  12085. console.info('onecold this.hasPermission 1= '+hasPermission)
  12086. console.info('onecold this.videoUrl 1= '+this.videoUrl)
  12087. }
  12088. let that = this;
  12089. that.showLoadIng();
  12090. this.isOpenAB = false
  12091. //设置XComponent回调的context
  12092. if (!!this.mContext) {
  12093. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  12094. }
  12095. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  12096. this.mIjkMediaPlayer.reset();
  12097. }
  12098. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  12099. //设置debug模式
  12100. this.mIjkMediaPlayer.setDebug(false);
  12101. //初始化配置
  12102. this.mIjkMediaPlayer.native_setup();
  12103. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  12104. if(this.volumeSmall){
  12105. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  12106. this.mIjkMediaPlayer.setVolume('1', '1');
  12107. }else{
  12108. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  12109. }
  12110. }else{
  12111. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  12112. }
  12113. //设置视频源
  12114. Logger.info(TAG, `IjkPlayer setDataSource url=${url}`);
  12115. this.mIjkMediaPlayer.setDataSource(url);
  12116. // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
  12117. const headers = new Map<string, string>();
  12118. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  12119. headers.set("Accept", "*/*");
  12120. if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
  12121. &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
  12122. //如果封面为空,则搜索封面
  12123. this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
  12124. }
  12125. // 如果是WebDAV网络音频,使用webdav_account_id获取认证信息(等待完成后再设置一次性头部)
  12126. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type)) {
  12127. Logger.info(`heanup WebDAV歌曲认证 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
  12128. if (this.currentSong.webdav_account_id) {
  12129. try {
  12130. const webdavManager = RemoteDriveManager.getInstance();
  12131. const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  12132. if (webDavHeaders && webDavHeaders.size > 0) {
  12133. webDavHeaders.forEach((value, key) => headers.set(key, value));
  12134. Logger.info(`heanup 成功通过webdav_account_id获取并合并WebDAV认证头`);
  12135. } else {
  12136. Logger.warn(`heanup 通过webdav_account_id获取认证头失败,播放可能无法继续`);
  12137. }
  12138. } catch (error) {
  12139. const err = error as Error;
  12140. Logger.error(`heanup 获取WebDAV认证头时出错: ${err.message}`);
  12141. }
  12142. } else {
  12143. Logger.error(`heanup WebDAV歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法进行认证`);
  12144. }
  12145. }
  12146. // 统一设置带认证的请求头
  12147. // 百度类型也需要特殊请求头
  12148. if (this.currentSong && isBaiduType(this.currentSong.type)) {
  12149. try {
  12150. const webdavManager = RemoteDriveManager.getInstance();
  12151. const baiduHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  12152. baiduHeaders.forEach((value, key) => headers.set(key, value));
  12153. const headerSnapshot: Record<string, string> = {};
  12154. headers.forEach((value, key) => headerSnapshot[key] = value);
  12155. Logger.info(TAG, `Baidu播放请求头: ${JSON.stringify(headerSnapshot)}`);
  12156. } catch (error) {
  12157. Logger.error(`heanup 构建百度请求头失败: ${(error as Error).message}`);
  12158. }
  12159. }
  12160. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  12161. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type)) {
  12162. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  12163. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  12164. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  12165. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  12166. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  12167. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  12168. // 缓冲和播放优化设置
  12169. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  12170. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  12171. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1"); // 预加载启动
  12172. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  12173. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  12174. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  12175. // 网络相关设置
  12176. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  12177. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  12178. // 重连设置
  12179. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  12180. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  12181. } else if (this.currentSong && isBaiduType(this.currentSong.type)) {
  12182. console.log(`heanup 为百度网盘播放设置IjkPlayer选项`);
  12183. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "15000000");
  12184. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "15000000");
  12185. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1");
  12186. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "1");
  12187. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "2097152");
  12188. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "25");
  12189. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", BaiduConstants.USER_AGENT);
  12190. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", "3");
  12191. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http-detect-range-support", "1");
  12192. console.log(`heanup 百度网盘 IjkPlayer 选项设置完成`);
  12193. }
  12194. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  12195. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  12196. // }
  12197. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  12198. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  12199. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  12200. let bufferSize = 50 * 1024 ; // 默认缓冲区大小为1MB
  12201. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  12202. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  12203. //停止预读的最小帧数
  12204. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  12205. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  12206. // 设置其他缓冲相关选项
  12207. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  12208. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  12209. //启动预加载
  12210. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  12211. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  12212. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  12213. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  12214. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  12215. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  12216. // 因此需要播放器丢包,才不会累积延时
  12217. // 这个和第三个参数packet-buffering无关。
  12218. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  12219. // 无限制收流
  12220. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  12221. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  12222. // 屏幕常亮
  12223. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  12224. // 开启hls起播优化 默认是关闭的
  12225. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "fetch_first", "on");
  12226. // 设置超时
  12227. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  12228. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  12229. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  12230. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  12231. // 变速播放
  12232. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  12233. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  12234. let Speed = this.mIjkMediaPlayer.getSpeed()
  12235. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  12236. //是否开启循环播放
  12237. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  12238. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  12239. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  12240. if (height === 0) {
  12241. return;
  12242. }
  12243. const va = width / height;
  12244. const vpa = that.videoParentAspectRatio;
  12245. if (vpa > va) {
  12246. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  12247. } else {
  12248. that.videoWidth = '100%';
  12249. }
  12250. if (width && height) {
  12251. that.videoAspectRatio = width / height;
  12252. }
  12253. LogUtils.getInstance()
  12254. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  12255. that.hideLoadIng();
  12256. }
  12257. }
  12258. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  12259. let mOnPreparedListener: OnPreparedListener = {
  12260. onPrepared: async () => {
  12261. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  12262. try {
  12263. //保存碰一碰分享的当前的歌曲
  12264. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  12265. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  12266. await this.initLyric(lyricPath);
  12267. const applyDuration = (durationMs: number): void => {
  12268. if (durationMs <= 0) {
  12269. return;
  12270. }
  12271. this.duration = durationMs;
  12272. this.durationTime = Math.floor(durationMs / 1000);
  12273. this.durationStringTime = secondToTime(this.durationTime);
  12274. this.totalTime = this.stringForTime(durationMs);
  12275. if (this.currentSong) {
  12276. this.currentSong.duration = this.totalTime;
  12277. try {
  12278. this.avSessionController.setAVMetadataMusic(this.currentSong, durationMs, this.lyricContent);
  12279. } catch (metaError) {
  12280. Logger.warn(TAG, `heanup 首次播放写入AVSession失败: ${(metaError as Error).message}`);
  12281. }
  12282. }
  12283. };
  12284. const fetchBaiduM3u8Duration = async (url: string): Promise<number> => {
  12285. if (!url || !isBaiduType(this.currentSong?.type ?? -1)) {
  12286. return 0;
  12287. }
  12288. const httpRequest = http.createHttp();
  12289. try {
  12290. const response = await httpRequest.request(url, {
  12291. method: http.RequestMethod.GET,
  12292. connectTimeout: 8000,
  12293. readTimeout: 8000,
  12294. expectDataType: http.HttpDataType.STRING,
  12295. header: {
  12296. 'User-Agent': BaiduConstants.STREAMING_USER_AGENT,
  12297. 'Host': 'pan.baidu.com'
  12298. }
  12299. });
  12300. if (response.responseCode !== 200 || typeof response.result !== 'string') {
  12301. return 0;
  12302. }
  12303. const text = response.result;
  12304. if (text.indexOf('#EXTM3U') < 0) {
  12305. return 0;
  12306. }
  12307. const lines = text.split('\n');
  12308. let totalSeconds = 0;
  12309. for (let i = 0; i < lines.length; i++) {
  12310. const line = lines[i].trim();
  12311. if (line.startsWith('#EXTINF:')) {
  12312. const colonIndex = line.indexOf(':');
  12313. if (colonIndex < 0) {
  12314. continue;
  12315. }
  12316. const content = line.substring(colonIndex + 1);
  12317. const commaIndex = content.indexOf(',');
  12318. const numberPart = commaIndex >= 0 ? content.substring(0, commaIndex) : content;
  12319. const seconds = Number(numberPart);
  12320. if (!Number.isNaN(seconds) && seconds > 0) {
  12321. totalSeconds += seconds;
  12322. }
  12323. }
  12324. }
  12325. if (totalSeconds > 0) {
  12326. return Math.floor(totalSeconds * 1000);
  12327. }
  12328. return 0;
  12329. } catch (fetchError) {
  12330. Logger.warn(TAG, `heanup 解析百度M3U8时长失败: ${(fetchError as Error).message}`);
  12331. return 0;
  12332. } finally {
  12333. httpRequest.destroy();
  12334. }
  12335. };
  12336. const fetchDurationFallback = async (): Promise<void> => {
  12337. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  12338. if (durationMs > 0) {
  12339. Logger.info(TAG, `heanup 通过M3U8推导出时长: ${durationMs}ms`);
  12340. applyDuration(durationMs);
  12341. return;
  12342. }
  12343. Logger.warn(TAG, 'heanup 首次播放未拿到时长,保持未知');
  12344. };
  12345. const preparedDuration = this.mIjkMediaPlayer.getDuration();
  12346. console.info("onecold preparedDuration--" + preparedDuration)
  12347. if (preparedDuration > 0) {
  12348. applyDuration(preparedDuration);
  12349. } else {
  12350. fetchDurationFallback();
  12351. }
  12352. setTimeout(() => {
  12353. this.avSessionController.initAvSession(false);
  12354. if (this.duration > 0) {
  12355. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  12356. }
  12357. this.setAvSessionListener();
  12358. this.updateSessionPlayState(true)
  12359. this.setCurrentPlayMode()
  12360. }, 500)
  12361. if(startOffset&&startOffset>0){//cue分轨播放
  12362. this.seekTo(startOffset + "");
  12363. this.saveLastPlayList()
  12364. return
  12365. }
  12366. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12367. let timeoutPlay = 0
  12368. if (StrUtil.isNotEmpty(this.videoUrl) &&
  12369. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  12370. timeoutPlay = 1000
  12371. }
  12372. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  12373. if (this.modeType === 0) { //文件夹
  12374. let parentPath = FileUtil.getParentPath(this.videoUrl)
  12375. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  12376. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  12377. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  12378. } else if (this.modeType === 1) { //媒体库
  12379. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  12380. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  12381. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  12382. } else if (this.modeType === 2) { //艺术家
  12383. if (this.currentSong?.artist) {
  12384. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  12385. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  12386. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  12387. }
  12388. } else if (this.modeType === 3) { //专辑
  12389. if (this.currentSong?.album) {
  12390. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  12391. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  12392. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  12393. }
  12394. }
  12395. this.duration = this.mIjkMediaPlayer.getDuration()
  12396. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  12397. if (this.mIjkMediaPlayer != null) {
  12398. let jumpTopTimeMs = this.jumpTopTime*1000;
  12399. if (jumpTopTimeMs <= this.duration) {
  12400. // 调用 seekTo 方法,跳到指定时间
  12401. if(PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY,true)){
  12402. console.log('onecold jumpTopTime = '+jumpTopTimeMs);
  12403. const position:number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  12404. console.log('onecold position = '+position);
  12405. if (position > jumpTopTimeMs) {
  12406. jumpTopTimeMs = position
  12407. }
  12408. }
  12409. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12410. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  12411. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  12412. }
  12413. }, timeoutPlay)
  12414. } else {
  12415. // 提示用户无法跳过
  12416. ToastUtil.showToast('跳过时间超过视频时长');
  12417. }
  12418. }
  12419. } else {
  12420. this.jumpTopTime = 0
  12421. this.jumpEndTime = 0
  12422. // console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  12423. // console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  12424. // console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  12425. // PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  12426. //记忆播放(每一首都会记忆播放)
  12427. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  12428. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12429. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  12430. this.restorePlaybackPosition() //读取播放记忆功能
  12431. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  12432. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  12433. this.restorePlaybackPosition() //读取播放记忆功能
  12434. }
  12435. this.isFirstStartPlay = false
  12436. }, timeoutPlay)
  12437. } else {
  12438. this.isFirstStartPlay = false
  12439. }
  12440. }
  12441. this.saveLastPlayList()
  12442. } catch (error) {
  12443. let err: BusinessError = error as BusinessError;
  12444. console.error('onecold failed with err: ' + JSON.stringify(err));
  12445. }
  12446. }
  12447. }
  12448. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  12449. let mOnTimedTextListener: OnTimedTextListener = {
  12450. onTimedText: () => {
  12451. }
  12452. }
  12453. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  12454. let mOnCompletionListener: OnCompletionListener = {
  12455. onCompletion: () => {
  12456. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  12457. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  12458. // 异步调用playNext
  12459. this.playNext().catch(() => {
  12460. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  12461. });
  12462. } else if (this.playType == 1) { //1:单片重复播放
  12463. this.CONTROL_PlayStatus = PlayStatus.INIT
  12464. that.startPlayOrResumePlay();
  12465. } else if (this.playType == 2) { //2:正常播放,单曲播完
  12466. that.showRePlay();
  12467. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  12468. that.progressValue = this.PROGRESS_MAX_VALUE;
  12469. that.slideEnable = false;
  12470. that.stop();
  12471. // ToastUtil.showToast('开始重新播放')
  12472. } else if (this.playType == 3) { //3:随机播放
  12473. // 异步调用randomPlay
  12474. this.randomPlay().catch(() => {
  12475. Logger.error('heanup OnCompletionListener randomPlay', `随机播放失败`);
  12476. });
  12477. }
  12478. }
  12479. }
  12480. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  12481. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  12482. onBufferingUpdate: (percent: number) => {
  12483. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  12484. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  12485. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  12486. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  12487. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  12488. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  12489. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  12490. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  12491. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  12492. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  12493. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  12494. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  12495. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  12496. let Looping = this.mIjkMediaPlayer.isLooping()
  12497. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  12498. }
  12499. }
  12500. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  12501. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  12502. onSeekComplete: () => {
  12503. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  12504. console.info('onecold startPlayOrResumePlay 10643')
  12505. that.startPlayOrResumePlay();
  12506. }
  12507. }
  12508. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  12509. let mOnInfoListener: OnInfoListener = {
  12510. onInfo: (what: number, extra: number) => {
  12511. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  12512. that.hideLoadIng();
  12513. }
  12514. }
  12515. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  12516. let mOnErrorListener: OnErrorListener = {
  12517. onError: (what: number, extra: number) => {
  12518. this.stopProgressTask();
  12519. LogUtils.getInstance().LOGI("heanup OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  12520. LogUtils.getInstance().LOGI('heanup 播放错误,歌曲详情:' + JSON.stringify(this.currentSong))
  12521. // 检查是否为WebDAV播放错误
  12522. let isWebDavError = false;
  12523. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.currentSong.filePath) {
  12524. try {
  12525. const globalContext = GlobalContext.getContext();
  12526. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  12527. if (webDavAuthInfo) {
  12528. isWebDavError = true;
  12529. }
  12530. } catch (error) {
  12531. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  12532. }
  12533. }
  12534. if (isWebDavError) {
  12535. Logger.error(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  12536. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  12537. // this.currentWebDavAuthInfo = null;
  12538. Logger.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  12539. // 根据错误代码提供更具体的错误信息
  12540. let errorMessage = "WebDAV播放失败";
  12541. if (what === -1) { // 网络错误
  12542. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  12543. } else if (what === -1004) { // HTTP 404
  12544. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  12545. } else if (what === -1001) { // 超时
  12546. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  12547. } else if (what === -1003) { // 无法解析主机
  12548. errorMessage = "无法连接到WebDAV服务器";
  12549. }
  12550. ToastUtil.showToast(errorMessage);
  12551. } else {
  12552. if (StrUtil.isNotEmpty(this.videoUrl) &&
  12553. !this.videoUrl.startsWith('http://') &&
  12554. !this.videoUrl.startsWith('https://') &&
  12555. !FileUtil.accessSync(this.videoUrl)) {
  12556. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  12557. }
  12558. }
  12559. that.hideLoadIng();
  12560. }
  12561. }
  12562. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  12563. this.mIjkMediaPlayer.setMessageListener();
  12564. this.mIjkMediaPlayer.prepareAsync();
  12565. this.mIjkMediaPlayer.start();
  12566. }
  12567. //保存最后播放的那首歌和已经对应的播放列表
  12568. saveLastPlayList() {
  12569. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  12570. PreferencesUtil.putSync('LastMusicList', this.songList)
  12571. }
  12572. // 清空播放记录
  12573. clearVideoHistory() {
  12574. this.table.clearPlayHistory((success: boolean, error?: string) => {
  12575. if (success) {
  12576. this.historyList = [];
  12577. this.updateListData(this.historyList)
  12578. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  12579. ToastUtil.showToast('清空播放记录成功')
  12580. } else {
  12581. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  12582. }
  12583. });
  12584. }
  12585. public async setAvSessionListener() {
  12586. if (!this.avSessionController) {
  12587. return;
  12588. }
  12589. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  12590. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  12591. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  12592. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  12593. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  12594. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  12595. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  12596. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  12597. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  12598. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  12599. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  12600. }
  12601. setLoopMode() {
  12602. let itype = this.playType + 1
  12603. if (itype >= 4) {
  12604. this.playType = 0
  12605. ToastUtil.showToast('连续播放')
  12606. } else if (itype === 1) {
  12607. this.playType = 1
  12608. ToastUtil.showToast('单曲循环')
  12609. } else if (itype === 2) {
  12610. this.playType = 2
  12611. ToastUtil.showToast('单曲播完')
  12612. } else if (itype === 3) {
  12613. this.playType = 3
  12614. ToastUtil.showToast('随机播放')
  12615. } else if (itype === 0) {
  12616. this.playType = 0
  12617. ToastUtil.showToast('连续播放')
  12618. }
  12619. PreferencesUtil.putSync('musicPlayType', this.playType)
  12620. this.setCurrentPlayMode()
  12621. }
  12622. private sessionSetLoopModeCallback = (mode: number) => {
  12623. if (this.mIjkMediaPlayer != null) {
  12624. ToastUtil.showToast('当前播放模式:' + mode)
  12625. Logger.info('onecold 当前播放模式= ' + mode)
  12626. let hmPlayMode = mode + 1
  12627. if (hmPlayMode >= 4) {
  12628. hmPlayMode = 0
  12629. }
  12630. if (hmPlayMode === 1) {
  12631. this.playType = 1
  12632. ToastUtil.showToast('单曲循环')
  12633. } else if (hmPlayMode === 0) {
  12634. this.playType = 2
  12635. ToastUtil.showToast('单曲播完')
  12636. } else if (hmPlayMode === 3) {
  12637. this.playType = 3
  12638. ToastUtil.showToast('随机播放')
  12639. } else if (hmPlayMode === 2) {
  12640. this.playType = 0
  12641. ToastUtil.showToast('连续播放')
  12642. }
  12643. PreferencesUtil.putSync('musicPlayType', this.playType)
  12644. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  12645. let playBackState: avSession.AVPlaybackState = {
  12646. loopMode: hmPlayMode,
  12647. };
  12648. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  12649. console.info(`set setLoopMode AVPlaybackState successfully`);
  12650. }).catch((err: BusinessError) => {
  12651. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  12652. });
  12653. }
  12654. }
  12655. setCurrentPlayMode() {
  12656. if (!this.avSessionController) {
  12657. return;
  12658. }
  12659. let mLoopMode = 0
  12660. switch (this.playType) {
  12661. case 0:
  12662. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  12663. break;
  12664. case 1:
  12665. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  12666. break;
  12667. case 2:
  12668. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  12669. break;
  12670. case 3:
  12671. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  12672. break;
  12673. }
  12674. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  12675. let playBState: avSession.AVPlaybackState = {
  12676. loopMode: mLoopMode,
  12677. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  12678. };
  12679. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  12680. console.info(`set setLoopMode AVPlaybackState successfully`);
  12681. }).catch((err: BusinessError) => {
  12682. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  12683. });
  12684. }
  12685. private sessionToggleFavoriteCallback = (assetId: string) => {
  12686. if (this.mIjkMediaPlayer != null && this.currentSong) {
  12687. console.info(`on toggleFavorite `);
  12688. // 应用收到收藏命令,进行收藏处理。
  12689. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  12690. this.doFav(this.currentSong)
  12691. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  12692. let playbackState: avSession.AVPlaybackState = {
  12693. isFavorite: !this.isFac,
  12694. };
  12695. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  12696. console.info(`SetAVPlaybackState successfully`);
  12697. }).catch((err: BusinessError) => {
  12698. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  12699. });
  12700. }
  12701. }
  12702. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  12703. device: avSession.OutputDeviceInfo) => {
  12704. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  12705. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  12706. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  12707. await this.startCasting();
  12708. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  12709. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  12710. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  12711. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  12712. if (device) {
  12713. this.endCasting();
  12714. }
  12715. }
  12716. };
  12717. private async startCasting() {
  12718. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  12719. this.setPlaybackStateChangeListener();
  12720. this.pause();
  12721. this.initQueueItem();
  12722. this.prepare();
  12723. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  12724. refToIsCasting?.set(true);
  12725. this.castSeek = true;
  12726. this.isCastPlaying = true;
  12727. }
  12728. async changeCasting() {
  12729. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  12730. this.initQueueItem();
  12731. this.prepare();
  12732. this.setPlaybackStateChangeListener();
  12733. this.isCastPlaying = true;
  12734. this.castSeek = true;
  12735. }
  12736. public endCasting() {
  12737. this.avSessionController.getAvSession()?.stopCasting();
  12738. this.stopCast();
  12739. this.isCastPlaying = false;
  12740. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  12741. refToIsCasting?.set(false);
  12742. this.pause();
  12743. this.setIsPlaying(false);
  12744. // if (this.curIndex === this.curSource.index) {
  12745. // this.play
  12746. // this.seek(this.currentTime * 1000);
  12747. // this.setIsPlaying(true);
  12748. // } else {
  12749. // this.pauseVideo();
  12750. // this.setIsPlaying(false);
  12751. // }
  12752. }
  12753. public setIsPlaying(isPlayer: boolean) {
  12754. this.isPlaying = isPlayer;
  12755. // 发送播放状态变化事件给歌单详情页面
  12756. try {
  12757. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  12758. const currentFilePath = this.currentSong?.filePath || ''
  12759. const eventData: emitter.EventData = {
  12760. data: {
  12761. isPlaying: this.isPlaying,
  12762. curIndex: this.curIndex,
  12763. currentFilePath: currentFilePath
  12764. }
  12765. };
  12766. emitter.emit(eventPlaybackStatus, eventData)
  12767. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  12768. } catch (error) {
  12769. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  12770. }
  12771. }
  12772. private setPlaybackStateChangeListener(): void {
  12773. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  12774. this.castController?.on('endOfStream', this.reloadCasting);
  12775. this.castController?.on('playNext', this.playNextCallback);
  12776. this.castController?.on('playPrevious', this.playPreviousCallback);
  12777. }
  12778. private updateSessionPlayState(isPlay: boolean): void {
  12779. // if(!this.isBgPlayOpen)
  12780. // return
  12781. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  12782. this.setAVSessionPlayState({
  12783. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  12784. position: {
  12785. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  12786. updateTime: new Date().getTime()
  12787. }
  12788. });
  12789. }
  12790. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  12791. this.avSessionController.setAvSessionPlayState(playbackState)
  12792. }
  12793. private positionChange(position: number) {
  12794. this.currentTime2 = position / 1000;
  12795. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  12796. }
  12797. private playDurationChange(duration: number) {
  12798. this.duration = duration;
  12799. this.durationTime = Math.floor(this.duration / 1000);
  12800. this.durationStringTime = secondToTime((this.durationTime));
  12801. }
  12802. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  12803. const duration = playbackState?.extras?.duration;
  12804. if (typeof duration === 'number') {
  12805. this.playDurationChange(duration as number);
  12806. }
  12807. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  12808. this.positionChange(playbackState?.position?.elapsedTime);
  12809. }
  12810. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  12811. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  12812. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  12813. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  12814. this.isCastPlaying = false;
  12815. }
  12816. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  12817. this.isCastPlaying = true;
  12818. }
  12819. };
  12820. private reloadCasting = async () => {
  12821. let item = this.songList[this.curIndex];
  12822. let uri = fileUri.getUriFromPath(item.filePath);
  12823. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  12824. // description.startPosition = 0;
  12825. this.castItem = {
  12826. itemId: this.curIndex,
  12827. description: {
  12828. assetId: item.filePath,
  12829. title: item.name,
  12830. artist: '',
  12831. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  12832. // mediaUri: item.filePath,
  12833. fdSrc: {
  12834. fd: file.fd
  12835. },
  12836. // 该字段大写,音频'AUDIO',视频'VIDEO'
  12837. mediaType: 'VIDEO',
  12838. mediaSize: item.videoSize,
  12839. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  12840. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  12841. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  12842. duration: this.duration,
  12843. // albumCoverUri: 'https://www.example.jpeg',
  12844. // albumTitle: '《ExampleAlbum》',
  12845. appName: this.appName,
  12846. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  12847. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  12848. }
  12849. };
  12850. this.prepare();
  12851. this.isCastPlaying = true;
  12852. };
  12853. public playNextCallback = (): void => {
  12854. this.playNext().catch(() => {
  12855. Logger.error('heanup playNextCallback', `播放下一首失败`);
  12856. });
  12857. };
  12858. public playPreviousCallback = (): void => {
  12859. this.playPrevious().catch(() => {
  12860. Logger.error('heanup playNextCallback', `播放上一首失败`);
  12861. });
  12862. };
  12863. async prepare() {
  12864. await this.castController?.prepare(this.castItem);
  12865. await this.castController?.start(this.castItem);
  12866. }
  12867. public initQueueItem() {
  12868. let item = this.songList[this.curIndex];
  12869. let time = this.currentTime;
  12870. let uri = fileUri.getUriFromPath(item.filePath);
  12871. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  12872. this.castItem = {
  12873. itemId: this.curIndex,
  12874. description: {
  12875. assetId: item.filePath,
  12876. title: item.name,
  12877. artist: '',
  12878. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  12879. fdSrc: {
  12880. fd: file.fd
  12881. },
  12882. // 该字段大写,音频'AUDIO',视频'VIDEO'
  12883. mediaType: 'AUDIO',
  12884. mediaSize: item.videoSize,
  12885. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  12886. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  12887. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  12888. duration: this.duration,
  12889. // albumCoverUri: 'https://www.example.jpeg',
  12890. // albumTitle: '《ExampleAlbum》',
  12891. appName: this.appName,
  12892. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  12893. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  12894. }
  12895. };
  12896. }
  12897. async stopCast() {
  12898. try {
  12899. this.castController?.off('playbackStateChange');
  12900. this.castController?.off('endOfStream');
  12901. this.castController?.off('playNext');
  12902. this.castController?.off('playPrevious');
  12903. this.castController?.off('error');
  12904. } catch (error) {
  12905. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  12906. }
  12907. }
  12908. private sessionPlayCallback = (): void => {
  12909. this.playOrPause()
  12910. };
  12911. private sessionPauseCallback = (): void => {
  12912. this.pause()
  12913. };
  12914. private playOrPause() {
  12915. if (!this.debounce()) {
  12916. return;
  12917. }
  12918. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  12919. this.pause();
  12920. } else {
  12921. console.info('onecold startPlayOrResumePlay 11064')
  12922. this.startPlayOrResumePlay();
  12923. this.playChange()
  12924. }
  12925. }
  12926. private sessionPlayNextCallback = (): void => {
  12927. this.playNext().catch(() => {
  12928. Logger.error('heanup sessionPlayPreviousCallback', `播放下 一首失败`);
  12929. });
  12930. };
  12931. private sessionPlayPreviousCallback = (): void => {
  12932. this.playPrevious().catch(() => {
  12933. Logger.error('heanup sessionPlayPreviousCallback', `播放上一首失败`);
  12934. });
  12935. };
  12936. private sessionStopCallback = (): void => {
  12937. this.stop()
  12938. };
  12939. private sessionFastForwardCallback = (time?: number) => {
  12940. if (!time) {
  12941. return;
  12942. }
  12943. if (this.mIjkMediaPlayer != null) {
  12944. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12945. let seeTime = curPosition + time * 1000;
  12946. // 限制 seekValue 在合法范围内
  12947. if (seeTime < 0) {
  12948. seeTime = 0;
  12949. } else if (seeTime > this.duration) {
  12950. seeTime = this.duration;
  12951. }
  12952. Logger.info('onecold seeTime= ' + seeTime)
  12953. this.setSeekToActionProgress(seeTime)
  12954. this.seekTo(seeTime + "")
  12955. }
  12956. };
  12957. /**
  12958. * Gesture method onActionUpdate.
  12959. *
  12960. * @param event Gesture event.手势拖动设置快进和后退
  12961. */
  12962. private setSeekToActionProgress(position: number) {
  12963. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  12964. let duration = this.mIjkMediaPlayer.getDuration();
  12965. let pos = 0;
  12966. if (duration > 0) {
  12967. this.slideEnable = true;
  12968. let curPercent = position / duration;
  12969. pos = curPercent * 100;
  12970. if (pos > this.PROGRESS_MAX_VALUE) {
  12971. this.progressValue = this.PROGRESS_MAX_VALUE
  12972. } else {
  12973. this.progressValue = pos;
  12974. }
  12975. }
  12976. // LogUtils.getInstance()
  12977. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  12978. this.totalTime = this.stringForTime(duration);
  12979. if (position > duration) {
  12980. position = duration;
  12981. }
  12982. this.isCurrentTime = true;
  12983. this.currentTime = this.stringForTime(position);
  12984. this.isCurrentTime = false
  12985. }
  12986. private sessionRewindCallback = (time?: number) => {
  12987. if (!time) {
  12988. return;
  12989. }
  12990. if (this.mIjkMediaPlayer != null) {
  12991. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12992. let seeTime = curPosition - time * 1000;
  12993. // 限制 seekValue 在合法范围内
  12994. if (seeTime < 0) {
  12995. seeTime = 0;
  12996. } else if (seeTime > this.duration) {
  12997. seeTime = this.duration;
  12998. }
  12999. Logger.info('onecold seeTime= ' + seeTime)
  13000. this.setSeekToActionProgress(seeTime)
  13001. this.seekTo(seeTime + "")
  13002. }
  13003. };
  13004. private sessionSeekCallback = (seekTime: number) => {
  13005. if (this.mIjkMediaPlayer != null) {
  13006. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  13007. this.seekTo(seekTime + "")
  13008. }
  13009. };
  13010. private async getFileSize(filePath: string): Promise<number> {
  13011. try {
  13012. const stat = await fs.stat(filePath);
  13013. return stat.size;
  13014. } catch (err) {
  13015. console.error('Failed to get file size: ' + err.message);
  13016. return 0;
  13017. }
  13018. }
  13019. private pause() {
  13020. if (this.mIjkMediaPlayer.isPlaying()) {
  13021. this.savePlaybackPosition();
  13022. this.mIjkMediaPlayer.pause();
  13023. this.setProgress();
  13024. this.mDestroyPage = true;
  13025. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  13026. this.updateSessionPlayState(false)
  13027. this.playChange()
  13028. if (this.pipController) {
  13029. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  13030. PiPWindow.PiPControlStatus.PAUSE);
  13031. }
  13032. }
  13033. }
  13034. private stop() {
  13035. this.savePlaybackPosition();
  13036. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13037. this.mIjkMediaPlayer.stop();
  13038. this.mIjkMediaPlayer.release();
  13039. this.stopProgressTask();
  13040. this.updateSessionPlayState(false)
  13041. this.playChange()
  13042. this.watchStatus();
  13043. }
  13044. //保持记忆播放功能
  13045. private savePlaybackPosition() {
  13046. if (this.mIjkMediaPlayer != null) {
  13047. const position = this.mIjkMediaPlayer.getCurrentPosition();
  13048. // ToastUtil.showToast('保存记忆播放 = ' + position)
  13049. const duration = this.mIjkMediaPlayer.getDuration();
  13050. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  13051. // 如果播放位置接近视频末尾,则保存 position 为 0
  13052. const playbackPosition = (duration - position < threshold) ? 0 : position;
  13053. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  13054. }
  13055. }
  13056. //获取记忆播放功能
  13057. private restorePlaybackPosition() {
  13058. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  13059. // ToastUtil.showToast('position = ' + position)
  13060. if (this.mIjkMediaPlayer != null && position > 0) {
  13061. // ToastUtil.showToast('seekTo = ' + position)
  13062. this.seekTo(position + "");
  13063. }
  13064. }
  13065. private seekTo(value: string) {
  13066. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  13067. ToastUtil.showToast('wma格式不支持拖动快进。')
  13068. return
  13069. }
  13070. this.isSeekTo = true
  13071. this.mIjkMediaPlayer.seekTo(value);
  13072. console.info('onecold startPlayOrResumePlay 11227')
  13073. // this.startPlayOrResumePlay()
  13074. // 在这里恢复计时器状态
  13075. this.setProgress()
  13076. this.isSeekTo = false
  13077. }
  13078. // 添加到下一首播放
  13079. private addToNextPlay(song: VideoItem) {
  13080. if (!this.debounce()) {
  13081. return;
  13082. }
  13083. if (this.currentSong) {
  13084. if (this.currentSong === song) {
  13085. ToastUtil.showToast('当前已经在播放这首歌了!')
  13086. return
  13087. }
  13088. }
  13089. // 如果未开始播放或队列为空
  13090. if (this.curIndex === -1 || this.songList.length === 0) {
  13091. this.songList = [song];
  13092. this.curIndex = 0;
  13093. this.doPlay(song)
  13094. return;
  13095. }
  13096. // 插入到当前索引+1的位置
  13097. const insertPos = this.curIndex + 1;
  13098. this.songList.splice(insertPos, 0, song);
  13099. this.songList = [...this.songList]; // 触发状态更新
  13100. this.sonDataSource.pushArrayData(this.songList)
  13101. ToastUtil.showToast('已添加至下一首播放')
  13102. }
  13103. //后退10s,可再设置设置默认几秒
  13104. backForward() {
  13105. if(this.mIjkMediaPlayer){
  13106. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  13107. let value = pos - Number(this.fastForwardSeconds) * 1000;
  13108. this.seekTo(value+"");
  13109. }
  13110. }
  13111. //快进10s,可再设置设置默认几秒
  13112. fastForward() {
  13113. if(this.mIjkMediaPlayer){
  13114. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  13115. let value = pos + Number(this.fastForwardSeconds) * 1000;
  13116. this.seekTo(value+"");
  13117. }
  13118. }
  13119. //下一个
  13120. private async playNext() {
  13121. if (!this.debounce()) {
  13122. return;
  13123. }
  13124. if (this.playType == 3) { //3:随机播放
  13125. await this.randomPlay()
  13126. return;
  13127. }
  13128. if (ArrayUtil.isNotEmpty(this.songList)) {
  13129. if (this.curIndex == this.songList.length - 1) {
  13130. this.curIndex = 0;
  13131. } else {
  13132. this.curIndex++;
  13133. }
  13134. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13135. this.stop();
  13136. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  13137. this.currentSong = this.songList[this.curIndex];
  13138. Logger.info('heanup playNext', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  13139. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13140. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13141. context: this.context,
  13142. autoParseMusicName: this.autoParseMusicName
  13143. });
  13144. this.artist = this.songList[this.curIndex].artist
  13145. this.name = this.songList[this.curIndex].name
  13146. //this.cover = this.songList[this.curIndex].pixelMapPath
  13147. this.changeImageAnimation()
  13148. }
  13149. }
  13150. changeImageAnimation() {
  13151. if(this.openSkipSongAnimate){
  13152. // 第一步:淡出动画
  13153. this.getUIContext()?.animateTo({
  13154. duration: 500,
  13155. curve: Curve.EaseOut,
  13156. }, () => {
  13157. this.opacityValueImage = 0.1;
  13158. if(this.isCoverRectangle){
  13159. this.scaleValueImage = 0.88
  13160. }
  13161. });
  13162. // 第二步:切换图片后淡入
  13163. setTimeout(() => {
  13164. this.cover = this.songList[this.curIndex].pixelMapPath
  13165. this.getUIContext()?.animateTo({
  13166. duration: 500,
  13167. curve: Curve.EaseIn,
  13168. }, () => {
  13169. this.opacityValueImage = 1;
  13170. this.scaleValueImage = 1 // 图标恢复到原始大小
  13171. this.startPlayOrResumePlay()
  13172. });
  13173. }, 500);
  13174. }else{
  13175. this.cover = this.songList[this.curIndex].pixelMapPath
  13176. this.startPlayOrResumePlay()
  13177. }
  13178. }
  13179. // 存储已播放的歌曲索引
  13180. private playedIndices: Set<number> = new Set();
  13181. //随机播放
  13182. private async randomPlay() {
  13183. // if (!this.debounce()) {
  13184. // return;
  13185. // }
  13186. if (ArrayUtil.isNotEmpty(this.songList)) {
  13187. if (this.songList.length > 3) {
  13188. // 如果所有歌曲都播放过一次,清空已播放索引集合
  13189. if (this.playedIndices.size === this.songList.length) {
  13190. this.playedIndices.clear();
  13191. }
  13192. // 随机选择一个未播放的歌曲索引
  13193. let newIndex: number;
  13194. // 添加超时机制防止无限循环
  13195. let attempt = 0;
  13196. const maxAttempts = 100; // 根据需求调整
  13197. do {
  13198. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  13199. attempt++;
  13200. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  13201. if (attempt >= maxAttempts) {
  13202. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  13203. newIndex = Math.floor(Math.random() * this.songList.length);
  13204. }
  13205. this.curIndex = newIndex;
  13206. this.playedIndices.add(newIndex);
  13207. } else {
  13208. // 当歌曲数量小于或等于3时,直接播放下一首
  13209. if (this.curIndex == this.songList.length - 1) {
  13210. this.curIndex = 0;
  13211. } else {
  13212. this.curIndex++;
  13213. }
  13214. }
  13215. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13216. this.stop();
  13217. this.currentSong = this.songList[this.curIndex];
  13218. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13219. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13220. context: this.context,
  13221. autoParseMusicName: this.autoParseMusicName
  13222. });
  13223. this.name = this.songList[this.curIndex].name;
  13224. this.artist = this.songList[this.curIndex].artist
  13225. // this.cover = this.songList[this.curIndex].pixelMapPath
  13226. this.changeImageAnimation()
  13227. }
  13228. }
  13229. private async playIndex(index: number) {
  13230. if (!this.debounce()) {
  13231. return;
  13232. }
  13233. if (ArrayUtil.isNotEmpty(this.songList)) {
  13234. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13235. this.stop();
  13236. this.curIndex = index;
  13237. this.currentSong = this.songList[index];
  13238. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13239. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13240. context: this.context,
  13241. autoParseMusicName: this.autoParseMusicName
  13242. });
  13243. this.name = this.currentSong.name
  13244. this.artist = this.currentSong.artist
  13245. this.changeImageAnimation()
  13246. }
  13247. }
  13248. //上一个
  13249. private async playPrevious() {
  13250. if (!this.debounce()) {
  13251. return;
  13252. }
  13253. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  13254. this.randomModePlayFromHistory()
  13255. return;
  13256. }
  13257. if (this.curIndex == 0) {
  13258. this.curIndex = this.songList.length - 1;
  13259. } else {
  13260. this.curIndex--;
  13261. }
  13262. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13263. this.stop();
  13264. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  13265. this.currentSong = this.songList[this.curIndex];
  13266. Logger.info('heanup playPrevious', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  13267. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13268. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13269. context: this.context,
  13270. autoParseMusicName: this.autoParseMusicName
  13271. });
  13272. this.name = this.songList[this.curIndex].name
  13273. this.artist = this.songList[this.curIndex].artist
  13274. this.changeImageAnimation()
  13275. }
  13276. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  13277. private async randomModePlayFromHistory() {
  13278. if (this.historyList.length >= 2) {
  13279. // 播放历史记录的第二首
  13280. const prevSong = this.historyList[1];
  13281. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  13282. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13283. this.stop();
  13284. // 直接使用历史记录中的歌曲信息,历史记录中的数据应该是完整的
  13285. this.currentSong = prevSong;
  13286. Logger.info('heanup randomModePlayFromHistory', `直接使用历史歌曲信息: ${prevSong.name}, type: ${prevSong.type}`);
  13287. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13288. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13289. context: this.context,
  13290. autoParseMusicName: this.autoParseMusicName
  13291. });
  13292. this.cover = prevSong.pixelMapPath
  13293. this.artist = prevSong.artist
  13294. this.name = prevSong.name;
  13295. console.info('onecold startPlayOrResumePlay 11434')
  13296. this.startPlayOrResumePlay();
  13297. } else {
  13298. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  13299. if (this.curIndex === 0) {
  13300. this.curIndex = this.songList.length - 1;
  13301. } else {
  13302. this.curIndex--;
  13303. }
  13304. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13305. this.stop();
  13306. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  13307. this.currentSong = this.songList[this.curIndex];
  13308. Logger.info('heanup randomModePlayFromHistory', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  13309. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13310. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13311. context: this.context,
  13312. autoParseMusicName: this.autoParseMusicName
  13313. });
  13314. this.artist = this.songList[this.curIndex].artist
  13315. this.name = this.songList[this.curIndex].name;
  13316. this.changeImageAnimation()
  13317. }
  13318. }
  13319. debounce() {
  13320. const delay = 600;
  13321. let cur = new Date().getTime();
  13322. if (cur - this.last > delay) {
  13323. this.last = cur;
  13324. return true;
  13325. }
  13326. return false;
  13327. }
  13328. /**
  13329. * Sets whether the screen is a constant based on the playback status.
  13330. */
  13331. watchStatus() {
  13332. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  13333. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  13334. this.windowClass.setWindowKeepScreenOn(true);
  13335. } else {
  13336. this.windowClass.setWindowKeepScreenOn(false);
  13337. }
  13338. }
  13339. /**
  13340. * Volume gesture method onActionStart.
  13341. *
  13342. * @param event Gesture event.
  13343. */
  13344. private customDialogComponentIdMM: number = 0
  13345. @Builder
  13346. customDialogComponentMM() {
  13347. Column() {
  13348. Row() {
  13349. Blank()
  13350. Text('验证密码')
  13351. .fontSize(22)
  13352. .fontColor($r('app.color.pri_bg'))
  13353. .margin({ top: 18 })
  13354. Blank()
  13355. Image($r('app.media.close'))
  13356. .fillColor(Color.White)
  13357. .margin({ top: 18, right: 18 })
  13358. .width(20)
  13359. .onClick(() => {
  13360. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  13361. })
  13362. }
  13363. .width('100%') // 使Row占据整个宽度
  13364. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  13365. Verify({
  13366. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  13367. });
  13368. }.height('60%')
  13369. .backgroundColor($r('app.color.index_background'))
  13370. .justifyContent(FlexAlign.SpaceBetween)
  13371. }
  13372. private handleVerifyCompleted(isSuccess: boolean) {
  13373. if (isSuccess) {
  13374. console.log('验证成功');
  13375. // 在这里处理验证成功后的逻辑
  13376. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  13377. this.currentPath = this.lockPath
  13378. this.getSortedFiles(this.currentPath)
  13379. } else {
  13380. // console.log('验证失败');
  13381. ToastUtil.showToast('验证失败')
  13382. }
  13383. }
  13384. private showVerifyDialog() {
  13385. promptAction.openCustomDialog({
  13386. transition: TransitionEffect.asymmetric(
  13387. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  13388. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  13389. ,
  13390. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  13391. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  13392. ),
  13393. builder: () => {
  13394. this.customDialogComponentMM()
  13395. },
  13396. isModal: true,
  13397. autoCancel: true,
  13398. maskColor: Color.Transparent,
  13399. alignment: DialogAlignment.Bottom,
  13400. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  13401. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  13402. console.log("dialog onWillDismiss")
  13403. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  13404. dismissDialogAction.dismiss()
  13405. }
  13406. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  13407. dismissDialogAction.dismiss()
  13408. }
  13409. }
  13410. }).then((dialogId: number) => {
  13411. this.customDialogComponentIdMM = dialogId
  13412. })
  13413. }
  13414. //左滑操作 移动文件 重命名 删除等操作
  13415. @Builder
  13416. DeleteButton(item: VideoItem, index: number, filePath: string) {
  13417. Row() {
  13418. //加入收藏
  13419. Button() {
  13420. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  13421. .fillColor(Color.White)
  13422. .width(20)
  13423. }
  13424. .width(40)
  13425. .height(40)
  13426. .type(ButtonType.Circle)
  13427. .backgroundColor(this.themeColor)
  13428. .margin(5)
  13429. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13430. .onClick(() => {
  13431. if (item) {
  13432. this.doFav(item)
  13433. }
  13434. })
  13435. //加入下一首播放
  13436. Button() {
  13437. Image($r('app.media.next_to_play'))
  13438. .fillColor(Color.White)
  13439. .width(20)
  13440. }
  13441. .width(40)
  13442. .height(40)
  13443. .type(ButtonType.Circle)
  13444. .backgroundColor(this.themeColor)
  13445. .margin(5)
  13446. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13447. .onClick(() => {
  13448. this.addToNextPlay(item);
  13449. })
  13450. //复制文件
  13451. Button() {
  13452. Image($r('app.media.copy'))
  13453. .fillColor(Color.White)
  13454. .width(20)
  13455. }
  13456. .width(40)
  13457. .height(40)
  13458. .type(ButtonType.Circle)
  13459. .backgroundColor(this.themeColor)
  13460. .margin(5)
  13461. .id(filePath + 'copy')
  13462. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13463. .onClick(() => {
  13464. this.showCopyDialog(false, item, index, filePath + 'copy');
  13465. })
  13466. //移动文件
  13467. Button() {
  13468. Image($r('app.media.cut'))
  13469. .fillColor(Color.White)
  13470. .width(20)
  13471. }
  13472. .width(40)
  13473. .height(40)
  13474. .type(ButtonType.Circle)
  13475. .backgroundColor(this.themeColor)
  13476. .margin(5)
  13477. .id(filePath)
  13478. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13479. .onClick(() => {
  13480. this.showCutDialog(false, item, index, filePath);
  13481. })
  13482. Button() {
  13483. Image($r('app.media.cut_current'))
  13484. .fillColor(Color.White)
  13485. .width(20)
  13486. }
  13487. .width(40)
  13488. .height(40)
  13489. .type(ButtonType.Circle)
  13490. .backgroundColor(this.themeColor)
  13491. .margin(5)
  13492. .id(filePath + 'current')
  13493. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  13494. (this.isHasDir ? Visibility.Visible : Visibility.None))
  13495. .onClick(() => {
  13496. this.showCutDialog(true, item, index, filePath + 'current');
  13497. })
  13498. //重命名
  13499. Button() {
  13500. Image($r('app.media.rename2'))
  13501. .fillColor(Color.White)
  13502. .width(20)
  13503. }
  13504. .width(40)
  13505. .height(40)
  13506. .type(ButtonType.Circle)
  13507. .backgroundColor(this.themeColor)
  13508. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  13509. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  13510. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  13511. .margin(5)
  13512. .onClick(() => {
  13513. this.showReNameDialog(item, index + '', filePath)
  13514. })
  13515. Button() {
  13516. Image($r('app.media.delete2'))
  13517. .fillColor(Color.White)
  13518. .width(20)
  13519. }
  13520. .width(40)
  13521. .height(40)
  13522. .type(ButtonType.Circle)
  13523. .backgroundColor(this.themeColor)
  13524. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  13525. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  13526. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  13527. .margin(5)
  13528. .onClick(() => {
  13529. this.selectedFiles.push(item)
  13530. this.showWarnIsDelete()
  13531. // this.showWarnIsDeleteFile(item, index + '', filePath)
  13532. })
  13533. Button() {
  13534. Image($r('app.media.share2'))
  13535. .fillColor(Color.White)
  13536. .width(20)
  13537. }
  13538. .width(40)
  13539. .height(40)
  13540. .type(ButtonType.Circle)
  13541. .backgroundColor(this.themeColor)
  13542. .margin(5)
  13543. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13544. .onClick(() => {
  13545. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  13546. })
  13547. }
  13548. }
  13549. /**
  13550. * 穿山甲banner广告
  13551. */
  13552. // private declare bannerAd: CSJNativeExpressAd;
  13553. // @State private status: string = "未加载"
  13554. // @State private isShowAd: boolean = false
  13555. // private declare mAdSlot: AdSlot;
  13556. // private mBiddingAdm = '' //服务端bidding才需要设置
  13557. // private expressLoadAdListener: NativeExpressAdListener = {
  13558. // /**
  13559. // * 加载失败的回调
  13560. // *
  13561. // * @param code
  13562. // * @param message
  13563. // */
  13564. // onError: (code: number, message: string) => {
  13565. // console.error("加载广告失败,code=" + code + ",message=" + message);
  13566. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  13567. // },
  13568. //
  13569. // /**
  13570. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  13571. // *
  13572. // * @param ads 返回的广告列表
  13573. // */
  13574. //
  13575. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  13576. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  13577. // if (ads && ads.length > 0) {
  13578. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  13579. // ad.setExpressInteractionListener({
  13580. // /**
  13581. // *广告的点击回调
  13582. // * @param type 广告的交互类型
  13583. // */
  13584. // onAdClicked: (type: number) => {
  13585. // console.log("BannerExpressAdPage==onAdClicked......");
  13586. // },
  13587. //
  13588. // /**
  13589. // * 广告的展示回调 每个广告仅回调一次
  13590. // * @param type 广告的交互类型
  13591. // */
  13592. // onAdShow: (type: number) => {
  13593. // console.log("BannerExpressAdPage==onAdShow......");
  13594. // },
  13595. //
  13596. // /**
  13597. // * 模板渲染失败
  13598. // */
  13599. // onRenderFail: (code: number, msg: string) => {
  13600. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  13601. // },
  13602. //
  13603. // /**
  13604. // * 模板渲染成功
  13605. // * @param width 返回view的宽 单位 vp
  13606. // * @param height 返回view的高 单位 vp
  13607. // */
  13608. // onRenderSuccess: (width: number, height: number) => {
  13609. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  13610. // this.bannerAd = ad;
  13611. // this.status = "广告加载完成待展示";
  13612. //
  13613. // this.showBannerAd()
  13614. // }
  13615. // })
  13616. // //渲染广告
  13617. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  13618. // this.setDislikeCallback(ad); //设置dislike
  13619. // ad.render(this.getUIContext())
  13620. // this.status = "广告加载中...";
  13621. // });
  13622. // }
  13623. // }
  13624. // }
  13625. //
  13626. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  13627. // ad.setDislikeCallback({
  13628. // /**
  13629. // * dislike show
  13630. // */
  13631. // onShow: () => {
  13632. // console.log("BannerExpressAdPage==dislike......show");
  13633. // },
  13634. //
  13635. // /**
  13636. // * @param position 选择的位置
  13637. // * @param value 选择的内容
  13638. // * @param enforceRemove 是否强制关闭广告
  13639. // */
  13640. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  13641. // this.isShowAd = false;
  13642. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  13643. // ",enforce=" + enforceRemove);
  13644. // },
  13645. //
  13646. // /**
  13647. // * 点击取消
  13648. // */
  13649. // onCancel: () => {
  13650. // console.log("BannerExpressAdPage==dislike......onCancel");
  13651. // }
  13652. //
  13653. // })
  13654. // }
  13655. /**
  13656. * 加载Banner广告
  13657. */
  13658. loadBannerAd(rit: string) {
  13659. // if (Utility.isNoble()) {
  13660. // return
  13661. // }
  13662. // if (!Utility.isPassInstallTime(2)) {
  13663. // return
  13664. // }
  13665. // this.isShowAd = false;
  13666. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  13667. // this.mAdSlot = new AdSlotBuilder()
  13668. // .setCodeId(rit)
  13669. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  13670. // .setAdCount(1)
  13671. // .setBidAdm(this.mBiddingAdm)
  13672. // .build()
  13673. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  13674. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  13675. // this.status = "广告加载中..."
  13676. }
  13677. /**
  13678. * 展示Banner广告
  13679. */
  13680. // showBannerAd() {
  13681. // if (!this.bannerAd) {
  13682. // return
  13683. // }
  13684. // this.isShowAd = true
  13685. // this.status = "已展示"
  13686. // }
  13687. /**
  13688. * 穿山甲广告代码结束
  13689. */
  13690. /**
  13691. * 处理歌单播放请求
  13692. */
  13693. private async handlePlaylistPlayRequest(playlistId: string, playlistName:
  13694. string, songFilePaths: string[], startIndex: number,isJump: boolean) {
  13695. try {
  13696. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 歌曲数量: ${songFilePaths.length}, 开始索引: ${startIndex}`)
  13697. // 检查是否为WebDAV播放请求
  13698. if (playlistId === 'webdav-playlist') {
  13699. Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
  13700. // 从全局内存读取videoItems数据
  13701. const videoItems = getWebdavVideoItems();
  13702. const currentPlayIndex = getWebdavCurrentPlayIndex();
  13703. Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
  13704. if (videoItems && videoItems.length > 0) {
  13705. // 验证webdav_account_id设置情况
  13706. const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
  13707. Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
  13708. if(isJump){
  13709. this.setShowPlayTrue()//显示播放页
  13710. }
  13711. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName)
  13712. return
  13713. } else {
  13714. return
  13715. }
  13716. }
  13717. if (playlistId === 'navidrome-playlist') {
  13718. Logger.info(`heanup 检测到Navidrome播放请求,从内存读取videoItems`);
  13719. const videoItems = getNavidromeVideoItems();
  13720. const currentPlayIndex = getNavidromeCurrentPlayIndex();
  13721. Logger.info(`heanup Navidrome歌曲列表长度: ${videoItems.length}`);
  13722. if (videoItems && videoItems.length > 0) {
  13723. if(isJump){
  13724. this.setShowPlayTrue()//显示播放页
  13725. }
  13726. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName);
  13727. return;
  13728. } else {
  13729. Logger.warn('heanup Navidrome播放请求缺少歌曲数据');
  13730. return;
  13731. }
  13732. }
  13733. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  13734. const songMap: Map<number, VideoItem> = new Map()
  13735. let completedQueries = 0
  13736. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  13737. // 遍历所有文件路径,使用索引记录位置
  13738. for (let i = 0; i < songFilePaths.length; i++) {
  13739. const filePath = songFilePaths[i]
  13740. const index = i
  13741. // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  13742. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  13743. const queryPromise = this.table.queryVideoByFilePath(filePath)
  13744. // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  13745. queryPromise.then((videoItem) => {
  13746. completedQueries++
  13747. // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  13748. if (videoItem) {
  13749. // 使用索引作为key保存到Map中,保持原始顺序
  13750. songMap.set(index, videoItem)
  13751. // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  13752. } else {
  13753. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  13754. }
  13755. // 检查是否所有歌曲都已加载完成
  13756. if (completedQueries === songFilePaths.length) {
  13757. // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  13758. // 按照索引顺序重建歌曲数组
  13759. const songs: VideoItem[] = []
  13760. for (let j = 0; j < songFilePaths.length; j++) {
  13761. const song = songMap.get(j)
  13762. if (song) {
  13763. songs.push(song)
  13764. // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  13765. }
  13766. }
  13767. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  13768. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  13769. }
  13770. }).catch((error: Error) => {
  13771. completedQueries++
  13772. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  13773. // 即使出错也要检查是否完成所有查询
  13774. if (completedQueries === songFilePaths.length) {
  13775. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  13776. // 按照索引顺序重建歌曲数组
  13777. const songs: VideoItem[] = []
  13778. for (let j = 0; j < songFilePaths.length; j++) {
  13779. const song = songMap.get(j)
  13780. if (song) {
  13781. songs.push(song)
  13782. }
  13783. }
  13784. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  13785. }
  13786. })
  13787. }
  13788. } catch (error) {
  13789. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  13790. ToastUtil.showToast('播放失败')
  13791. }
  13792. }
  13793. /**
  13794. * 完成歌单加载并开始播放
  13795. */
  13796. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string) {
  13797. if (songs.length === 0) {
  13798. Logger.error('heanup 没有找到任何可播放的歌曲')
  13799. ToastUtil.showToast('没有找到可播放的歌曲')
  13800. return
  13801. }
  13802. this.songList = songs
  13803. this.sonDataSource.pushArrayData(songs)
  13804. this.sonDataSource.notifyDataReload()
  13805. this.curIndex = startIndex
  13806. if (songs[startIndex]) {
  13807. // 确保当前播放的歌曲也更新到存储
  13808. AppStorage.setOrCreate('currentSong', songs[startIndex])
  13809. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  13810. this.doPlay(songs[startIndex], startIndex, true)
  13811. }
  13812. PreferencesUtil.putSync('LastMusicList', this.songList)
  13813. // ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  13814. }
  13815. }
  13816. //视频气泡窗口的布局
  13817. @Builder
  13818. function customPopupBuilder(dataBu: BubbleBean) {
  13819. List() {
  13820. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  13821. ListItem() {
  13822. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13823. Row() {
  13824. Column() {
  13825. Image(dataBu.imageRes[index])
  13826. .height(28)
  13827. .fillColor(dataBu.color)
  13828. .alignSelf(ItemAlign.Center)
  13829. }
  13830. .width(32)
  13831. Text(item)
  13832. .padding({
  13833. top: 10,
  13834. bottom: 10,
  13835. right: 10,
  13836. left: 10
  13837. })
  13838. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  13839. .textAlign(TextAlign.Start)
  13840. .width("100%")
  13841. }
  13842. }
  13843. .backgroundColor($r('app.color.settings_background_main'))
  13844. .margin({ top: 6, bottom: 6 })
  13845. }
  13846. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  13847. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  13848. TransitionEffect.scale({ x: 0, y: 0 })))
  13849. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  13850. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  13851. .onClick(() => {
  13852. dataBu.onItemClick?.(index)
  13853. })
  13854. })
  13855. }
  13856. .scrollBar(BarState.Off)
  13857. .width(120)
  13858. .divider({
  13859. strokeWidth: 1,
  13860. color: "#22FFFFFF"
  13861. })
  13862. }
  13863. // Function to calculate a hash for the file list
  13864. function simpleHash(fileList: string[]): string {
  13865. let hash = 0;
  13866. const str = fileList.join(',');
  13867. for (let i = 0; i < str.length; i++) {
  13868. const char = str.charCodeAt(i);
  13869. hash = (hash << 5) - hash + char;
  13870. hash |= 0; // Convert to 32bit integer
  13871. }
  13872. return hash.toString();
  13873. }
  13874. interface MoreItem {
  13875. id: number;
  13876. image: Resource;
  13877. title: string;
  13878. }
  13879. //视频气泡窗口的布局
  13880. @Builder
  13881. function cutPopupBuilder(dataBu: BubbleBean) {
  13882. Column() {
  13883. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  13884. .padding({
  13885. top: 10,
  13886. bottom: 10,
  13887. right: 10,
  13888. left: 10
  13889. })
  13890. .textAlign(TextAlign.Start)
  13891. .width(160)
  13892. .fontWeight(666)
  13893. .fontSize(16)
  13894. List() {
  13895. ForEach(dataBu.data, (item: string, index: number) => {
  13896. ListItem() {
  13897. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13898. Row() {
  13899. Column() {
  13900. Image($r('app.media.music_group'))
  13901. .height(28)
  13902. .fillColor(dataBu.color)
  13903. .alignSelf(ItemAlign.Center)
  13904. }
  13905. .width(32)
  13906. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  13907. .padding({
  13908. top: 10,
  13909. bottom: 10,
  13910. right: 10,
  13911. left: 10
  13912. })
  13913. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  13914. .fontSize(15)
  13915. }
  13916. }
  13917. .backgroundColor(Color.Transparent)
  13918. .margin({ top: 7, bottom: 7 })
  13919. }
  13920. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  13921. .animation({ duration: 500 }),
  13922. TransitionEffect.scale({ x: 0, y: 0 })))
  13923. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  13924. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  13925. .onClick(() => {
  13926. dataBu.onItemClick?.(index)
  13927. })
  13928. })
  13929. }
  13930. .scrollBar(BarState.Off)
  13931. .width(150)
  13932. .divider({
  13933. strokeWidth: 1,
  13934. color: "#22FFFFFF"
  13935. })
  13936. }
  13937. .height(300)
  13938. .padding({
  13939. bottom: 30
  13940. })
  13941. }
  13942. function getFileDirName(filePath: string,rootPath:string): string{
  13943. if(filePath===rootPath){
  13944. return '首页'
  13945. }
  13946. let result = FileUtil.getFileName(filePath)
  13947. if(StrUtil.isEmpty(result))
  13948. return ''
  13949. if(result.startsWith('.'))
  13950. result = result.replace(/\./g, '')
  13951. return result
  13952. }
  13953. //只扫描当前目录下文件(不扫描子文件夹)的方法
  13954. @Concurrent
  13955. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  13956. const table: MediaTable = new MediaTable(context);
  13957. try {
  13958. // 直接获取当前目录下的文件列表
  13959. const files = FileUtil.listFileSync(dirPath);
  13960. await Promise.all(files.map(async (file) => {
  13961. const fPath = `${dirPath}/${file}`;
  13962. // 跳过目录,只处理文件
  13963. if (FileUtil.isDirectory(fPath)) {
  13964. return;
  13965. }
  13966. // 跳过特定格式文件
  13967. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  13968. return;
  13969. }
  13970. // 检查是否为媒体文件
  13971. if (Utility.isMeidaByExtension(fPath)) {
  13972. let mType = CommonConstants.TYPE_LOCAL;
  13973. if (fPath.includes(lockPath)) {
  13974. mType = CommonConstants.TYPE_LOCK;
  13975. }
  13976. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  13977. context, fPath, mType, true
  13978. );
  13979. table.insert(mediaItem, (id: number) => {
  13980. // 插入回调函数
  13981. }, cover_api);
  13982. }
  13983. }));
  13984. } catch (error) {
  13985. console.error(' 扫描当前目录失败:', error);
  13986. }
  13987. }
  13988. //内嵌标签后更新库
  13989. @Concurrent
  13990. async function updateInfoDb(
  13991. context: Context,
  13992. filePath: string,
  13993. titleStr: string,
  13994. artistStr: string,
  13995. albumStr: string,
  13996. lyricConStr: string,
  13997. yearStr: string,
  13998. genreStr: string,
  13999. trackStr: string,
  14000. albumArtistStr: string,
  14001. composerStr: string,
  14002. lyricistStr: string,
  14003. commentStr: string,
  14004. discStr: string,
  14005. ): Promise<boolean> {
  14006. const table: MediaTable = new MediaTable(context);
  14007. await new Promise<void>((resolve, reject) => {
  14008. table.getRdbStore(context, (err:Error) => {
  14009. err ? reject(err) : resolve();
  14010. });
  14011. });
  14012. return await new Promise<boolean>((resolve) => {
  14013. table.updateMediaInfo(filePath, titleStr, artistStr, albumStr, lyricConStr,
  14014. yearStr, genreStr, trackStr, albumArtistStr, composerStr, lyricistStr, commentStr, discStr,
  14015. (success: boolean, error?: string) => {
  14016. if (success) {
  14017. console.log("onecold 编辑信息成功,数据库已同步");
  14018. } else {
  14019. console.error("onecold 编辑信息数据库失败原因: " + error);
  14020. }
  14021. resolve(success);
  14022. });
  14023. });
  14024. }