LocalMusic.ets 534 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417
  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 { EventConstants } from '../common/constants/EventConstants';
  31. import Logger from '../common/util/Logger';
  32. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  33. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  34. import { BubbleBean } from '../viewmodel/BubbleBean';
  35. import { PopupPosition, XPopup } from '@chinalike/popup';
  36. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  37. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  38. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  39. import { MessageEvents, util, worker, ErrorEvent, JSON } from '@kit.ArkTS';
  40. import { Verify } from './Verify';
  41. import { taskpool } from '@kit.ArkTS';
  42. import { RotatingCover } from './RotatingCover';
  43. import { PlayConstants } from '../common/constants/PlayConstants';
  44. import { effectKit } from '@kit.ArkGraphics2D';
  45. import { ColorConversion } from '../common/util/ColorConversion';
  46. import { LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  47. import { AvSessionController } from '../controller/AvSessionController';
  48. import { repairAudioMetadata, convertDsfToWav, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  49. import { extractHwMediaMetadata, FFMpegTags,Utility } from '../common/util/Utility';
  50. import { TagsContentCover } from '../view/TagsContentCover';
  51. import {
  52. DeviceChangeReason,
  53. IjkMediaPlayer,
  54. InterruptEvent,
  55. InterruptHintType,
  56. LogUtils,
  57. OnBufferingUpdateListener,
  58. OnCompletionListener,
  59. OnErrorListener,
  60. OnInfoListener,
  61. OnPreparedListener,
  62. OnSeekCompleteListener,
  63. OnTimedTextListener,
  64. OnVideoSizeChangedListener
  65. } from '@ohos/ijkplayer';
  66. import { PlayStatus } from '../common/PlayStatus';
  67. import fs from '@ohos.file.fs';
  68. import { image } from '@kit.ImageKit';
  69. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  70. import { UniversalDetector } from '@ohos/juniversalchardet';
  71. import { SettingPage } from '../pages/SettingPage';
  72. import { secondToTime,getTransverterText } from '../common/util/CommUtils';
  73. import { CommonConstants2 } from '../common/util/CommonConstants2';
  74. import { hilog } from '@kit.PerformanceAnalysisKit';
  75. import { LazyDataSource } from '../common/util/LazyDataSource';
  76. import MediaTable from '../common/util/MediaTable';
  77. import FileDeletionWatcher from '../common/util/FileDeletionWatcher';
  78. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  79. import ImageUtils from '../common/util/ImageUtils';
  80. import { ringtone } from '@kit.RingtoneKit';
  81. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  82. import { resourceManager } from '@kit.LocalizationKit';
  83. import { deviceInfo } from '@kit.BasicServicesKit';
  84. import { RemoteCacheManager } from '../common/network/RemoteCacheManager';
  85. import '../common/network/RemoteCacheRegistry';
  86. import { RemoteCacheType, resolveCacheFilePath } from '../common/network/RemoteSongCache';
  87. import { findWebDavCacheIfExists, triggerWebDavCacheDownload } from '../common/network/WebDavFileCache';
  88. import { navidromeApi } from '../common/network/NavidromeApi';
  89. import { ServerLogUtil } from '../common/util/ServerLogUtil';
  90. import { ensureSmbFileStreaming, SmbStreamingMeta } from '../common/network/SmbFileCache';
  91. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  92. import app from '@system.app';
  93. import { TextNodeController } from './PipLyricTextBuilder';
  94. import { IndexerView } from './IndexerView';
  95. import { KeyCode } from '@kit.InputKit';
  96. import { KnockController } from '../controller/KnockController';
  97. import { DeleteComptent } from '../view/DeleteComptent';
  98. import { ABLoopComptent } from '../view/ABLoopComptent';
  99. import { FixMessyView } from '../view/FixMessyView';
  100. import { parseCueFile,CueTrack,CueInfo } from '../common/util/CueUtils';
  101. import { CueComptent } from '../view/CueComptent';
  102. import PlaylistTable from '../common/util/PlaylistTable';
  103. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  104. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  105. import { convertPlaylistSongsToVideoItems, emptyView,updateAllSongsSortOrder } from '../pages/PlaylistDetailPage';
  106. import { Playlist, PlaylistSong } from '../viewmodel/Playlist';
  107. import { Song } from '../viewmodel/Song';
  108. import { SongType } from '../common/enums/SongType';
  109. import { RemoteDriveManager, WebDavAuthInfo as WebDavManagerAuthInfo,
  110. buildHttpHeadersWithWebDav,
  111. WebDavAuthItem} from '../common/util/RemoteDriveManager';
  112. import PermissionUtil from '../common/util/PermissionUtil'
  113. import { EditAudio, setRingTone } from './EditAudio';
  114. import { ExtractAccompaniment } from './ExtractAccompaniment';
  115. import { ExtractAudioFromVideo } from './ExtractAudioFromVideo';
  116. import { AudioFormatConverter } from './AudioFormatConverter';
  117. import { MergeAudio } from './MergeAudio';
  118. import { AIVoiceSeparation } from './AIVoiceSeparation';
  119. import { WebDavUrlUtil } from '../common/util/WebDavUrlUtil';
  120. import { ChangeTone } from './ChangeTone';
  121. import {
  122. hdsEffect,
  123. HdsVisualComponent,
  124. HdsSceneController,
  125. HdsSceneType,
  126. HdsVisualComponentAttribute,
  127. } from '@kit.UIDesignKit';
  128. import { GlobalAlphabetIndexerModifier } from '../Styels/GlobalStyles'
  129. import { getFirstLetter } from '../Constants';
  130. import { audio } from '@kit.AudioKit';
  131. const TAG = 'LocalMusic';
  132. const HICAR_LOG_TAG = 'HiCarWindow';
  133. function logHiCarWindow(message: string): void {
  134. void ServerLogUtil.info(HICAR_LOG_TAG, message);
  135. }
  136. /**
  137. * 歌单播放事件数据
  138. */
  139. interface PlaylistEventData {
  140. playlistId: string;
  141. playlistName: string;
  142. songCount: number;
  143. startIndex: number;
  144. songFilePaths: string[];
  145. isJump: boolean;
  146. webDavAuthInfo?: WebDavAuthItem; // 新增WebDAV认证信息
  147. }
  148. const DEFAULT_INDEX =
  149. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  150. 'X', 'Y', 'Z']
  151. //排序类型
  152. function getTypeOrder(type: number) {
  153. switch (type) {
  154. case CommonConstants.TYPE_IS_DIR:
  155. return 1; // First
  156. case CommonConstants.TYPE_IS_CSJAD:
  157. return 2; // Middle
  158. case CommonConstants.TYPE_LOCAL:
  159. return 3; // Last
  160. case CommonConstants.TYPE_WEBDAV:
  161. case CommonConstants.TYPE_SMB:
  162. case CommonConstants.TYPE_NAVIDROME:
  163. return 3;
  164. default:
  165. return 4; // Unknown types, if any, go last
  166. }
  167. }
  168. function isWebDavType(type: number): boolean {
  169. return type === CommonConstants.TYPE_WEBDAV;
  170. }
  171. function isSmbType(type: number): boolean {
  172. return type === CommonConstants.TYPE_SMB;
  173. }
  174. function isNavidromeType(type: number): boolean {
  175. return type === CommonConstants.TYPE_NAVIDROME;
  176. }
  177. function isFtpType(type: number): boolean {
  178. return type === CommonConstants.TYPE_FTP;
  179. }
  180. function isRemoteCloudType(type: number): boolean {
  181. return isWebDavType(type) || isSmbType(type) || isNavidromeType(type) || isFtpType(type);
  182. }
  183. function getShareNameFromFilePath(filePath?: string): string | undefined {
  184. if (!filePath) {
  185. return undefined;
  186. }
  187. const match = filePath.match(/^smb:\/\/[^/]+\/([^/]+)/i);
  188. return match && match[1] ? match[1] : undefined;
  189. }
  190. function removeSharePrefixFromPath(path: string, primaryShare?: string, secondaryShare?: string): string {
  191. const uniqueShares: string[] = [];
  192. [primaryShare, secondaryShare].forEach((name?: string) => {
  193. const cleaned = name ? name.replace(/^\/+|\/+$/g, '') : '';
  194. if (cleaned.length > 0 && !uniqueShares.some(item => item.toLowerCase() === cleaned.toLowerCase())) {
  195. uniqueShares.push(cleaned);
  196. }
  197. });
  198. if (uniqueShares.length === 0) {
  199. return path;
  200. }
  201. let result = path;
  202. for (let i = 0; i < uniqueShares.length; i++) {
  203. const share = uniqueShares[i];
  204. const lowerPath = result.toLowerCase();
  205. const lowerShare = share.toLowerCase();
  206. if (lowerPath === lowerShare) {
  207. result = '';
  208. break;
  209. }
  210. const prefix = `${lowerShare}/`;
  211. if (lowerPath.startsWith(prefix)) {
  212. result = result.substring(share.length + 1);
  213. break;
  214. }
  215. }
  216. return result;
  217. }
  218. function extractSmbRelativePath(song: VideoItem, shareNameOverride?: string): string {
  219. const shareFromFilePath = getShareNameFromFilePath(song.filePath);
  220. const shareName = shareNameOverride ?? shareFromFilePath;
  221. if (song.remote_rel_path && song.remote_rel_path.length > 0) {
  222. const cleaned = song.remote_rel_path.replace(/^\/+/, '');
  223. return removeSharePrefixFromPath(cleaned, shareName, shareFromFilePath);
  224. }
  225. if (!song.filePath) {
  226. return '';
  227. }
  228. const match = song.filePath.match(/^smb:\/\/[^/]+\/([^/]+)(\/.*)?$/i);
  229. if (!match) {
  230. return song.filePath.replace(/^\/+/, '');
  231. }
  232. const remainder = match[2] ? match[2].replace(/^\/+/, '') : '';
  233. if (remainder.length === 0) {
  234. return '';
  235. }
  236. return remainder;
  237. }
  238. function extractFtpRelativePath(song: VideoItem): string {
  239. if (song.remote_rel_path && song.remote_rel_path.length > 0) {
  240. return song.remote_rel_path.replace(/^\/+/, '');
  241. }
  242. if (!song.filePath) {
  243. return '';
  244. }
  245. const match = song.filePath.match(/^ftp:\/\/[^/]+(?::\d+)?(\/.*)$/i);
  246. if (match && match[1]) {
  247. return match[1].replace(/^\/+/, '');
  248. }
  249. return song.filePath.replace(/^\/+/, '');
  250. }
  251. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  252. interface MetadataExtractionOptions {
  253. context?: common.Context;
  254. autoParseMusicName?: boolean;
  255. }
  256. interface WorkerEditMusicResult {
  257. success: boolean;
  258. error?: string;
  259. coverResult?: boolean;
  260. needRefreshList?: boolean;
  261. metadataResult?: boolean;
  262. }
  263. interface LocalEditMusicPayload {
  264. context: Context;
  265. item: VideoItem;
  266. titleStr: string;
  267. artistStr: string;
  268. ablumStr: string;
  269. yearStr: string;
  270. genreStr: string;
  271. trackStr: string;
  272. albumArtistStr: string;
  273. composerStr: string;
  274. lyricistStr: string;
  275. commentStr: string;
  276. discStr: string;
  277. lyricConStr: string;
  278. imagePathStr: string;
  279. currentPath: string;
  280. packName: string;
  281. modeType: number;
  282. autoParseMusicName: boolean;
  283. }
  284. interface WorkerMetadataPayload {
  285. originFilePath: string;
  286. originId?: string;
  287. bit_rate?: string;
  288. duration?: string;
  289. sampleRate?: string;
  290. mimeType?: string;
  291. md5Str?: string;
  292. videoSize?: number;
  293. size?: string;
  294. pixelMapPath?: string;
  295. artist?: string;
  296. album?: string;
  297. name?: string;
  298. lyricContent?: string;
  299. bits_per_raw_sample?: string;
  300. channels?: string;
  301. channel_layout?: string;
  302. start_time?: string;
  303. genre?: string;
  304. year?: string;
  305. probe_score?: number;
  306. track?: string;
  307. disc?: string;
  308. ALBUMARTIST?: string;
  309. COMPOSER?: string;
  310. COMMENT?: string;
  311. LYRICIST?: string;
  312. nb_streams?: number;
  313. nb_programs?: number;
  314. error?: string;
  315. }
  316. interface WebDavMetadataUpdatePayload {
  317. filePath: string;
  318. pixelMapPath?: string;
  319. name?: string;
  320. artist?: string;
  321. }
  322. const metadataExtractionInFlight: Set<string> = new Set();
  323. const METADATA_RETRY_DELAY_MS = 1500;
  324. const METADATA_MAX_RETRY = 120;
  325. async function scheduleMetadataExtractionFromCache(
  326. song: VideoItem,
  327. cachePath: string,
  328. options?: MetadataExtractionOptions,
  329. expectedSize?: number,
  330. retryCount: number = 0
  331. ): Promise<void> {
  332. if (!song || !cachePath || !song.filePath || !options || !options.context) {
  333. return;
  334. }
  335. if (!isRemoteCloudType(song.type ?? -1)) {
  336. return;
  337. }
  338. if (metadataExtractionInFlight.has(song.filePath)) {
  339. return;
  340. }
  341. if (song.bit_rate && song.sampleRate && song.duration) {
  342. return;
  343. }
  344. const requiredSize = expectedSize && expectedSize > 0 ? expectedSize : undefined;
  345. try {
  346. const stat = await fileIo.stat(cachePath);
  347. const ready = requiredSize !== undefined ? stat.size >= requiredSize : stat.size > 0;
  348. if (!ready) {
  349. if (retryCount >= METADATA_MAX_RETRY) {
  350. Logger.warn(TAG, `缓存尚未完成,放弃解析: ${cachePath}`);
  351. return;
  352. }
  353. setTimeout(() => {
  354. void scheduleMetadataExtractionFromCache(song, cachePath, options, expectedSize, retryCount + 1);
  355. }, METADATA_RETRY_DELAY_MS);
  356. return;
  357. }
  358. } catch (error) {
  359. if (retryCount >= METADATA_MAX_RETRY) {
  360. Logger.warn(TAG, `无法读取缓存文件,放弃解析: ${(error as Error).message}`);
  361. return;
  362. }
  363. setTimeout(() => {
  364. void scheduleMetadataExtractionFromCache(song, cachePath, options, expectedSize, retryCount + 1);
  365. }, METADATA_RETRY_DELAY_MS);
  366. return;
  367. }
  368. metadataExtractionInFlight.add(song.filePath);
  369. workerInstance.postMessage({
  370. code: 5,
  371. data: options.context,
  372. data2: cachePath,
  373. data3: song.type,
  374. data4: {
  375. name: song.name,
  376. originFilePath: song.filePath,
  377. originId: song.id,
  378. autoParseMusicName: options.autoParseMusicName ?? false
  379. }
  380. });
  381. }
  382. function sanitizePlaybackUrl(rawUrl: string | null | undefined): string {
  383. if (!rawUrl) {
  384. return '';
  385. }
  386. try {
  387. const decoded = decodeURI(rawUrl);
  388. const encoded = encodeURI(decoded);
  389. // encodeURI 不会处理 #,手动转义避免播放器把剩余内容当作片段
  390. return encoded.replace(/#/g, '%23');
  391. } catch (error) {
  392. const err = error as Error;
  393. Logger.warn(TAG, `URL 编码失败,使用降级方案: ${err?.message}`);
  394. return rawUrl.replace(/ /g, '%20').replace(/#/g, '%23');
  395. }
  396. }
  397. function cloneVideoItem(item: VideoItem): VideoItem {
  398. const copy = new VideoItem(
  399. item.name,
  400. item.id,
  401. item.filePath,
  402. item.type,
  403. item.videoSize,
  404. item.cTime,
  405. item.size,
  406. item.pixelMapPath,
  407. item.artist,
  408. item.album,
  409. item.fileName,
  410. item.lastPlayed
  411. );
  412. copy.parentPath = item.parentPath;
  413. copy.isFav = item.isFav;
  414. copy.size = item.size;
  415. copy.pixelMapPath = item.pixelMapPath;
  416. copy.artist = item.artist;
  417. copy.album = item.album;
  418. copy.duration = item.duration;
  419. copy.mimeType = item.mimeType;
  420. copy.sampleRate = item.sampleRate;
  421. copy.trackCount = item.trackCount;
  422. copy.lastPlayedStr = item.lastPlayedStr;
  423. copy.playCount = item.playCount;
  424. copy.lyricContent = item.lyricContent;
  425. copy.md5Str = item.md5Str;
  426. copy.extra_json = item.extra_json;
  427. copy.pyStr = item.pyStr;
  428. copy.bit_rate = item.bit_rate;
  429. copy.probe_score = item.probe_score;
  430. copy.year = item.year;
  431. copy.nb_streams = item.nb_streams;
  432. copy.nb_programs = item.nb_programs;
  433. copy.genre = item.genre;
  434. copy.track = item.track;
  435. copy.bits_per_raw_sample = item.bits_per_raw_sample;
  436. copy.channels = item.channels;
  437. copy.channel_layout = item.channel_layout;
  438. copy.start_time = item.start_time;
  439. copy.ALBUMARTIST = item.ALBUMARTIST;
  440. copy.COMPOSER = item.COMPOSER;
  441. copy.LYRICIST = item.LYRICIST;
  442. copy.COMMENT = item.COMMENT;
  443. copy.disc = item.disc;
  444. copy.webdav_account_id = item.webdav_account_id;
  445. copy.remote_rel_path = item.remote_rel_path;
  446. return copy;
  447. }
  448. /**
  449. * 异步设置videoUrl的辅助方法,处理WebDAV URL的构建
  450. * @param song 歌曲对象
  451. * @returns Promise<string> 完整的URL
  452. */
  453. /**
  454. * 设置videoUrl,通过webdav_account_id设置完整的 URL
  455. * @param song 歌曲对象
  456. * @returns Promise<string> 完整的URL
  457. */
  458. async function setVideoUrlForSong(song: VideoItem, options?: MetadataExtractionOptions): Promise<string> {
  459. const metadataOptions = options ?? {};
  460. if (isWebDavType(song.type) && song.webdav_account_id) {
  461. try {
  462. Logger.info(TAG, `WebDAV 路径信息 remote_rel_path: ${song.remote_rel_path}`);
  463. Logger.info(TAG, `WebDAV 路径信息 filePath: ${song.filePath}`);
  464. const relativePath = song.remote_rel_path || song.filePath;
  465. const manager = RemoteDriveManager.getInstance();
  466. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  467. if (account) {
  468. const cachePath = await findWebDavCacheIfExists(account, relativePath);
  469. if (cachePath) {
  470. Logger.info(TAG, `WebDAV 缓存命中,直接播放: ${cachePath}`);
  471. void scheduleMetadataExtractionFromCache(song, cachePath, metadataOptions, song.videoSize);
  472. return cachePath;
  473. }
  474. const fullUrlFromAccount = WebDavUrlUtil.buildFullUrl(account, relativePath);
  475. if (fullUrlFromAccount) {
  476. const sanitizedUrl = sanitizePlaybackUrl(fullUrlFromAccount);
  477. const downloadPromise = triggerWebDavCacheDownload(account, relativePath, sanitizedUrl);
  478. if (downloadPromise) {
  479. downloadPromise.then((completedPath?: string | null) => {
  480. if (completedPath) {
  481. void scheduleMetadataExtractionFromCache(song, completedPath, metadataOptions, song.videoSize);
  482. }
  483. }).catch((error: Error) => {
  484. Logger.error(TAG, `WebDAV 缓存后台下载失败: ${error.message}`);
  485. });
  486. }
  487. Logger.info(TAG, `WebDAV 启动异步缓存: ${relativePath}`);
  488. return sanitizedUrl;
  489. }
  490. }
  491. const fallbackUrl = await WebDavUrlUtil.buildFullUrlByAccountId(song.webdav_account_id, relativePath);
  492. if (fallbackUrl) {
  493. Logger.warn(TAG, `WebDAV 使用全局查询到的URL: ${fallbackUrl}`);
  494. return sanitizePlaybackUrl(fallbackUrl);
  495. }
  496. Logger.error(TAG, `WebDAV URL构建失败,使用原始路径: ${relativePath}`);
  497. return sanitizePlaybackUrl(relativePath);
  498. } catch (error) {
  499. Logger.error(TAG, `WebDAV URL构建出错: ${(error as Error).message}`);
  500. const fallbackPath = song.remote_rel_path || song.filePath;
  501. return sanitizePlaybackUrl(fallbackPath);
  502. }
  503. }
  504. if (isNavidromeType(song.type) && song.webdav_account_id) {
  505. try {
  506. const manager = RemoteDriveManager.getInstance();
  507. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  508. if (!account) {
  509. throw new Error('Navidrome账号不可用');
  510. }
  511. const navSongId = song.remote_rel_path || song.id || song.filePath;
  512. const streamUrl = await navidromeApi.buildStreamUrl(account, navSongId);
  513. void ServerLogUtil.info(TAG, `流地址构建成功: ${streamUrl}`);
  514. void ServerLogUtil.debug(TAG, `播放songId=${navSongId}, account=${ServerLogUtil.sanitizeAccount(account)}`);
  515. return sanitizePlaybackUrl(streamUrl);
  516. } catch (error) {
  517. const err = error as Error;
  518. void ServerLogUtil.error(TAG, `URL构建失败: ${err.message}`);
  519. throw new Error(err.message);
  520. }
  521. }
  522. if (isSmbType(song.type) && song.webdav_account_id) {
  523. try {
  524. const manager = RemoteDriveManager.getInstance();
  525. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  526. if (!account) {
  527. throw new Error('SMB账号不可用');
  528. }
  529. const relativePath = extractSmbRelativePath(song, account.smbShare);
  530. const pathInfo = await resolveCacheFilePath(
  531. RemoteCacheType.SMB,
  532. account.id?.toString(),
  533. relativePath
  534. );
  535. const streamMeta: SmbStreamingMeta = {
  536. fileSize: song.videoSize,
  537. mimeType: song.mimeType,
  538. fileName: song.fileName || song.name
  539. };
  540. const streamingUrl = await ensureSmbFileStreaming(account, pathInfo.normalizedRelative, streamMeta);
  541. Logger.info(TAG, `SMB 流地址: ${streamingUrl}`);
  542. void scheduleMetadataExtractionFromCache(song, pathInfo.cachePath, metadataOptions, song.videoSize);
  543. const shouldBypassSanitize = streamingUrl.startsWith('http://127.0.0.1:');
  544. return shouldBypassSanitize ? streamingUrl : sanitizePlaybackUrl(streamingUrl);
  545. } catch (error) {
  546. const err = error as Error;
  547. Logger.error(TAG, `SMB 流式播放失败: ${err.message}`);
  548. throw new Error(err.message);
  549. }
  550. }
  551. if (isFtpType(song.type) && song.webdav_account_id) {
  552. try {
  553. const manager = RemoteDriveManager.getInstance();
  554. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  555. if (!account) {
  556. throw new Error('FTP账号不可用');
  557. }
  558. const relativePath = extractFtpRelativePath(song);
  559. const cachedPath = await RemoteCacheManager.ensureCached(RemoteCacheType.FTP, {
  560. account,
  561. remotePath: relativePath
  562. });
  563. Logger.info(TAG, `FTP 缓存路径: ${cachedPath}`);
  564. void scheduleMetadataExtractionFromCache(song, cachedPath, metadataOptions, song.videoSize);
  565. return cachedPath;
  566. } catch (error) {
  567. const err = error as Error;
  568. Logger.error(TAG, `FTP 缓存失败: ${err.message}`);
  569. throw new Error(err.message);
  570. }
  571. }
  572. if (isWebDavType(song.type)) {
  573. Logger.warn(TAG, `WebDAV歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
  574. return sanitizePlaybackUrl(song.filePath);
  575. }
  576. if (isSmbType(song.type)) {
  577. Logger.warn(TAG, `SMB歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
  578. return song.filePath;
  579. }
  580. if (isFtpType(song.type)) {
  581. Logger.warn(TAG, `FTP歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
  582. return song.filePath;
  583. }
  584. if (isNavidromeType(song.type)) {
  585. throw new Error('Navidrome歌曲缺少webdav_account_id,无法构建播放链接');
  586. }
  587. return song.filePath;
  588. }
  589. // 定义接口
  590. interface HiCarAspectRatio {
  591. ratio: number;
  592. name: string;
  593. }
  594. interface GeneratedObjectLiteralInterface_1 {
  595. assetId: string;
  596. title: string;
  597. artist: string;
  598. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  599. mediaUri: string;
  600. // 该字段大写,音频'AUDIO',视频'VIDEO'
  601. mediaType: string;
  602. mediaSize: number;
  603. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  604. startPosition: number;
  605. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  606. duration: number;
  607. albumCoverUri: string;
  608. albumTitle: string;
  609. appName: string;
  610. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  611. drmScheme: string;
  612. }
  613. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  614. const ITEM_HEIGHT: number = 65; // 列表项中高度
  615. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  616. //功能强大的音乐播放器
  617. @Preview
  618. @Component
  619. export struct LocalMusic {
  620. private prevOffsetY: number = 0; // 记录上一次的Y轴偏移量
  621. @State autoHideTitle: boolean = true //滚动自动隐藏标题栏
  622. // 字母表
  623. @State alphaBet: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
  624. 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  625. @State alphaBetStyle: GlobalAlphabetIndexerModifier = new GlobalAlphabetIndexerModifier()
  626. @State selectAlphaBetIndex: number = 0
  627. @State isShowAlphaBet: boolean = false
  628. @State isScrolling: boolean = false
  629. @State isTouchingAlphaBet: boolean = false
  630. @State alphabetHeight: number = 0
  631. public enableShowAlphabet: boolean = true // 是否显示字母表
  632. @State isShowPrecious: boolean = false //播控条显示上一首按钮
  633. //背景两侧流光控制器
  634. @State sceneBgController: HdsSceneController|undefined = deviceInfo.sdkApiVersion>=20
  635. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  636. new HdsSceneController()
  637. .setSceneParams({
  638. backgroundMaskColors: [Color.Green, Color.Red],
  639. firstEdgeFlowLight: {
  640. startPos: 0,
  641. endPos: 0.5,
  642. color: Color.Red
  643. },
  644. secondEdgeFlowLight: {
  645. startPos: 0,
  646. endPos: -0.5,
  647. color: Color.Green
  648. }
  649. }) : undefined;
  650. //背景流光控制器
  651. @State bgController: hdsEffect.ShaderEffectController|undefined = deviceInfo.sdkApiVersion>=20
  652. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  653. new hdsEffect.ShaderEffectController():undefined;
  654. @State showAddSheet:boolean = false
  655. searchController: SearchController = new SearchController()
  656. @State rightTopImage:Resource = $r('sys.symbol.sort')
  657. @State isEditAudio:boolean = false
  658. @State isExtractAcc:boolean = false
  659. @State isConverter:boolean = false
  660. @State isAIVoiceSeparation:boolean = false
  661. @State isExtractAudio:boolean = false
  662. @State isMergeAudio:boolean = false
  663. @State isCopyFileToDownLoad: boolean = false
  664. @State isChangeTone:boolean = false
  665. @State offHeight: number = 75
  666. @State currentSongList: Array<VideoItem> = []//当前歌单
  667. @Consume currentSongListName:string //当前歌单名称
  668. @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
  669. @State isRefreshing: boolean = false;
  670. @State maxRefreshingHeight: number = 100.0;
  671. private contentNode?: ComponentContent<Object> = undefined;
  672. // WebDAV相关实例变量(现在改为从内存读取,不再需要存储)
  673. @State ratioL: number = 1;
  674. @State mediaKuCount: number = 0;
  675. @State albumCount: number = 0;
  676. @State artistCount: number = 0;
  677. @State fastForwardSeconds: string = '10'
  678. @State isShowBackFast: boolean = true//快进快退按钮
  679. @State isCanAuto:boolean = true
  680. @State opacityValueImage: number = 1;
  681. @State tipPopup:boolean = false
  682. @Consume mType: number;
  683. @StorageProp('themeColor') themeColor: string =
  684. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  685. themeMode: number = 0;
  686. @State titleName: string = '首页'
  687. @State textStr: string = ''
  688. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  689. // private download_path: string = '';
  690. @Consume rootPath: string //音频根目录
  691. @Consume currentPath: string
  692. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  693. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  694. @State lockPath: string = ''
  695. @State favPath: string = ''
  696. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  697. @State historyPath: string = ''
  698. @State historyList: Array<VideoItem> = []
  699. @Consume isHistory: boolean
  700. static readonly HISTORY_MUSIC: string = 'music_historyList';
  701. private table: MediaTable = new MediaTable(getContext(this))
  702. private playlistTable: PlaylistTable | null = null
  703. private deletionWatcher: FileDeletionWatcher | null = null
  704. @State allPlaylists: Playlist[] = []
  705. @State isZero: boolean = false
  706. @State fileList: Array<string> = []
  707. @State dirList: Array<VideoItem> = []
  708. @Consume videoLocalList:VideoItem[]
  709. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  710. @State listRefreshKey: number = 0
  711. // @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  712. @StorageProp('mediaKuList') mediaKuList: Array<VideoItem> = []; //媒体库文件
  713. @State artistList: Array<VideoItem> = []; //艺术家文件
  714. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  715. @State albumList: Array<VideoItem> = []; //专辑文件
  716. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  717. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  718. @State imageOpacities: number[] = [];
  719. @Consume isCanBack: boolean
  720. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  721. @State showSingleLyric: boolean = false
  722. @State sortType: number = 4 //默认排序方式
  723. @State isShowSimi: boolean = false //是否显示私密音频
  724. @State isShowFAV: boolean = true //是否显示我的收藏
  725. @State isShowTitleBar: boolean = true //是否显示分类导航条
  726. @State isShowAllBar: boolean = true //是否显示播放全部条
  727. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  728. @State isShowHistory: boolean = true //是否显示最近播放
  729. @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
  730. @State isGridMusic: boolean = false //是否网格布局
  731. @State isCircleBtn: boolean = false //是否圆形播放按钮
  732. @State twoFingerType: number = 3 //双支放大缩小的类型
  733. @State isScrollHide: boolean = false //是否滚动隐藏
  734. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  735. @State isStartAutoPlay: boolean = false //启动后自动播放
  736. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  737. @State isShowHeader: boolean = true
  738. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  739. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  740. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  741. @State isSwipe: boolean = false //listItem的左滑开关
  742. @State openSkipSongAnimate: boolean = true//切歌动画效果
  743. @State customizeBgPath: string | undefined = '';
  744. @State isDarkMode: boolean = false
  745. @State lyricTextWeight: number = 400
  746. @State lyricTextWeightPip: number = 400
  747. @State currentSwiperIndex: number = 0
  748. @State blurValue: number = 0 //背景模糊
  749. @State bgBrightness: number = 0 //背景亮度
  750. private listScroller: ListScroller = new ListScroller()
  751. private playListScroller: Scroller = new Scroller()
  752. @State isOneKeyTags:boolean = false
  753. @State isFixMessy:boolean = false
  754. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  755. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  756. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  757. @StorageProp('windowWidth') windowWidth: number = 0;
  758. @StorageProp('windowHeight') windowHeight: number = 0;
  759. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  760. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  761. private UNKONWN:string = '';
  762. private listArea: Area = {
  763. width: 0,
  764. height: 0,
  765. position: {},
  766. globalPosition: {}
  767. }
  768. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  769. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  770. // WebDAV认证信息缓存(作为实例变量,比全局上下文更可靠)
  771. private currentWebDavAuthInfo: WebDavAuthItem | null = null;
  772. //瀑布流的列数横竖屏动态切换
  773. onIsLandscapeChange() {
  774. if(this.isLandscape){
  775. this.columns = 4
  776. }else{
  777. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  778. }
  779. }
  780. onColorModeChange() {
  781. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  782. }
  783. //点击某个歌单id发生变化的时候回调
  784. onIDChange(){
  785. console.log('onecold 歌单id发生变化this.currentSongListID='+this.currentSongListID)
  786. console.log('onecold 歌单id发生变化this.currentSongListName='+this.currentSongListName)
  787. if(this.modeType==4){
  788. this.titleName = this.currentSongListName
  789. this.rightTopImage = $r('sys.symbol.sort')
  790. //获取缓存
  791. const cacheSongs:string =PreferencesUtil.getStringSync(this.currentSongListID+'currentSongList', '')
  792. console.log('onecold 歌单id发生变化获取缓存2 cacheSongs = '+cacheSongs)
  793. if(StrUtil.isNotEmpty(cacheSongs)){
  794. this.currentSongList = JSON.parse(cacheSongs) as VideoItem[]
  795. this.updateListData(this.currentSongList, true)
  796. }
  797. this.doSongListTask()//获取歌单信息
  798. }
  799. }
  800. async doSongListTask() {
  801. // 初始化歌单数据库
  802. const playlistTable = new PlaylistTable(this.context);
  803. // 查询歌单中的所有歌曲
  804. const playlistSongs: PlaylistSong[] = await playlistTable.queryPlaylistSongs(this.currentSongListID);
  805. console.log('onecold 歌单id发生变化获取缓存7 playlistSongs='+playlistSongs.length)
  806. if (ArrayUtil.isEmpty(playlistSongs)) {
  807. this.updateListData([], true)
  808. } else {
  809. this.currentSongList = await convertPlaylistSongsToVideoItems(this.context, playlistSongs);
  810. console.log('onecold 从数据库读取的歌曲为 playlistSongs='+this.currentSongList.length)
  811. this.updateListData(this.currentSongList, true)
  812. if (ArrayUtil.isNotEmpty(this.currentSongList)&&this.currentSongList.length > 100) {
  813. // 只保存前100条记录到缓存中
  814. let canceList = this.currentSongList.slice(0, 100);
  815. PreferencesUtil.putSync(this.currentSongListID+'currentSongList',
  816. JSON.stringify(canceList))
  817. } else {
  818. PreferencesUtil.putSync(this.currentSongListID+'currentSongList', JSON.stringify(this.currentSongList));
  819. }
  820. }
  821. this.isRefreshing = false
  822. }
  823. onModeChange() {
  824. this.isFavMusic = false
  825. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  826. switch (this.modeType) {
  827. case 0:
  828. this.getSortedFiles(this.currentPath)
  829. break
  830. case 1:
  831. this.rightTopImage = $r('sys.symbol.sort')
  832. this.updateListData(this.mediaKuList)
  833. this.titleName = Utility.resourceToString(this.context,$r('app.string.media_ku'))
  834. break
  835. case 2:
  836. this.rightTopImage = $r('sys.symbol.sort')
  837. this.updateListData(this.artistList)
  838. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  839. break
  840. case 3:
  841. this.rightTopImage = $r('sys.symbol.sort')
  842. this.updateListData(this.albumList)
  843. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  844. break
  845. }
  846. }
  847. // @Consume currentSong: VideoItem | undefined;
  848. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  849. // @StorageLink('isPlay') isPlay: boolean = false;
  850. @Consume isShowPlay: boolean ;
  851. @StorageLink('songList') songList: Array<VideoItem> = [];
  852. @State translateY: number = 0;
  853. @State isShowSheet: boolean = false;
  854. @State isShowSheetView: boolean = false;
  855. @State isShowTimeCloseView: boolean = false;
  856. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  857. @StorageLink('currIndex') curIndex: number = 0;
  858. @Consume isShowDrawer: boolean;
  859. @Consume offsetX: number;
  860. @State isFac: boolean = false;
  861. @State favList: Array<VideoItem> = []
  862. @Consume isFavMusic: boolean
  863. @State isClickedPLayAll: boolean = false;
  864. private scrollerForlist: ListScroller = new ListScroller();
  865. private knockController: KnockController | undefined = undefined;
  866. // 修改为:
  867. imagesF: ImageFrameInfo[] = CommonConstants.IMAGE_FRAME_INFO;
  868. @StorageProp('animationState') animationState: AnimationStatus = AnimationStatus.Initial
  869. // 缓存机制
  870. private cache: Map<string, Array<VideoItem>> = new Map();
  871. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  872. // 持久化缓存
  873. private async saveCacheToStorage() {
  874. const cacheArray = Array.from(this.cache.entries());
  875. const stringCacheArray = Array.from(this.stringCache.entries());
  876. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  877. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  878. }
  879. // 载入缓存
  880. private async loadCacheFromStorage() {
  881. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  882. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  883. if (cacheString) {
  884. const parsedCache: Object | null = JSON.parse(cacheString);
  885. if (parsedCache && Array.isArray(parsedCache)) {
  886. const cacheArray: [string, Array<VideoItem>][] = parsedCache;
  887. this.cache = new Map(cacheArray);
  888. }
  889. }
  890. if (stringCacheString) {
  891. const parsedStringCache: Object | null = JSON.parse(stringCacheString);
  892. if (parsedStringCache && Array.isArray(parsedStringCache)) {
  893. const stringCacheArray: [string, string][] = parsedStringCache;
  894. this.stringCache = new Map(stringCacheArray);
  895. }
  896. }
  897. }
  898. // 查找缓存
  899. private findCache(key: string): Array<VideoItem> | undefined {
  900. return this.cache.get(key);
  901. }
  902. // 查找字符串缓存
  903. private findStringCache(key: string): string | undefined {
  904. return this.stringCache.get(key);
  905. }
  906. // 添加缓存
  907. private addCache(key: string, value: Array<VideoItem>) {
  908. this.cache.set(key, value);
  909. }
  910. // 添加字符串缓存
  911. private addStringCache(key: string, value: string) {
  912. this.stringCache.set(key, value);
  913. }
  914. // 删除缓存
  915. private deleteCache(key: string) {
  916. this.cache.delete(key);
  917. this.saveCacheToStorage()
  918. }
  919. // 删除字符串缓存
  920. private deleteStringCache(key: string) {
  921. this.stringCache.delete(key);
  922. }
  923. // 多选机制
  924. @State selectedFiles: Array<VideoItem> = [];
  925. @Consume isMultiSelect: boolean;
  926. @State isAllSelected: boolean = false;
  927. @State appName: string = ''
  928. @State isHasDir: boolean = false
  929. @State packName: string = ''
  930. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  931. doSwipBack() {
  932. if(this.isSearchMode){
  933. console.info('onecold doSwipBack = ' +this.isSearchMode)
  934. this.isSearchMode = false
  935. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  936. this.searchText = ''
  937. this.getSortedFiles(this.currentPath)
  938. return
  939. }
  940. this.onSearchInput('')
  941. return
  942. }
  943. this.isZero = false
  944. if (this.modeType !== 0 && this.isCanBack) {
  945. this.onModeChange()
  946. this.isCanBack = false
  947. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  948. setTimeout(() => {
  949. if (this.modeType == 2) {
  950. if (this.isGridMusic||this.twoFingerType==4) {
  951. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  952. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  953. if(this.twoFingerType==4){
  954. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  955. }else{
  956. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  957. }
  958. } else {
  959. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  960. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  961. }
  962. } else if (this.modeType == 3) {
  963. if (this.isGridMusic||this.twoFingerType==4) {
  964. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  965. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 0
  966. if(this.twoFingerType==4){
  967. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  968. }else{
  969. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  970. }
  971. } else {
  972. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  973. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  974. }
  975. }
  976. }, 200)
  977. return
  978. }
  979. if (this.isHistory || this.isFavMusic) {
  980. this.isHistory = false
  981. this.getSortedFiles(this.currentPath)
  982. return
  983. }
  984. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  985. animateTo({ duration: 555 }, () => {
  986. // 动画闭包内控制Image组件的出现和消失
  987. this.isShowDrawer = !this.isShowDrawer
  988. this.offsetX = 0
  989. })
  990. return
  991. }
  992. //返回上一级歌单的滚动位置
  993. setTimeout(() => {
  994. if (this.modeType == 0) {
  995. if (this.isGridMusic||this.twoFingerType==4) {
  996. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  997. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
  998. if(this.twoFingerType==4){
  999. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  1000. }else{
  1001. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1002. }
  1003. } else {
  1004. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  1005. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1006. }
  1007. }
  1008. }, 300)
  1009. this.currentPath = Utility.getParentDirectory(this.currentPath)
  1010. Logger.info('this.currentPath2 = ' + this.currentPath)
  1011. this.getSortedFiles(this.currentPath)
  1012. }
  1013. // 组件生命周期
  1014. aboutToAppear() {
  1015. console.info('onecold aboutToAppear sdkApiVersion = '+deviceInfo.sdkApiVersion)
  1016. if(ArrayUtil.isNotEmpty(this.videoLocalList)&&this.modeType==0){
  1017. this.updateListData(this.videoLocalList)
  1018. }
  1019. // 初始化 PlaylistTable
  1020. this.playlistTable = new PlaylistTable(getContext(this))
  1021. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  1022. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  1023. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  1024. this.tipPopup = !this.tipPopup
  1025. PreferencesUtil.putSync('isFirstTiped',false)
  1026. }
  1027. this.initSetting()
  1028. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  1029. Utility.getAppName(getContext(this)).then((appName: string) => {
  1030. this.appName = appName
  1031. })
  1032. this.packName = AppUtil.getBundleName()
  1033. this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
  1034. this.loadCacheFromStorage(); // 加载文件夹缓存
  1035. // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
  1036. this.initLoadCache()
  1037. this.mkDownLoadDir()
  1038. let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
  1039. // 监听广播事件(打开其他应用处理)
  1040. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  1041. this.saveVideoDatas([eventData.data?.message], true)
  1042. });
  1043. //侧滑广播接收时间
  1044. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
  1045. // 监听广播事件(打开其他应用处理)
  1046. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  1047. animateTo({ duration: 555 }, () => {
  1048. this.doSwipBack()
  1049. })
  1050. });
  1051. //ScanFilePage广播接收时间
  1052. let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
  1053. // 监听ScanFilePage广播事件(更新数据库)
  1054. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  1055. this.doUpdateData()
  1056. });
  1057. // 监听歌单播放请求事件
  1058. let eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY }
  1059. emitter.on(eventPlaylistPlay, async (eventData: emitter.EventData) => {
  1060. const data = eventData.data as Record<string, Object>
  1061. if (!data) {
  1062. Logger.error('heanup eventPlaylistPlay: eventData.data is undefined or null')
  1063. return
  1064. }
  1065. // 检查歌单播放数据结构
  1066. if (data.playlistId && data.songFilePaths && data.startIndex !== undefined) {
  1067. const playlistData: PlaylistEventData = {
  1068. playlistId: data.playlistId as string,
  1069. playlistName: data.playlistName as string,
  1070. songCount: data.songCount as number,
  1071. startIndex: data.startIndex as number,
  1072. isJump: data.isJump as boolean,
  1073. songFilePaths: data.songFilePaths as string[]
  1074. }
  1075. await this.handlePlaylistPlayRequest(
  1076. playlistData.playlistId,
  1077. playlistData.playlistName,
  1078. playlistData.songFilePaths,
  1079. playlistData.startIndex,
  1080. playlistData.isJump,
  1081. )
  1082. return
  1083. }
  1084. Logger.error('heanup eventPlaylistPlay: 接收到无效的数据结构')
  1085. });
  1086. let eventRefreshSort: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_REFRESH_SORT }
  1087. // 监听广播事件(通用设置配置更新)
  1088. emitter.on(eventRefreshSort, (eventData: emitter.EventData) => {
  1089. if(this.modeType ==4){
  1090. this.doSongListTask()//获取歌单信息
  1091. }
  1092. });
  1093. let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
  1094. // 监听广播事件(通用设置配置更新)
  1095. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  1096. this.doChangeSetting()
  1097. });
  1098. let event: Callback<InterruptEvent> = (event) => {
  1099. // LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  1100. console.info(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  1101. this.savePlaybackPosition()
  1102. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  1103. this.pause();
  1104. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  1105. console.info(`onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  1106. console.info('onecold startPlayOrResumePlay 514')
  1107. this.startPlayOrResumePlay();
  1108. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  1109. console.info(`onecold 与其他应用音频冲突 被截断点 INTERRUPT_HINT_STOP`)
  1110. if(!this.isSameTimePlay){
  1111. this.stop();
  1112. }
  1113. }
  1114. }
  1115. this.mIjkMediaPlayer.on('audioInterrupt', event);
  1116. // 音频设备断连回调处理
  1117. let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  1118. LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  1119. if (event.reason === DeviceChangeReason.REASON_NEW_DEVICE_AVAILABLE) { // 音频设备连接
  1120. } else if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  1121. console.info('onecold 音频设备断开连接, 暂停播放')
  1122. this.pause();
  1123. }
  1124. }
  1125. // 订阅音频设备断开和连接事件
  1126. this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  1127. const eventPause: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_PAUSE }
  1128. // 监听广播事件(hicar断开暂停播放)
  1129. emitter.on(eventPause, (eventData: emitter.EventData) => {
  1130. this.pause();
  1131. });
  1132. this.makeWorker()
  1133. //折叠屏的屏幕显示模式变化
  1134. display.on('foldDisplayModeChange', (data) => {
  1135. this.doChangeBarHeight()
  1136. });
  1137. display.on('foldStatusChange', (data) => {
  1138. Logger.info('onecold foldStatusChange ')
  1139. });
  1140. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  1141. // 读取 themeMode 并同步 currentColorMode
  1142. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  1143. this.applyThemeMode(this.themeMode)
  1144. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  1145. AppStorage.setOrCreate('themeColor', themeColor);
  1146. this.themeColor = themeColor;
  1147. this.doChangeSetting()
  1148. this.windowClass.on('windowSizeChange', (size) => {
  1149. LogUtil.info('onecold windowSizeChange')
  1150. this.doChangeBarHeight()
  1151. let viewWidth = px2vp(size.width);
  1152. let viewHeight = px2vp(size.height);
  1153. if(this.isPhoneLan()){
  1154. this.is_auto_hide_progress = false
  1155. if(this.isHiCar()){
  1156. return
  1157. }
  1158. setTimeout(() => {
  1159. this.is_auto_hide_progress = true
  1160. }, 6000)
  1161. }else{
  1162. this.startAutoHide()
  1163. }
  1164. });
  1165. this.eventHub.on('onStateChange', (fg: boolean) => {
  1166. if (fg && this.curState === 'STARTED') {
  1167. this.stopPip();
  1168. }
  1169. });
  1170. //NewIndex的博空调收到eventHub消息控制播放
  1171. this.getUIContext().getHostContext()!.eventHub.on('playOrPause', () => {
  1172. if (ArrayUtil.isNotEmpty(this.songList)) {
  1173. this.playOrPause();
  1174. } else {
  1175. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1176. }
  1177. });
  1178. this.getUIContext().getHostContext()!.eventHub.on('playPrevious', () => {
  1179. if (ArrayUtil.isNotEmpty(this.songList)) {
  1180. this.playPrevious();
  1181. } else {
  1182. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1183. }
  1184. });
  1185. this.getUIContext().getHostContext()!.eventHub.on('playNext', () => {
  1186. if (ArrayUtil.isNotEmpty(this.songList)) {
  1187. this.playNext();
  1188. } else {
  1189. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1190. }
  1191. });
  1192. this.getUIContext().getHostContext()!.eventHub.on('showPlayerView', () => {
  1193. this.showPlayerView();
  1194. });
  1195. this.getUIContext().getHostContext()!.eventHub.on('openPlayList', () => {
  1196. this.openPlayList();
  1197. });
  1198. }
  1199. //载入媒体库,艺术家,专辑等缓存
  1200. initLoadCache(){
  1201. this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
  1202. this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
  1203. this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
  1204. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  1205. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  1206. if(ArrayUtil.isNotEmpty(cachedList)){
  1207. this.mediaKuList = cachedList
  1208. if(this.modeType==1){
  1209. this.updateListData(this.mediaKuList)
  1210. }
  1211. }
  1212. let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
  1213. let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
  1214. if(ArrayUtil.isNotEmpty(artistCachedList)){
  1215. this.artistList = artistCachedList
  1216. let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
  1217. const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
  1218. this.artistMap = new Map(parsedArray);
  1219. // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
  1220. if(this.modeType==2){
  1221. this.updateListData(this.artistList)
  1222. }
  1223. }
  1224. let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
  1225. let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
  1226. if(ArrayUtil.isNotEmpty(albumCachedList)){
  1227. this.albumList = albumCachedList
  1228. let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
  1229. const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
  1230. this.albumMap = new Map(parsedArray);
  1231. if(this.modeType==3){
  1232. this.updateListData(this.albumList)
  1233. }
  1234. }
  1235. }
  1236. startAutoHide() {
  1237. if(this.isHiCar()){
  1238. return
  1239. }
  1240. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  1241. console.info('onecold startAutoHide')
  1242. this.is_auto_hide_progress = false
  1243. setTimeout(() => {
  1244. this.is_auto_hide_progress = true
  1245. }, 6000)
  1246. }
  1247. }
  1248. applyThemeMode(mode: number) {
  1249. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  1250. if (mode === 1) {
  1251. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  1252. } else if (mode === 2) {
  1253. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1254. }
  1255. AppStorage.setOrCreate('currentColorMode', colorMode)
  1256. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  1257. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  1258. AppStorage.setOrCreate('themeMode', mode)
  1259. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1260. // 只有强制浅色/深色时才主动设置
  1261. const context = getContext(this) as common.UIAbilityContext
  1262. context.getApplicationContext().setColorMode(colorMode)
  1263. }
  1264. initSetting() {
  1265. this.autoHideTitle = PreferencesUtil.getBooleanSync('autoHideTitle', true)
  1266. this.isShowPrecious = PreferencesUtil.getBooleanSync('isShowPrecious', false)
  1267. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1268. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  1269. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  1270. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, false)
  1271. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  1272. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  1273. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  1274. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  1275. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  1276. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  1277. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  1278. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  1279. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  1280. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 2)
  1281. this.isCoverTop = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP, true)
  1282. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  1283. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  1284. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  1285. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  1286. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  1287. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  1288. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  1289. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  1290. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  1291. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  1292. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  1293. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  1294. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  1295. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  1296. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  1297. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  1298. this.isCopyFileToDownLoad = PreferencesUtil.getBooleanSync(SettingPage.IS_COPYFILE_TO_DOWNLOAD, false)
  1299. let audioManager = audio.getAudioManager();
  1300. let audioSessionManager: audio.AudioSessionManager = audioManager.getSessionManager();
  1301. if(this.isSameTimePlay){
  1302. //与其他应用同时播放,关键代码
  1303. let strategy: audio.AudioSessionStrategy = {
  1304. concurrencyMode: audio.AudioConcurrencyMode.CONCURRENCY_MIX_WITH_OTHERS
  1305. };
  1306. audioSessionManager.activateAudioSession(strategy).then(() => {
  1307. console.info('onecold Succeeded in doing activateAudioSession.');
  1308. }).catch((err: BusinessError) => {
  1309. console.error(`Failed to activateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1310. });
  1311. }else{
  1312. let isActivated = audioSessionManager.isAudioSessionActivated();
  1313. if(isActivated){
  1314. audioSessionManager.deactivateAudioSession().then(() => {
  1315. console.info('Succeeded in doing deactivateAudioSession.');
  1316. }).catch((err: BusinessError) => {
  1317. console.error(`Failed to deactivateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1318. });
  1319. }
  1320. }
  1321. if(this.volumeSmall){
  1322. this.volume = 0.5
  1323. }else{
  1324. this.volume = 1
  1325. }
  1326. //如果是hicar连接状态,这些都是false
  1327. if(this.isHiCar()){
  1328. this.isShowTitleBar = true//不显示导航栏
  1329. this.columns=4
  1330. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  1331. {
  1332. this.isShowHeader = false//二级菜单不显示头部
  1333. this.isGridMusic= false//用list不用网格
  1334. this.isCoverTopBig = false
  1335. }
  1336. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  1337. }
  1338. if (this.isSavePlayMode) {
  1339. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  1340. }
  1341. }
  1342. doChangeSetting() {
  1343. this.initSetting()
  1344. this.deleteCache(this.currentPath)
  1345. if (this.modeType === 0) {
  1346. this.getSortedFiles(this.currentPath)
  1347. }
  1348. }
  1349. doChangeBarHeight() {
  1350. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  1351. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  1352. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  1353. this.setBarHeightNormal()
  1354. }
  1355. }
  1356. onPageShow() {
  1357. this.knockController?.immersiveListening();
  1358. app.setImageCacheCount(100);
  1359. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  1360. app.setImageRawDataCacheSize(104857600);
  1361. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  1362. }
  1363. //开启线程查看各个数据库
  1364. makeWorker() {
  1365. setTimeout(() => {
  1366. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  1367. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  1368. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  1369. // workerInstance.postMessage({
  1370. // code: 1,
  1371. // data1: this.context,
  1372. // data2: this.rootPath,
  1373. // data3: this.lockPath,
  1374. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1375. // data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  1376. // });
  1377. PreferencesUtil.putSync('isFirstApp', false)
  1378. } else {
  1379. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1380. workerInstance.postMessage({ code: 3, data: this.context });
  1381. workerInstance.postMessage({ code: 4, data: this.context });
  1382. this.getHistoryList(false)
  1383. }
  1384. }, 1000)
  1385. workerInstance.onmessage = (e: MessageEvents): void => {
  1386. switch (e.data.code) {
  1387. case 101: //第一次扫描文件夹入库
  1388. ToastUtil.showToast('刷新同步数据库成功!')
  1389. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  1390. this.doAllUpdateData()
  1391. break;
  1392. case 102: //查询媒体库列表
  1393. this.isRefreshing = false
  1394. this.mediaKuList = e.data.data
  1395. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  1396. Utility.doSortListAscending(this.mediaKuList)
  1397. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  1398. if (this.modeType === 1) {
  1399. this.updateListData(this.mediaKuList)
  1400. }
  1401. PreferencesUtil.putSync('mediaKuCount', this.mediaKuList.length)
  1402. // 处理媒体库前100条记录,列表长度并存储到PreferencesUtil
  1403. if (ArrayUtil.isNotEmpty(this.mediaKuList)&&this.mediaKuList.length > 100) {
  1404. // 只保存前100条记录到缓存中
  1405. let truncatedList = this.mediaKuList.slice(0, 100);
  1406. PreferencesUtil.putSync('mediaKuList', JSON.stringify(truncatedList));
  1407. } else {
  1408. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  1409. }
  1410. break;
  1411. case 103: //收到查询艺术家列表
  1412. this.isRefreshing = false
  1413. this.artistMap = e.data.data1;
  1414. this.artistList = e.data.data2;
  1415. PreferencesUtil.putSync('artistCount', this.artistList.length)
  1416. // 处理艺术家前100条记录,列表长度并存储到PreferencesUtil
  1417. if (ArrayUtil.isNotEmpty(this.artistList)&&this.artistList.length > 100) {
  1418. // 只保存前100条记录到缓存中
  1419. let truncatedList = this.artistList.slice(0, 100);
  1420. PreferencesUtil.putSync('artistList', JSON.stringify(truncatedList));
  1421. } else {
  1422. PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
  1423. }
  1424. // 处理并缓存前60条艺术家数据
  1425. const sortedEntries = Array.from(this.artistMap.entries())
  1426. .sort((a, b) => b[1].length - a[1].length)
  1427. .slice(0, 60);
  1428. PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
  1429. break;
  1430. case 104: //收到查询专辑列表
  1431. this.isRefreshing = false
  1432. this.albumMap = e.data.data1;
  1433. this.albumList = e.data.data2
  1434. //查询完毕在启动是否自动播放
  1435. if (this.isStartAutoPlay&&this.isCanAuto) {
  1436. this.isCanAuto = false
  1437. console.info('onecold startPlayOrResumePlay 757')
  1438. this.startPlayOrResumePlay()
  1439. }
  1440. PreferencesUtil.putSync('albumCount', this.albumList.length)
  1441. // 处理专辑前100条记录,列表长度并存储到PreferencesUtil
  1442. if (ArrayUtil.isNotEmpty(this.albumList)&&this.albumList.length > 100) {
  1443. // 只保存前100条记录到缓存中
  1444. let truncatedList = this.albumList.slice(0, 100);
  1445. PreferencesUtil.putSync('albumList', JSON.stringify(truncatedList));
  1446. } else {
  1447. PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
  1448. }
  1449. const mapArrayAlbum = Array.from(this.albumMap.entries())
  1450. .sort((a, b) => b[1].length - a[1].length)
  1451. .slice(0, 60);
  1452. PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
  1453. break;
  1454. case 105: // 缓存完成后返回的元数据
  1455. this.handleWorkerMetadataPayload(e.data.data as WorkerMetadataPayload);
  1456. break;
  1457. case 106: // 编辑音乐元数据和封面完成
  1458. this.handleEditMusicResult(e.data);
  1459. break;
  1460. }
  1461. };
  1462. // 在调用terminate后,执行onexit
  1463. workerInstance.onexit = (code) => {
  1464. metadataExtractionInFlight.clear();
  1465. Logger.info(TAG, 'workerInstance 线程已退出,code: ' + code);
  1466. }
  1467. workerInstance.onerror = (err: ErrorEvent) => {
  1468. metadataExtractionInFlight.clear();
  1469. console.error('workerInstance 线程执行发生异常: ' + err.message)
  1470. }
  1471. }
  1472. private handleWorkerMetadataPayload(payload: WorkerMetadataPayload | undefined): void {
  1473. if (!payload || !payload.originFilePath) {
  1474. return;
  1475. }
  1476. metadataExtractionInFlight.delete(payload.originFilePath);
  1477. if (payload.error) {
  1478. Logger.warn(TAG, `缓存文件元数据解析失败: ${payload.error}`);
  1479. return;
  1480. }
  1481. this.applyMetadataToCollections(payload.originFilePath, payload);
  1482. }
  1483. private applyMetadataToCollections(filePath: string, payload: WorkerMetadataPayload): void {
  1484. const targets: Array<VideoItem> = [];
  1485. let mainListUpdated = false;
  1486. let playlistUpdated = false;
  1487. if (this.currentSong && this.currentSong.filePath === filePath) {
  1488. targets.push(this.currentSong);
  1489. }
  1490. const collectFromList = (list?: Array<VideoItem>, markUpdated?: () => void) => {
  1491. if (!list || list.length === 0) {
  1492. return;
  1493. }
  1494. const found = Utility.getItemByFilePath(list, filePath);
  1495. if (found) {
  1496. markUpdated?.();
  1497. targets.push(found);
  1498. }
  1499. };
  1500. collectFromList(this.videoLocalList, () => {
  1501. mainListUpdated = true;
  1502. });
  1503. collectFromList(this.songList, () => {
  1504. playlistUpdated = true;
  1505. });
  1506. collectFromList(this.historyList);
  1507. collectFromList(this.favList);
  1508. const remoteManager = RemoteDriveManager.getInstance();
  1509. collectFromList(remoteManager.webDavSongs);
  1510. const updated = new Set<VideoItem>();
  1511. const remoteMetadataUpdates: Map<string, WebDavMetadataUpdatePayload> = new Map();
  1512. for (let i = 0; i < targets.length; i++) {
  1513. const target = targets[i];
  1514. if (!target || updated.has(target)) {
  1515. continue;
  1516. }
  1517. updated.add(target);
  1518. this.mergeVideoItemWithPayload(target, payload);
  1519. if (isRemoteCloudType(target.type) && StrUtil.isNotEmpty(target.filePath)) {
  1520. remoteMetadataUpdates.set(target.filePath, {
  1521. filePath: target.filePath,
  1522. pixelMapPath: target.pixelMapPath,
  1523. name: target.name,
  1524. artist: target.artist
  1525. });
  1526. }
  1527. }
  1528. if (this.currentSong && this.currentSong.filePath === filePath) {
  1529. this.mergeVideoItemWithPayload(this.currentSong, payload);
  1530. if (payload.name) {
  1531. this.name = payload.name;
  1532. }
  1533. if (payload.artist) {
  1534. this.artist = payload.artist;
  1535. }
  1536. if (payload.pixelMapPath) {
  1537. this.cover = payload.pixelMapPath;
  1538. }
  1539. if (payload.lyricContent) {
  1540. this.applyInlineLyricContent(payload.lyricContent);
  1541. }
  1542. this.currentSong = cloneVideoItem(this.currentSong);
  1543. AppStorage.setOrCreate('currentSong', this.currentSong);
  1544. }
  1545. const primaryTarget = targets.length > 0 ? targets[0] : undefined;
  1546. if (primaryTarget) {
  1547. this.persistRemoteMetadataToDb(primaryTarget).catch((error: Error) => {
  1548. Logger.error(TAG, `缓存元数据持久化失败: ${error.message}`);
  1549. });
  1550. }
  1551. if (remoteMetadataUpdates.size > 0) {
  1552. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  1553. emitter.emit(eventUpdate, { data: Array.from(remoteMetadataUpdates.values()) });
  1554. }
  1555. this.refreshLazyListViews(mainListUpdated, playlistUpdated);
  1556. }
  1557. private handleEditMusicResult(result: WorkerEditMusicResult): void {
  1558. // 关闭进度条
  1559. DialogHelper.closeLoading();
  1560. if (result.success) {
  1561. console.log("heanup 编辑信息成功,数据库已同步");
  1562. if (result.coverResult) {
  1563. ToastUtil.showToast('内嵌封面成功');
  1564. }
  1565. ToastUtil.showToast('内嵌音乐标签成功');
  1566. this.isShowMoreView = false;
  1567. this.name = this.titleStr;
  1568. // 同步当前播放的歌曲信息
  1569. if (this.editingItem && this.editingItem.filePath == this.currentSong?.filePath) {
  1570. this.currentSong.name = this.titleStr;
  1571. this.artist = this.artistStr;
  1572. this.currentSong.artist = this.artistStr;
  1573. this.currentSong.album = this.ablumStr;
  1574. this.currentSong.year = this.yearStr;
  1575. this.currentSong.genre = this.genreStr;
  1576. this.currentSong.track = this.trackStr;
  1577. this.currentSong.lyricContent = this.lyricConStr;
  1578. this.currentSong.ALBUMARTIST = this.albumArtistStr;
  1579. this.currentSong.COMPOSER = this.composerStr;
  1580. this.currentSong.LYRICIST = this.lyricistStr;
  1581. this.currentSong.COMMENT = this.commentStr;
  1582. }
  1583. // if (result.needRefreshList && this.modeType == 0) {
  1584. // this.deleteCache(this.currentPath);
  1585. // this.getSortedFiles(this.currentPath);
  1586. // }
  1587. // 同步编辑字段到本地列表
  1588. if (this.editingItem) {
  1589. this.syncEditedFields(this.editingItem);
  1590. this.syncListsAfterEdit(this.editingItem.filePath);
  1591. this.doUpateEditedFields(this.editingItem);
  1592. }
  1593. // 清理临时变量
  1594. this.longItemFilePath = '';
  1595. this.tempLyricContent = '';
  1596. this.isShowEdit = false;
  1597. this.imagePathStr = '';
  1598. } else {
  1599. console.error("heanup 编辑信息失败: " + result.error);
  1600. ToastUtil.showToast('编辑失败: ' + (result.error || '未知错误'));
  1601. // 清理临时变量
  1602. this.longItemFilePath = '';
  1603. this.tempLyricContent = '';
  1604. this.isShowEdit = false;
  1605. this.imagePathStr = '';
  1606. }
  1607. }
  1608. private assignStringMetadata(target: VideoItem, key: keyof VideoItem, value?: string | null, allowEmpty = false): void {
  1609. if (value === undefined || value === null) {
  1610. return;
  1611. }
  1612. const text = value.toString();
  1613. if (!allowEmpty && text.trim().length === 0) {
  1614. return;
  1615. }
  1616. Reflect.set(target, key as string, value);
  1617. }
  1618. private assignNumberMetadata(target: VideoItem, key: keyof VideoItem, value?: number | null): void {
  1619. if (value === undefined || value === null || Number.isNaN(value)) {
  1620. return;
  1621. }
  1622. Reflect.set(target, key as string, value);
  1623. }
  1624. private mergeVideoItemWithPayload(target: VideoItem, payload: WorkerMetadataPayload): void {
  1625. if (!target || !payload) {
  1626. return;
  1627. }
  1628. this.assignStringMetadata(target, 'name', payload.name);
  1629. this.assignStringMetadata(target, 'artist', payload.artist);
  1630. this.assignStringMetadata(target, 'album', payload.album);
  1631. this.assignStringMetadata(target, 'bit_rate', payload.bit_rate);
  1632. this.assignStringMetadata(target, 'duration', payload.duration);
  1633. this.assignStringMetadata(target, 'sampleRate', payload.sampleRate);
  1634. this.assignStringMetadata(target, 'mimeType', payload.mimeType);
  1635. this.assignStringMetadata(target, 'size', payload.size);
  1636. this.assignStringMetadata(target, 'pixelMapPath', payload.pixelMapPath);
  1637. this.assignStringMetadata(target, 'lyricContent', payload.lyricContent, true);
  1638. this.assignStringMetadata(target, 'genre', payload.genre);
  1639. this.assignStringMetadata(target, 'track', payload.track);
  1640. this.assignStringMetadata(target, 'bits_per_raw_sample', payload.bits_per_raw_sample);
  1641. this.assignStringMetadata(target, 'channels', payload.channels);
  1642. this.assignStringMetadata(target, 'channel_layout', payload.channel_layout);
  1643. this.assignStringMetadata(target, 'start_time', payload.start_time);
  1644. this.assignStringMetadata(target, 'year', payload.year);
  1645. this.assignStringMetadata(target, 'disc', payload.disc);
  1646. this.assignStringMetadata(target, 'ALBUMARTIST', payload.ALBUMARTIST);
  1647. this.assignStringMetadata(target, 'COMPOSER', payload.COMPOSER);
  1648. this.assignStringMetadata(target, 'LYRICIST', payload.LYRICIST);
  1649. this.assignStringMetadata(target, 'COMMENT', payload.COMMENT, true);
  1650. this.assignNumberMetadata(target, 'videoSize', payload.videoSize);
  1651. this.assignNumberMetadata(target, 'probe_score', payload.probe_score);
  1652. this.assignNumberMetadata(target, 'nb_streams', payload.nb_streams);
  1653. this.assignNumberMetadata(target, 'nb_programs', payload.nb_programs);
  1654. }
  1655. private mergeVideoItemFromSource(target: VideoItem, source: VideoItem): void {
  1656. if (!target || !source) {
  1657. return;
  1658. }
  1659. this.assignStringMetadata(target, 'name', source.name);
  1660. this.assignStringMetadata(target, 'artist', source.artist);
  1661. this.assignStringMetadata(target, 'album', source.album);
  1662. this.assignStringMetadata(target, 'bit_rate', source.bit_rate);
  1663. this.assignStringMetadata(target, 'duration', source.duration);
  1664. this.assignStringMetadata(target, 'sampleRate', source.sampleRate);
  1665. this.assignStringMetadata(target, 'trackCount', source.trackCount);
  1666. this.assignStringMetadata(target, 'mimeType', source.mimeType);
  1667. this.assignStringMetadata(target, 'size', source.size);
  1668. this.assignStringMetadata(target, 'pixelMapPath', source.pixelMapPath);
  1669. this.assignStringMetadata(target, 'lyricContent', source.lyricContent, true);
  1670. this.assignStringMetadata(target, 'genre', source.genre);
  1671. this.assignStringMetadata(target, 'track', source.track);
  1672. this.assignStringMetadata(target, 'bits_per_raw_sample', source.bits_per_raw_sample);
  1673. this.assignStringMetadata(target, 'channels', source.channels);
  1674. this.assignStringMetadata(target, 'channel_layout', source.channel_layout);
  1675. this.assignStringMetadata(target, 'start_time', source.start_time);
  1676. this.assignStringMetadata(target, 'year', source.year);
  1677. this.assignStringMetadata(target, 'disc', source.disc);
  1678. this.assignStringMetadata(target, 'ALBUMARTIST', source.ALBUMARTIST);
  1679. this.assignStringMetadata(target, 'COMPOSER', source.COMPOSER);
  1680. this.assignStringMetadata(target, 'LYRICIST', source.LYRICIST);
  1681. this.assignStringMetadata(target, 'COMMENT', source.COMMENT, true);
  1682. this.assignNumberMetadata(target, 'videoSize', source.videoSize);
  1683. this.assignNumberMetadata(target, 'probe_score', source.probe_score);
  1684. this.assignNumberMetadata(target, 'nb_streams', source.nb_streams);
  1685. this.assignNumberMetadata(target, 'nb_programs', source.nb_programs);
  1686. if (source.remote_rel_path && StrUtil.isEmpty(target.remote_rel_path)) {
  1687. target.remote_rel_path = source.remote_rel_path;
  1688. }
  1689. }
  1690. private async hydrateRemoteSongFromDb(item: VideoItem | undefined): Promise<void> {
  1691. if (!item || !isRemoteCloudType(item.type)) {
  1692. return;
  1693. }
  1694. const storagePath = item.remote_rel_path || WebDavUrlUtil.toStoragePath(item.filePath);
  1695. if (!storagePath) {
  1696. return;
  1697. }
  1698. try {
  1699. const cached = await this.table.queryVideoByFilePath(storagePath);
  1700. if (!cached) {
  1701. return;
  1702. }
  1703. this.mergeVideoItemFromSource(item, cached);
  1704. if (StrUtil.isEmpty(item.remote_rel_path)) {
  1705. item.remote_rel_path = storagePath;
  1706. }
  1707. if (item === this.currentSong) {
  1708. if (StrUtil.isNotEmpty(item.name)) {
  1709. this.name = item.name;
  1710. }
  1711. if (StrUtil.isNotEmpty(item.artist)) {
  1712. this.artist = item.artist!;
  1713. }
  1714. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  1715. this.cover = item.pixelMapPath!;
  1716. }
  1717. if (StrUtil.isNotEmpty(item.lyricContent) && StrUtil.isEmpty(this.lyricContent)) {
  1718. this.applyInlineLyricContent(item.lyricContent as string);
  1719. }
  1720. }
  1721. } catch (error) {
  1722. Logger.error(TAG, `hydrateRemoteSongFromDb 失败: ${(error as Error).message}`);
  1723. }
  1724. }
  1725. private applyInlineLyricContent(content: string): void {
  1726. if (StrUtil.isEmpty(content)) {
  1727. return;
  1728. }
  1729. this.lyricContent = content;
  1730. const lines = content.split('\n').map(line => line.trim());
  1731. const lyric = this.parser.parse(lines);
  1732. this.lyricController.setLyric(lyric);
  1733. this.lyricControllerXF.setLyric(lyric);
  1734. this.lyricControllerSingle.setLyric(lyric);
  1735. }
  1736. private extractParentPathFromStoragePath(path: string): string {
  1737. if (!path) {
  1738. return '';
  1739. }
  1740. const lastSlash = path.lastIndexOf('/');
  1741. if (lastSlash <= 0) {
  1742. return '';
  1743. }
  1744. return path.substring(0, lastSlash);
  1745. }
  1746. private resolveRemoteStoragePath(target: VideoItem): string | null {
  1747. if (!target || !isRemoteCloudType(target.type)) {
  1748. return null;
  1749. }
  1750. if (isWebDavType(target.type)) {
  1751. const storagePath = target.remote_rel_path || WebDavUrlUtil.toStoragePath(target.filePath);
  1752. if (storagePath) {
  1753. target.remote_rel_path = storagePath;
  1754. return storagePath;
  1755. }
  1756. return null;
  1757. }
  1758. if (target.remote_rel_path && target.remote_rel_path.length > 0) {
  1759. return target.remote_rel_path;
  1760. }
  1761. return null;
  1762. }
  1763. private async persistRemoteMetadataToDb(target: VideoItem): Promise<void> {
  1764. if (!this.context || !target || !isRemoteCloudType(target.type)) {
  1765. return;
  1766. }
  1767. const storagePath = this.resolveRemoteStoragePath(target);
  1768. if (!storagePath) {
  1769. return;
  1770. }
  1771. const table = new MediaTable(this.context);
  1772. await new Promise<void>((resolve) => {
  1773. table.getRdbStore(this.context as Context, () => resolve());
  1774. });
  1775. const cloneItem = cloneVideoItem(target);
  1776. cloneItem.filePath = storagePath;
  1777. cloneItem.remote_rel_path = storagePath;
  1778. cloneItem.parentPath = this.extractParentPathFromStoragePath(storagePath);
  1779. await table.saveOrUpdateWebDavItem(cloneItem);
  1780. }
  1781. onPageHide(): void {
  1782. this.knockController?.immersiveDisableListening();
  1783. }
  1784. @State isFirstStartPlay: boolean = false
  1785. private async startFileDeletionWatcher(): Promise<void> {
  1786. if (!this.rootPath) {
  1787. return;
  1788. }
  1789. if (!this.deletionWatcher) {
  1790. this.deletionWatcher = new FileDeletionWatcher(this.context, this.table);
  1791. }
  1792. try {
  1793. await this.deletionWatcher.watchDirectories([
  1794. this.rootPath,
  1795. this.lockPath,
  1796. this.favPath,
  1797. this.historyPath
  1798. ]);
  1799. } catch (error) {
  1800. Logger.error(TAG, `初始化文件删除监听失败: ${(error as Error).message}`);
  1801. }
  1802. }
  1803. //获取download_path
  1804. async mkDownLoadDir() {
  1805. const documentViewPicker = new picker.DocumentViewPicker()
  1806. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  1807. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  1808. PreferencesUtil.putSync('download_path', this.rootPath+'/')
  1809. this.currentPath = this.rootPath
  1810. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  1811. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  1812. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  1813. Logger.info('onecold rootPath = ' + this.rootPath)
  1814. Logger.info('onecold lockPath = ' + this.lockPath)
  1815. if (!FileUtil.accessSync(this.lockPath)) {
  1816. FileUtil.mkdirSync(this.lockPath)
  1817. }
  1818. if (!FileUtil.accessSync(this.favPath)) {
  1819. FileUtil.mkdirSync(this.favPath)
  1820. }
  1821. if (!FileUtil.accessSync(this.historyPath)) {
  1822. FileUtil.mkdirSync(this.historyPath)
  1823. }
  1824. // await this.startFileDeletionWatcher();
  1825. this.getSortedFiles(this.rootPath).then(async () => {
  1826. this.isFavMusic = false
  1827. //穿山甲
  1828. // this.loadBannerAd(CSJUtil.getBannerID())
  1829. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  1830. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  1831. if (ArrayUtil.isEmpty(this.songList)) {
  1832. this.songList = this.getCurFileList()
  1833. } else {
  1834. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  1835. }
  1836. if (ArrayUtil.isNotEmpty(this.songList)) {
  1837. this.isFirstStartPlay = true
  1838. this.sonDataSource.pushArrayData(this.songList)
  1839. if (this.currentSong === undefined) {
  1840. this.isFirstStartPlay = false
  1841. this.currentSong = this.songList[0]
  1842. }
  1843. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  1844. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  1845. context: this.context,
  1846. autoParseMusicName: this.autoParseMusicName
  1847. });
  1848. Logger.info(TAG, `WebDAV URL同步构建完成: ${this.videoUrl}`);
  1849. this.name = this.currentSong.name
  1850. this.cover = this.currentSong.pixelMapPath
  1851. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  1852. } else {
  1853. this.name = '空空如也'
  1854. }
  1855. })
  1856. this.getFavList(false)
  1857. }
  1858. getFavList(isFavRefresh: boolean) {
  1859. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  1860. this.favList = result
  1861. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  1862. this.videoLocalList = this.favList
  1863. this.updateListData(this.videoLocalList)
  1864. }
  1865. })
  1866. }
  1867. getHistoryList(isRefresh: boolean) {
  1868. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  1869. this.historyList = result
  1870. // for (let i = 0; i < this.historyList.length; i++) {
  1871. //
  1872. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  1873. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  1874. // }
  1875. if (isRefresh) {
  1876. this.videoLocalList = this.historyList
  1877. this.updateListData(this.videoLocalList, true)
  1878. }
  1879. })
  1880. }
  1881. // 组件消失生命周期
  1882. aboutToDisappear() {
  1883. console.info('LifeCycleComponent aboutToDisappear');
  1884. this.deletionWatcher?.stop();
  1885. this.knockController?.immersiveDisableListening();
  1886. this.curIndex = 0
  1887. emitter.off(EventConstants.EVENT_AUDIO_OPEN);
  1888. emitter.off(EventConstants.EVENT_SCAN_UPDATE);
  1889. emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
  1890. emitter.off(EventConstants.EVENT_SETTING_UPDATE);
  1891. this.mDestroyPage = true;
  1892. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  1893. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  1894. this.stop();
  1895. }
  1896. this.mIjkMediaPlayer.off('audioInterrupt');
  1897. this.mIjkMediaPlayer.off('deviceChange');
  1898. if (workerInstance) {
  1899. workerInstance.terminate();
  1900. }
  1901. this.stopPip();
  1902. this.destroyPipController()
  1903. this.getUIContext().getHostContext()!.eventHub.off('playOrPause');
  1904. this.getUIContext().getHostContext()!.eventHub.off('playPrevious');
  1905. this.getUIContext().getHostContext()!.eventHub.off('playNext');
  1906. this.getUIContext().getHostContext()!.eventHub.off('showPlayerView');
  1907. this.getUIContext().getHostContext()!.eventHub.off('openPlayList');
  1908. }
  1909. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean,openItem?:VideoItem) {
  1910. this.isFavMusic = false
  1911. console.info('onecold getSortedFiles 1 curPath '+curPath)
  1912. if (isWorkerPost) {
  1913. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1914. }
  1915. if (this.modeType !== 0) {
  1916. return
  1917. }
  1918. console.info('onecold getSortedFiles 2')
  1919. this.isCanBack = false
  1920. this.currentPath = curPath
  1921. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  1922. this.titleName = getFileDirName(this.currentPath,this.rootPath)
  1923. if (curPath === this.rootPath) {
  1924. this.rightTopImage = $r('sys.symbol.sort')
  1925. } else {
  1926. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  1927. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  1928. this.rightTopImage = $r('sys.symbol.chevron_left')
  1929. }
  1930. }
  1931. // Get the current file list and calculate its hash
  1932. this.fileList = FileUtil.listFileSync(curPath);
  1933. const currentHash = simpleHash(this.fileList);
  1934. // Check cache
  1935. const cachedValue = this.findCache(curPath);
  1936. Logger.info('onecold cachedValue = ' + cachedValue)
  1937. const cachedHash = this.findStringCache(curPath + '_hash');
  1938. const cachedDirList = this.findCache(curPath + "_dirList");
  1939. if (cachedValue !== undefined&&!this.isRefreshing) {
  1940. // this.videoLocalList = cachedValue;
  1941. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  1942. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  1943. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  1944. }
  1945. this.isRefreshing = false
  1946. this.updateListData(cachedValue)
  1947. }
  1948. if (cachedDirList !== undefined) {
  1949. this.dirList = cachedDirList
  1950. }
  1951. //通过当前hash值和缓存hash判断list有没有变化
  1952. if (cachedValue && cachedHash === currentHash) {
  1953. return;
  1954. }
  1955. // this.fileList = FileUtil.listFileSync(curPath)
  1956. let directories: Array<VideoItem> = [];
  1957. let files: Array<VideoItem> = [];
  1958. for (let i = 0; i < this.fileList.length; i++) {
  1959. console.info(`The name of file: ${this.fileList[i]}`);
  1960. let path = curPath + '/' + this.fileList[i]
  1961. if (FileUtil.isDirectory(path)) {
  1962. let item: VideoItem =
  1963. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  1964. '')
  1965. if (this.isShowDir(item.name)) {
  1966. directories.push(item);
  1967. }
  1968. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1969. // Utility.doSortListAscending(directories)
  1970. } else {
  1971. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  1972. let item: VideoItem =
  1973. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  1974. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  1975. files.push(item);
  1976. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1977. // this.doSortListAscending(files)
  1978. }
  1979. }
  1980. }
  1981. }
  1982. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  1983. if (this.currentPath !== this.lockPath) {
  1984. files = result;
  1985. }
  1986. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1987. Utility.doSortListAscending(files)
  1988. if (this.currentPath === this.rootPath) {
  1989. this.dirList = directories
  1990. this.addCache(curPath + "_dirList", this.dirList);
  1991. }
  1992. //插入广告先注释掉
  1993. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  1994. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  1995. // directories.push(adItem)
  1996. // }
  1997. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  1998. this.videoLocalList = directories.concat(files);
  1999. this.updateListData(this.videoLocalList)
  2000. if (ArrayUtil.isNotEmpty(files)) {
  2001. if (this.currentPath != this.rootPath) {
  2002. if (files) {
  2003. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  2004. }
  2005. }
  2006. // 缓存结果
  2007. this.addCache(curPath, this.videoLocalList);
  2008. await this.saveCacheToStorage(); // 保存缓存至本地存储
  2009. this.addStringCache(curPath + '_hash', currentHash);
  2010. }
  2011. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  2012. for (let i = 0; i < this.videoLocalList.length; i++) {
  2013. console.info(`onecold gengxin 1: ${this.videoLocalList[i].name}`);
  2014. }
  2015. // this.setButtonStatus()
  2016. this.openMusic(isOpen, destPath,openItem)
  2017. this.isRefreshing = false
  2018. });
  2019. }
  2020. //第三方app打开天天静听导入音乐后播放
  2021. openMusic(isOpen?: boolean, destPath?: string,openItem?:VideoItem){
  2022. if (isOpen&&destPath) {
  2023. if (destPath === undefined) {
  2024. // 处理 destPath 为 undefined 的情况
  2025. return
  2026. }
  2027. if (destPath.endsWith('.lrc')) {
  2028. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  2029. if (StrUtil.isNotEmpty(this.videoUrl)) {
  2030. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  2031. this.initLyric(lyricPath);
  2032. }
  2033. return
  2034. }
  2035. if(openItem){
  2036. this.doPlay(openItem,0,false,true)
  2037. // this.isShowPlay = true
  2038. this.setShowPlayTrue()
  2039. }
  2040. }
  2041. }
  2042. //扫描文件夹入库
  2043. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  2044. const files = FileUtil.listFileSync(curPath);
  2045. let mediaItems: VideoItem[] = [];
  2046. Logger.info('onecold scanDirectory start ')
  2047. for (const file of files) {
  2048. const fPath = `${curPath}/${file}`;
  2049. if (fPath === this.lockPath) {
  2050. Logger.info(`Skipping locked path: ${fPath}`);
  2051. continue;
  2052. }
  2053. if (FileUtil.isDirectory(fPath)) {
  2054. // Recursively scan subdirectories
  2055. const subDirItems = await this.scanDirectory(fPath);
  2056. mediaItems = mediaItems.concat(subDirItems);
  2057. } else {
  2058. Logger.info('onecold scanDirectory filePath = ' + fPath)
  2059. // Process media files
  2060. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  2061. let mediaItem: VideoItem =
  2062. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2063. mediaItems.push(mediaItem);
  2064. this.table.insert(mediaItem, (id: number) => {
  2065. });
  2066. }
  2067. }
  2068. }
  2069. return mediaItems;
  2070. }
  2071. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  2072. animateTo({ duration: 666 }, () => {
  2073. this.opacityItem = 0.5;
  2074. });
  2075. setTimeout(() => {
  2076. this.videoLocalList = mList;
  2077. if (!noSort) {
  2078. if (this.modeType === 0 || this.modeType === 1) {
  2079. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  2080. this.doSortType(this.sortType)
  2081. }
  2082. }
  2083. this.dataSource.pushArrayData(this.videoLocalList)
  2084. animateTo({ duration: 666 }, () => {
  2085. this.opacityItem = 1;
  2086. });
  2087. this.setButtonStatus()
  2088. //添加到字母索引表
  2089. this.setAlphaBet()
  2090. }, 200);
  2091. }
  2092. getCurFileList(): Array<VideoItem> {
  2093. if(this.isSearchMode){
  2094. return this.filteredList
  2095. }
  2096. let files: Array<VideoItem> = [];
  2097. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2098. for (let i = 0; i < this.videoLocalList.length; i++) {
  2099. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  2100. files.push(this.videoLocalList[i]);
  2101. }
  2102. }
  2103. }
  2104. return files
  2105. }
  2106. setButtonStatus() {
  2107. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2108. this.isZero = false
  2109. } else {
  2110. this.isZero = true
  2111. }
  2112. if (this.currentPath !== this.rootPath &&
  2113. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  2114. this.isHasDir = true //不为空,说明有子文件夹
  2115. } else {
  2116. this.isHasDir = false
  2117. }
  2118. }
  2119. @Builder
  2120. SortMenuBuilder() {
  2121. Menu() {
  2122. MenuItem({
  2123. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2124. content: "按艺术家升序"
  2125. })
  2126. .onClick(async () => {
  2127. this.doSortType(0)
  2128. PreferencesUtil.put(SettingPage.SORT_TYPE, 0)
  2129. this.updateListData(this.videoLocalList, true)
  2130. })
  2131. MenuItem({
  2132. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2133. content: "按艺术家降序"
  2134. })
  2135. .onClick(async () => {
  2136. this.doSortType(1)
  2137. PreferencesUtil.put(SettingPage.SORT_TYPE, 1)
  2138. this.updateListData(this.videoLocalList, true)
  2139. })
  2140. MenuItem({
  2141. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat_size_square')),
  2142. content: "按专辑升序"
  2143. })
  2144. .onClick(async () => {
  2145. this.doSortType(2)
  2146. PreferencesUtil.put(SettingPage.SORT_TYPE, 2)
  2147. this.updateListData(this.videoLocalList, true)
  2148. })
  2149. MenuItem({
  2150. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.character_arrow_clockwise')),
  2151. content: "按专辑降序"
  2152. })
  2153. .onClick(async () => {
  2154. this.doSortType(3)
  2155. PreferencesUtil.put(SettingPage.SORT_TYPE, 3)
  2156. this.updateListData(this.videoLocalList, true)
  2157. })
  2158. MenuItem({
  2159. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2160. content: $r('app.string.sort_by_name')
  2161. })
  2162. .onClick(async () => {
  2163. this.doSortType(4)
  2164. PreferencesUtil.put(SettingPage.SORT_TYPE, 4)
  2165. this.updateListData(this.videoLocalList, true)
  2166. })
  2167. MenuItem({
  2168. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2169. content: '按名称降序'
  2170. })
  2171. .onClick(async () => {
  2172. this.doSortType(5)
  2173. PreferencesUtil.put(SettingPage.SORT_TYPE, 5)
  2174. this.updateListData(this.videoLocalList, true)
  2175. })
  2176. MenuItem({
  2177. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2178. content: $r('app.string.sort_by_time')
  2179. })
  2180. .onClick(async () => {
  2181. this.doSortType(6)
  2182. PreferencesUtil.put(SettingPage.SORT_TYPE, 6)
  2183. this.updateListData(this.videoLocalList, true)
  2184. })
  2185. MenuItem({
  2186. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  2187. content: '按添加时间降序'
  2188. })
  2189. .onClick(async () => {
  2190. this.doSortType(7)
  2191. PreferencesUtil.put(SettingPage.SORT_TYPE, 7)
  2192. this.updateListData(this.videoLocalList, true)
  2193. })
  2194. }.attributeModifier(new MenuModifier())
  2195. }
  2196. @Builder
  2197. SortMenuForArtistAblumBuilder() {
  2198. Menu() {
  2199. MenuItem({
  2200. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2201. content: $r('app.string.sort_by_name')
  2202. })
  2203. .onClick(async () => {
  2204. this.doSortType(4)
  2205. // PreferencesUtil.put(SettingPage.SORT_TYPE, 2)
  2206. this.updateListData(this.videoLocalList, true)
  2207. })
  2208. MenuItem({
  2209. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2210. content: '按名称降序'
  2211. })
  2212. .onClick(async () => {
  2213. this.doSortType(5)
  2214. this.updateListData(this.videoLocalList, true)
  2215. })
  2216. MenuItem({
  2217. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2218. content: '按数量升序'
  2219. })
  2220. .onClick(async () => {
  2221. this.doSortType(8)
  2222. this.updateListData(this.videoLocalList, true)
  2223. })
  2224. MenuItem({
  2225. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  2226. content: '按数量降序'
  2227. })
  2228. .onClick(async () => {
  2229. this.doSortType(9)
  2230. this.updateListData(this.videoLocalList, true)
  2231. })
  2232. }.attributeModifier(new MenuModifier())
  2233. }
  2234. doSortType(index: number) {
  2235. switch (index) {
  2236. case 0:
  2237. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2238. // 类型排序优先级
  2239. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2240. if (typeOrder !== 0) {
  2241. return typeOrder;
  2242. }
  2243. // 处理艺术家可能为undefined的字符串比较
  2244. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  2245. const artistB = b.artist?.trim() || '';
  2246. return artistA.localeCompare(artistB);
  2247. });
  2248. break;
  2249. case 1:
  2250. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2251. // 类型排序优先级
  2252. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2253. if (typeOrder !== 0) {
  2254. return typeOrder;
  2255. }
  2256. // 处理艺术家可能为undefined的字符串比较
  2257. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  2258. const artistB = b.artist?.trim() || '';
  2259. return artistB.localeCompare(artistA);
  2260. });
  2261. break;
  2262. case 2:
  2263. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2264. // 类型排序优先级
  2265. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2266. if (typeOrder !== 0) {
  2267. return typeOrder;
  2268. }
  2269. // 处理专辑可能为undefined的字符串比较
  2270. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  2271. const albumB = b.album?.trim() || '';
  2272. return albumA.localeCompare(albumB);
  2273. });
  2274. break;
  2275. case 3:
  2276. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2277. // 类型排序优先级
  2278. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2279. if (typeOrder !== 0) {
  2280. return typeOrder;
  2281. }
  2282. // 处理专辑可能为undefined的字符串比较
  2283. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  2284. const albumB = b.album?.trim() || '';
  2285. return albumB.localeCompare(albumA);
  2286. });
  2287. break;
  2288. case 4:
  2289. Utility.doSortListAscending(this.videoLocalList,this.isShowFileName)
  2290. break;
  2291. case 5:
  2292. Utility.doSortListDescending(this.videoLocalList,this.isShowFileName)
  2293. break;
  2294. case 6:
  2295. this.videoLocalList.sort((a, b) => {
  2296. // First, sort by type
  2297. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2298. if (typeOrder !== 0) {
  2299. return typeOrder;
  2300. }
  2301. // If types are the same, sort by cTime in ascending order
  2302. return a.cTime.localeCompare(b.cTime);
  2303. });
  2304. break;
  2305. case 7:
  2306. this.videoLocalList.sort((a, b) => {
  2307. // First, sort by type
  2308. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2309. if (typeOrder !== 0) {
  2310. return typeOrder;
  2311. }
  2312. // If types are the same, sort by cTime in descending order
  2313. return b.cTime.localeCompare(a.cTime);
  2314. });
  2315. break;
  2316. case 8:
  2317. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  2318. // 1. Sort by type first
  2319. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  2320. if (typeOrder !== 0) {
  2321. return typeOrder;
  2322. }
  2323. // 2. Then sort by artist count (numeric comparison)
  2324. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  2325. if(this.modeType === 2){
  2326. sortMap = this.artistMap
  2327. }else{
  2328. sortMap = this.albumMap
  2329. }
  2330. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  2331. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  2332. return aArtistCount - bArtistCount;
  2333. });
  2334. break;
  2335. case 9:
  2336. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  2337. // 1. Sort by type first
  2338. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  2339. if (typeOrder !== 0) {
  2340. return typeOrder;
  2341. }
  2342. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  2343. if(this.modeType === 2){
  2344. sortMap = this.artistMap
  2345. }else{
  2346. sortMap = this.albumMap
  2347. }
  2348. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  2349. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  2350. return bArtistCount - aArtistCount;
  2351. });
  2352. break;
  2353. }
  2354. }
  2355. showSheelDialog() {
  2356. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  2357. // this.showTips()
  2358. // return
  2359. // }
  2360. this.showAddDialog()
  2361. }
  2362. showAddDialog() {
  2363. if (this.modeType === 2 || this.modeType === 3) {
  2364. return
  2365. }
  2366. DialogHelper.showActionSheetDialog({
  2367. title: "请选择添加方式(建议歌词文件一起导入)",
  2368. sheets: [
  2369. { value: "新建文件夹", fontColor: $r('app.color.text_color') },
  2370. { value: "手动导入", fontColor: $r('app.color.text_color') },
  2371. { value: "自动导入", fontColor: $r('app.color.text_color') },
  2372. { value: "全选导入", fontColor: $r('app.color.text_color') },
  2373. ],
  2374. maskColor: Color.Transparent,
  2375. backgroundColor: $r('app.color.bg_card'),
  2376. transition: AnimationHelper.transitionInDown(555),
  2377. onAction: (index) => {
  2378. switch (index) {
  2379. case 0:
  2380. if (this.modeType === 0) {
  2381. this.showMkDialog()
  2382. } else {
  2383. ToastUtil.showToast('请切换到首页才能新建文件夹!')
  2384. }
  2385. break;
  2386. case 1:
  2387. this.callFilePickerSelectFile()
  2388. break;
  2389. case 2:
  2390. this.showTips()
  2391. break;
  2392. case 3:
  2393. this.goSelectMusic()
  2394. break;
  2395. }
  2396. }
  2397. })
  2398. }
  2399. //拉起音频
  2400. goSelectMusic() {
  2401. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  2402. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  2403. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  2404. ) {
  2405. ToastUtil.showToast('暂时不支持该设备')
  2406. return
  2407. }
  2408. try {
  2409. let documentSelectOptions = new picker.DocumentSelectOptions();
  2410. documentSelectOptions.authMode = true
  2411. documentSelectOptions.multiAuthMode = true
  2412. if( deviceInfo.sdkApiVersion>=21){//如果api大于21 ,可以支持1w首歌以上
  2413. documentSelectOptions.maxSelectNumber = 20000
  2414. }
  2415. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  2416. let documentPicker = new picker.DocumentViewPicker(this.context);
  2417. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  2418. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  2419. this.saveVideoDatas(documentSelectResult)
  2420. }
  2421. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  2422. JSON.stringify(documentSelectResult));
  2423. }).catch((err: BusinessError) => {
  2424. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  2425. });
  2426. } catch (error) {
  2427. let err: BusinessError = error as BusinessError;
  2428. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2429. }
  2430. }
  2431. async showTips() {
  2432. try {
  2433. this.getUIContext().getPromptAction().showDialog({
  2434. title: '导入指南',
  2435. message:'用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2436. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2437. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2438. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后去文件扫描一下。\n',
  2439. buttons: [
  2440. {
  2441. text: '知道了',
  2442. color: '#000000'
  2443. },
  2444. ]
  2445. }, (err, data) => {
  2446. if (err) {
  2447. console.error('showDialog err: ' + err);
  2448. return;
  2449. }
  2450. console.info('showDialog success callback, click button: ' + data.index);
  2451. });
  2452. } catch (error) {
  2453. let message = (error as BusinessError).message;
  2454. let code = (error as BusinessError).code;
  2455. console.error(`showDialog args error code is ${code}, message is ${message}`);
  2456. };
  2457. // DialogHelper.showTipsDialog({
  2458. // title: '使用提示:自动导入教程',
  2459. //
  2460. // content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2461. // + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2462. // '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2463. // '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  2464. // onAction: (action) => {
  2465. // if (action == DialogAction.TWO) {
  2466. // PreferencesUtil.putSync('isFirstMusic', false)
  2467. // router.pushUrl({
  2468. // url: 'pages/ScanFilePage'
  2469. // });
  2470. // }
  2471. // }
  2472. // })
  2473. }
  2474. showMkDialog() {
  2475. DialogHelper.showTextInputDialog({
  2476. title: '新建歌单',
  2477. maskColor: Color.Transparent,
  2478. text: '',
  2479. transition: AnimationHelper.transitionInDown(666),
  2480. onChange: (text) => {
  2481. console.error("onChange: " + text);
  2482. },
  2483. onAction: (action, dialogId, content) => {
  2484. // ToastUtil.showToast('content = ' +content)
  2485. if (action == DialogAction.TWO) {
  2486. const newName = content
  2487. const newPath = this.currentPath + '/' + newName
  2488. FileUtil.mkdir(newPath, true).then(() => {
  2489. this.cache.delete(this.currentPath); // 删除目标路径缓存
  2490. this.getSortedFiles(this.currentPath)
  2491. }).catch((error: BusinessError) => {
  2492. console.error(error.message);
  2493. });
  2494. }
  2495. }
  2496. })
  2497. }
  2498. @State progress: number = 0;
  2499. async saveVideoDatas(uris:string[],isOpen?:boolean){
  2500. if (ArrayUtil.isEmpty(uris)) {
  2501. return;
  2502. }
  2503. console.info('onecold this.isCopyFileToDownLoad = ' + this.isCopyFileToDownLoad);
  2504. if(this.isCopyFileToDownLoad||this.currentPath==this.lockPath||isOpen){
  2505. this.saveVideoDatasToDownLoad(uris,isOpen)
  2506. return
  2507. }
  2508. // 初始化进度条
  2509. this.progress = 0;
  2510. DialogHelper.showLoadingProgress({
  2511. progress: this.progress,
  2512. backCancel: false,
  2513. autoCancel: false,
  2514. loadColor: $r('app.color.title_bar_bg'),
  2515. fontColor: $r('app.color.title_bar_bg')
  2516. });
  2517. // 计算处理总数用于进度计算
  2518. const totalItems = uris.length;
  2519. let processedItems = 0;
  2520. for (let i = 0; i < uris.length; i++) {
  2521. let filePath = uris[i];
  2522. try {
  2523. if (this.currentPath !== this.lockPath) { // 判断不是私密音乐,才入库
  2524. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2525. let mediaItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context,
  2526. filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2527. console.info('onecold saveVideoDatas filePath = ' + filePath)
  2528. if (!filePath.includes(this.rootPath)) {
  2529. console.info('onecold saveVideoDatas mediaItem.parentPath111 = ' + mediaItem.parentPath)
  2530. mediaItem.parentPath = this.currentPath;
  2531. }
  2532. console.info('onecold saveVideoDatas mediaItem.parentPath = ' + mediaItem.parentPath)
  2533. this.table.insert(mediaItem, (id: number) => {
  2534. // 插入完成回调
  2535. });
  2536. }
  2537. }
  2538. // 更新进度
  2539. processedItems++;
  2540. this.progress = Math.floor((processedItems / totalItems) * 100);
  2541. DialogHelper.updateLoading(' 正在处理', this.progress);
  2542. } catch (error) {
  2543. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2544. // 即使出错也更新进度
  2545. processedItems++;
  2546. this.progress = Math.floor((processedItems / totalItems) * 100);
  2547. DialogHelper.updateLoading(' 正在处理', this.progress);
  2548. }
  2549. }
  2550. // 关闭进度条
  2551. DialogHelper.closeLoading();
  2552. this.isZero = false
  2553. // 删除目标路径缓存
  2554. setTimeout(() => {
  2555. this.cache.delete(this.currentPath);
  2556. this.getSortedFiles(this.currentPath,false,uris[0],isOpen)
  2557. this.setButtonStatus()
  2558. }, 500);
  2559. }
  2560. async saveVideoDatasToDownLoad(uris: string[], isOpen?: boolean) {
  2561. if (ArrayUtil.isEmpty(uris)) {
  2562. return;
  2563. }
  2564. let newUris: string[] = [];
  2565. this.progress = 0
  2566. DialogHelper.showLoadingProgress({
  2567. progress: this.progress,
  2568. backCancel: false,
  2569. autoCancel: false,
  2570. loadColor: this.themeColor,
  2571. fontColor: this.themeColor
  2572. });
  2573. // 计算所有文件的总大小
  2574. let totalSize = 0;
  2575. for (let uri of uris) {
  2576. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  2577. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  2578. await fileIo.close(sourceFile.fd);
  2579. }
  2580. let totalRead = 0;
  2581. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  2582. Logger.info(TAG, 'destPath uri: ' + destPath);
  2583. for (let i = 0; i < uris.length; i++) {
  2584. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  2585. Logger.info(TAG, 'filePath uri: ' + filePath);
  2586. newUris.push(filePath);
  2587. try {
  2588. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  2589. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  2590. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  2591. const buffer = new ArrayBuffer(buffSize);
  2592. let len = await fileIo.read(sourceFile.fd, buffer);
  2593. while (len > 0) {
  2594. await fileIo.write(destFile.fd, buffer.slice(0, len));
  2595. totalRead += len;
  2596. // 计算总进度
  2597. this.progress = Math.floor((totalRead / totalSize) * 100);
  2598. DialogHelper.updateLoading('正在导入', this.progress);
  2599. len = await fileIo.read(sourceFile.fd, buffer);
  2600. }
  2601. await fileIo.close(sourceFile.fd);
  2602. await fileIo.close(destFile.fd);
  2603. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  2604. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2605. let mediaItem: VideoItem =
  2606. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2607. this.table.insert(mediaItem, (id: number) => {
  2608. // 删除目标路径缓存
  2609. this.cache.delete(this.currentPath);
  2610. this.getSortedFiles(this.currentPath, true, destPath, isOpen,mediaItem)
  2611. });
  2612. }
  2613. }
  2614. } catch (error) {
  2615. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2616. }
  2617. }
  2618. DialogHelper.closeLoading()
  2619. this.isZero = false
  2620. // setTimeout(() => {
  2621. // // 删除目标路径缓存
  2622. // this.cache.delete(this.currentPath);
  2623. // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
  2624. // }, 500);
  2625. Logger.info(TAG, 'scan select video result:' + newUris)
  2626. }
  2627. //拉起音频
  2628. // goSelectMusic(){
  2629. //
  2630. // try {
  2631. // let audioSelectOptions = new picker.AudioSelectOptions();
  2632. // let audioPicker = new picker.AudioViewPicker(this.context);
  2633. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  2634. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  2635. // this.saveVideoDatas(audioSelectResult)
  2636. // }
  2637. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  2638. // }).catch((err: BusinessError) => {
  2639. //
  2640. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  2641. // });
  2642. // } catch (error) {
  2643. // let err: BusinessError = error as BusinessError;
  2644. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2645. // }
  2646. //
  2647. //
  2648. //
  2649. // }
  2650. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  2651. if (!item) {
  2652. return undefined;
  2653. }
  2654. try {
  2655. let selectUris: Array<string> = [];
  2656. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  2657. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  2658. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  2659. photoSelectOptions.maxSelectNumber = 1;
  2660. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  2661. selectUris = photoSelectResult.photoUris;
  2662. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  2663. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  2664. console.info('file fd: ' + file.fd);
  2665. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  2666. let imagePath = this.context.filesDir + FileUtil.separator + name
  2667. imagePath = fileUri.getUriFromPath(imagePath)
  2668. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  2669. fileIo.copyFileSync(file.fd, file2.fd)
  2670. fileIo.closeSync(file);
  2671. fileIo.closeSync(file2);
  2672. if (item.filePath == this.currentSong?.filePath) {
  2673. this.cover = imagePath
  2674. }
  2675. if (item) {
  2676. item.pixelMapPath = imagePath
  2677. }
  2678. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  2679. if (success) {
  2680. this.doUpdateData()
  2681. console.log("onecold 更新音乐封面成功,数据库已同步");
  2682. } else {
  2683. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  2684. }
  2685. });
  2686. LogUtil.debug("onecold this.cover =" + this.cover)
  2687. return FileUtil.getFilePath(imagePath); // Return the image path here
  2688. } catch (err) {
  2689. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  2690. return undefined;
  2691. }
  2692. }
  2693. // 拉起picker选择文件管理器
  2694. async callFilePickerSelectFile(): Promise<void> {
  2695. try {
  2696. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  2697. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  2698. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  2699. } else {
  2700. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  2701. }
  2702. let documentPicker = new picker.DocumentViewPicker();
  2703. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  2704. Logger.info(TAG,
  2705. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  2706. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  2707. this.saveVideoDatas(DocumentSelectResult)
  2708. }
  2709. }).catch((err: BusinessError) => {
  2710. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  2711. });
  2712. } catch (err) {
  2713. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  2714. }
  2715. }
  2716. //重命名的对话框
  2717. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  2718. if(!item.filePath.includes(this.packName)){
  2719. ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限重命名')
  2720. return
  2721. }
  2722. DialogHelper.showTextInputDialog({
  2723. title: '重命名',
  2724. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  2725. maskColor: Color.Transparent,
  2726. backgroundColor: Color.Grey,
  2727. transition: AnimationHelper.transitionInDown(666),
  2728. onChange: (text) => {
  2729. console.error("onChange: " + text);
  2730. },
  2731. onAction: (action, dialogId, content) => {
  2732. // ToastUtil.showToast('content = ' +content)
  2733. if (action == DialogAction.TWO) {
  2734. const newName = content
  2735. const newPath = this.currentPath + '/' + newName
  2736. console.log("onecold item = " + item.type);
  2737. this.doReName(index, newName, filePath, newPath, item)
  2738. }
  2739. }
  2740. })
  2741. }
  2742. //剪切 移动到另个文件夹的对话框
  2743. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2744. Logger.info('onecold showCutDialog')
  2745. let mList: Array<string> = []
  2746. let rPath = this.rootPath
  2747. if (isCurrent) {
  2748. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2749. rPath = this.currentPath
  2750. } else {
  2751. mList = Utility.getNameList(this.dirList);
  2752. rPath = this.rootPath
  2753. }
  2754. let dataBean = new BubbleBean()
  2755. dataBean.data = mList
  2756. dataBean.color = this.themeColor
  2757. dataBean.onItemClick = (i) => {
  2758. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2759. Logger.info('newPath = ' + newPath)
  2760. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  2761. ToastUtil.showToast('移动成功')
  2762. this.table.deleteData(item, () => {
  2763. });
  2764. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2765. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2766. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2767. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2768. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2769. this.table.insert(newItem, (id: number) => {
  2770. //加入数据库
  2771. });
  2772. }
  2773. this.cache.delete(this.currentPath); // 删除原路径缓存
  2774. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2775. this.getSortedFiles(this.currentPath, true)
  2776. }).catch((error: BusinessError) => {
  2777. console.error(error.message);
  2778. });
  2779. XPopup.dismissTop()
  2780. }
  2781. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2782. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2783. popupPosition = PopupPosition.TOP
  2784. }
  2785. if (index <= 3) {
  2786. popupPosition = PopupPosition.BOTTOM
  2787. }
  2788. let pup: XPopup
  2789. if (this.isDarkMode) {
  2790. pup = XPopup.Builder()
  2791. .setPopupPosition(popupPosition)
  2792. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  2793. .setBackgroundColor(Color.Black)
  2794. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2795. .show()
  2796. } else {
  2797. pup = XPopup.Builder()
  2798. .setPopupPosition(popupPosition)
  2799. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  2800. .setBackgroundColor(Color.White)
  2801. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2802. .show()
  2803. }
  2804. }
  2805. //复制 到另个文件夹的对话框
  2806. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2807. Logger.info('onecoldv showCopyDialog')
  2808. let mList: Array<string> = []
  2809. let rPath = this.rootPath
  2810. if (isCurrent) {
  2811. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2812. rPath = this.currentPath
  2813. } else {
  2814. mList = Utility.getNameList(this.dirList);
  2815. rPath = this.rootPath
  2816. }
  2817. let dataBean = new BubbleBean()
  2818. dataBean.data = mList
  2819. dataBean.isCopy = true
  2820. dataBean.color = this.themeColor
  2821. dataBean.onItemClick = (i) => {
  2822. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2823. Logger.info('newPath = ' + newPath)
  2824. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2825. ToastUtil.showToast('复制成功')
  2826. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2827. this.getSortedFiles(this.currentPath)
  2828. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2829. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2830. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2831. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2832. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2833. this.table.insert(newItem, (id: number) => {
  2834. //加入数据库
  2835. });
  2836. }
  2837. }).catch((error: BusinessError) => {
  2838. console.error(error.message);
  2839. });
  2840. XPopup.dismissTop()
  2841. }
  2842. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2843. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2844. popupPosition = PopupPosition.TOP
  2845. }
  2846. if (index <= 3) {
  2847. popupPosition = PopupPosition.BOTTOM
  2848. }
  2849. let pup: XPopup
  2850. if (this.isDarkMode) {
  2851. pup = XPopup.Builder()
  2852. .setPopupPosition(popupPosition)
  2853. .atView(id)
  2854. .setMaxHeight('60%')
  2855. .setBackgroundColor(Color.Black)
  2856. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2857. .show();
  2858. } else {
  2859. pup = XPopup.Builder()
  2860. .setPopupPosition(popupPosition)
  2861. .atView(id)
  2862. .setMaxHeight('60%')
  2863. .setBackgroundColor(Color.White)
  2864. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2865. .show();
  2866. }
  2867. }
  2868. //重命名索引index的视频
  2869. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  2870. FileUtil.rename(oldPath, newPath).then(async () => {
  2871. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2872. if (info.type === CommonConstants.TYPE_IS_DIR) {
  2873. //如果是文件夹先删除源数据,再添加新数据
  2874. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  2875. if (success) {
  2876. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  2877. } else {
  2878. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  2879. }
  2880. });
  2881. this.scanDirectory(newPath)
  2882. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  2883. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  2884. if (success) {
  2885. console.log(" onecold 重命名成功,数据库已同步");
  2886. } else {
  2887. console.error(" onecold 重命名数据库失败原因: " + error);
  2888. }
  2889. });
  2890. }
  2891. let mediaItem: VideoItem =
  2892. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2893. this.videoLocalList[index] = mediaItem;
  2894. }
  2895. this.cache.delete(this.currentPath)
  2896. this.getSortedFiles(this.currentPath, true)
  2897. }).catch((error: BusinessError) => {
  2898. console.error(error.message);
  2899. });
  2900. }
  2901. build() {
  2902. Stack() {
  2903. this.ContentBuild()
  2904. Stack() {
  2905. Column()
  2906. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  2907. height: '95%',
  2908. dragBar: true,
  2909. showClose: true,
  2910. blurStyle: BlurStyle.Thin,
  2911. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  2912. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  2913. title: {
  2914. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  2915. + `(${this.songList.length}首)`
  2916. }
  2917. })
  2918. }
  2919. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  2920. modalTransition: ModalTransition.DEFAULT,
  2921. onWillDisappear: () => {
  2922. this.setShowPlayFalse()
  2923. },
  2924. })
  2925. }
  2926. .alignContent(Alignment.Bottom)
  2927. .width('100%')
  2928. .height('100%')
  2929. }
  2930. @Builder
  2931. ContentBuild() {
  2932. Scroll() {
  2933. Column() {
  2934. Stack() {
  2935. //libraryname加上去后onKeyEvent监听不了,因为目前的解决方案是上面的XComponent,去掉libraryname
  2936. XComponent({ id: 'for_onKeyEvent',type: XComponentType.SURFACE,
  2937. controller: this.xcomponentController })
  2938. .onLoad(async (event?: object) => {
  2939. })
  2940. .focusable(true)
  2941. .height(0)
  2942. .focusOnTouch(true)
  2943. .defaultFocus(true) // 自动获取键盘焦点
  2944. .onKeyEvent((event?: KeyEvent) => {
  2945. console.info('onecold点击 onKeyEvent')
  2946. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  2947. if (!event || event.type !== KeyType.Down) {
  2948. return;
  2949. }
  2950. console.info('onecold点击 onKeyEvent event.keyCode: ' + event.keyCode)
  2951. //空格键 Space key controls pause/play
  2952. if (event.keyCode === KeyCode.KEYCODE_SPACE|| event.keyCode === KeyCode.KEYCODE_MEDIA_PLAY_PAUSE) {
  2953. this.playOrPause()
  2954. }
  2955. if (event.keyCode === KeyCode.KEYCODE_DPAD_UP) {
  2956. this.playPrevious()
  2957. }
  2958. if (event.keyCode === KeyCode.KEYCODE_DPAD_DOWN) {
  2959. this.playNext()
  2960. }
  2961. // Right-click to fast forward
  2962. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  2963. this.fastForward()
  2964. }
  2965. // Left-click to rewind
  2966. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  2967. this.backForward()
  2968. }
  2969. })
  2970. Column() {
  2971. XComponent({
  2972. id: 'xcomponentId',
  2973. type: 'surface',
  2974. libraryname: 'ijkplayer_napi',
  2975. controller: this.xcomponentController
  2976. })
  2977. .onLoad((event?: object) => {
  2978. if (!!event) {
  2979. this.initDelayPlay(event);
  2980. }
  2981. })
  2982. .onDestroy(() => {
  2983. })
  2984. .width('100%')// .width(this.videoWidth)
  2985. .aspectRatio(this.videoAspectRatio)
  2986. }
  2987. .aspectRatio(this.videoAspectRatio)
  2988. .justifyContent(FlexAlign.Center)
  2989. .backgroundColor(Color.Transparent)
  2990. .visibility(Visibility.Hidden)
  2991. .height(CommonConstants.FULL_PERCENT)
  2992. .width(CommonConstants.FULL_PERCENT)
  2993. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  2994. height:this.isLandscape?'80%': '43%',
  2995. dragBar: true,
  2996. showClose: true,
  2997. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  2998. blurStyle:BlurStyle.Thin,
  2999. backgroundColor:Color.Transparent,
  3000. title: { title: 'AB循环' }
  3001. })
  3002. Stack() {
  3003. Column() {
  3004. if(this.twoFingerType==4){
  3005. this.getWaterView()
  3006. }else{
  3007. if(this.isGridMusic){
  3008. this.getGridView()
  3009. }else {
  3010. this.getList()
  3011. }
  3012. }
  3013. if (this.modeType ==0||this.modeType==4) {
  3014. Column() {
  3015. emptyView(this.themeColor)
  3016. }
  3017. .onClick(()=>{
  3018. this.asyncCurrentPathOnlyFile()
  3019. })
  3020. .position({ top: 200 })
  3021. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  3022. .animation({ duration: 500 }),
  3023. TransitionEffect.scale({ x: 0, y: 0 })))
  3024. .justifyContent(FlexAlign.Center)
  3025. .opacity(this.isZero ? 1 : 0)
  3026. .visibility(this.isZero && !this.isFavMusic && !this.isHistory
  3027. ? Visibility.Visible : Visibility.None)
  3028. .animation({
  3029. duration: 500,
  3030. curve: Curve.Friction // 可选动画曲线
  3031. })
  3032. .width('100%')
  3033. }
  3034. }
  3035. .layoutWeight(1)
  3036. .height('100%')
  3037. // 右侧居中的字母表索引
  3038. this.indexBuilder()
  3039. this.topTitleBar()
  3040. }
  3041. .alignContent(Alignment.Top)
  3042. .layoutWeight(1)
  3043. .height('100%')
  3044. Row() {
  3045. Button(this.isAllSelected ? '反选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  3046. .width(45)
  3047. .height(45)
  3048. .fontSize(10)
  3049. .margin({ top: 10, bottom: 10, right: 6 })
  3050. .backgroundColor(this.themeColor)
  3051. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3052. .onClick(() => {
  3053. if (this.isAllSelected) {
  3054. // 全不选
  3055. this.selectedFiles = [];
  3056. } else {
  3057. // 全选
  3058. this.selectedFiles = [...this.getCurFileList()];
  3059. }
  3060. this.isAllSelected = !this.isAllSelected;
  3061. })
  3062. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  3063. .width(72)
  3064. .height(45)
  3065. .fontSize(10)
  3066. .margin({ top: 10, bottom: 10, right: 6 })
  3067. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3068. .backgroundColor(this.themeColor)
  3069. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  3070. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3071. })
  3072. .onClick(() => {
  3073. // if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  3074. this.isOneKeyTags = !this.isOneKeyTags
  3075. // }else{
  3076. // ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限批量内嵌标签,导入的时候请勾选复制一份。')
  3077. // }
  3078. })
  3079. Button('合并', { type: ButtonType.Circle, stateEffect: true })
  3080. .width(45)
  3081. .height(45)
  3082. .fontSize(10)
  3083. .margin({ top: 10, bottom: 10, right: 6 })
  3084. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3085. .backgroundColor(this.themeColor)
  3086. .bindContentCover($$this.isMergeAudio, this.MergeAudioBuilder(), {
  3087. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3088. })
  3089. .onClick(() => {
  3090. if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  3091. this.isMergeAudio = !this.isMergeAudio
  3092. }else{
  3093. ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限合并')
  3094. }
  3095. })
  3096. Button('+歌单', { type: ButtonType.Circle, stateEffect: true })
  3097. .width(45)
  3098. .height(45)
  3099. .fontSize(10)
  3100. .margin({ top: 10, bottom: 10, right: 6 })
  3101. .backgroundColor(this.themeColor)
  3102. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3103. .onClick(async () => {
  3104. this.longItemFilePath = ''
  3105. await this.openAddToPlaylistDialog(this.selectedFiles)
  3106. })
  3107. // Button('乱码', { type: ButtonType.Circle, stateEffect: true })
  3108. // .width(45)
  3109. // .height(45)
  3110. // .fontSize(10)
  3111. // .margin({ top: 10, bottom: 10, right: 6 })
  3112. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3113. // .backgroundColor(this.themeColor)
  3114. // .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  3115. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3116. // })
  3117. // .onClick(() => {
  3118. // this.isFixMessy = !this.isFixMessy
  3119. // })
  3120. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  3121. // .width('35%')
  3122. // .height(60)
  3123. // .id('music_cut')
  3124. // .margin({ top: 10, bottom: 10, right: 6 })
  3125. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3126. // .backgroundColor(this.themeColor)
  3127. // .onClick(() => {
  3128. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  3129. // })
  3130. //
  3131. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  3132. // .width('35%')
  3133. // .height(60)
  3134. // .id('music_cut_current')
  3135. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  3136. // .margin({ top: 10, bottom: 10, right: 6 })
  3137. // .backgroundColor(this.themeColor)
  3138. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3139. // .onClick(() => {
  3140. //
  3141. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  3142. // })
  3143. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  3144. // .width('35%')
  3145. // .height(60)
  3146. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  3147. // .margin({ top: 10, bottom: 10, right: 6 })
  3148. // .backgroundColor(this.themeColor)
  3149. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3150. // .onClick(() => {
  3151. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  3152. // })
  3153. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  3154. .width(45)
  3155. .height(45)
  3156. .fontSize(10)
  3157. .margin({ top: 10, bottom: 10, right: 6 })
  3158. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  3159. .backgroundColor(this.themeColor)
  3160. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3161. .onClick(() => {
  3162. this.showWarnIsDelete()
  3163. })
  3164. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  3165. .width(45)
  3166. .height(45)
  3167. .fontSize(10)
  3168. .margin({ top: 10, bottom: 10, right: 6 })
  3169. .backgroundColor(this.themeColor)
  3170. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3171. .onClick(() => {
  3172. this.selectedFiles = [];
  3173. this.isAllSelected = false
  3174. this.isMultiSelect = false
  3175. })
  3176. }
  3177. .width('100%')
  3178. .justifyContent(FlexAlign.Center)
  3179. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  3180. .opacity(this.isMultiSelect ? 1 : 0)
  3181. .animation({
  3182. duration: 666,
  3183. curve: 'ease-in-out' // 可选动画曲线
  3184. })
  3185. .position({ bottom: 20 }) // 将 Row 固定在底部
  3186. }
  3187. .width('100%')
  3188. .height('100%')
  3189. .alignContent(Alignment.Top)
  3190. }
  3191. .width('100%')
  3192. .height('100%')
  3193. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  3194. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  3195. .backgroundImagePosition(Alignment.Center)
  3196. .backdropBlur(this.blurValue)
  3197. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  3198. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  3199. }
  3200. }
  3201. //字母表索引
  3202. @Builder
  3203. indexBuilder(){
  3204. if(this.enableShowAlphabet){
  3205. Column({space: 5}){
  3206. if(this.isShowAlphaBet){
  3207. AlphabetIndexer({arrayValue: this.alphaBet,selected: this.selectAlphaBetIndex})
  3208. .attributeModifier(this.alphaBetStyle)
  3209. .usingPopup(this.isTouchingAlphaBet)
  3210. .onAreaChange((old_value,new_value)=>{
  3211. this.alphabetHeight = new_value.height as number
  3212. })
  3213. .popupPosition({
  3214. x: 40,
  3215. y: this.alphabetHeight / 2
  3216. })
  3217. .onSelect((index: number) => {
  3218. this.onSelectIndexItem(this.alphaBet[index])
  3219. })
  3220. .onTouch((event: TouchEvent) =>{
  3221. this.isShowAlphaBet = true
  3222. if(event.type === TouchType.Up || event.type === TouchType.Cancel){
  3223. this.isTouchingAlphaBet = false
  3224. }else{
  3225. this.isTouchingAlphaBet = true
  3226. }
  3227. })
  3228. .transition(
  3229. TransitionEffect.translate({x: 10})
  3230. .combine(TransitionEffect.opacity(0.1))
  3231. .animation({
  3232. duration: 150,
  3233. curve: Curve.EaseInOut,
  3234. })
  3235. )
  3236. }else{
  3237. Blank()
  3238. .layoutWeight(1)
  3239. }
  3240. // ListLocateButton()
  3241. // .onClick(() =>{
  3242. // this.locateSong()
  3243. // })
  3244. // .clickEffect({level:ClickEffectLevel.LIGHT,scale: 0.5})
  3245. // .margin({
  3246. // bottom: 10
  3247. // })
  3248. }
  3249. .padding({
  3250. bottom: 0
  3251. })
  3252. .position({x:'92%'})
  3253. .height('100%')
  3254. .justifyContent(FlexAlign.Center)
  3255. }
  3256. }
  3257. onSelectIndexItem(letter: string) {
  3258. let songs = this.videoLocalList
  3259. let targetIndex = -1;
  3260. for (let i = 0; i < songs.length; i++) {
  3261. let song = songs[i]
  3262. let text = this.isShowFileName?song.fileName:
  3263. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  3264. if(this.sortType === 0||this.sortType==1){
  3265. text = song.artist
  3266. }else if(this.sortType === 2||this.sortType==3){
  3267. text = song.album
  3268. }
  3269. if(text){
  3270. let firstPinyin = getFirstLetter(text)
  3271. if (firstPinyin&&firstPinyin === letter) {
  3272. targetIndex = i;
  3273. break;
  3274. }
  3275. }
  3276. }
  3277. if (targetIndex !== -1) {
  3278. this.listScroller.scrollToIndex(targetIndex);
  3279. }
  3280. }
  3281. // 找到对应字母表的索引
  3282. findAlphaBetIndex(song: VideoItem):number{
  3283. let text = this.isShowFileName?song.fileName:
  3284. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  3285. if(this.sortType === 0||this.sortType==1){
  3286. text = song.artist
  3287. }else if(this.sortType === 2||this.sortType==3){
  3288. text = song.album
  3289. }
  3290. if(text){
  3291. let firstLetter = getFirstLetter(text)
  3292. for(let i=0;i<this.alphaBet.length;i++){
  3293. if(this.alphaBet[i] === firstLetter){
  3294. return i
  3295. }
  3296. }
  3297. }
  3298. return 0
  3299. }
  3300. async setAlphaBet(){
  3301. return new Promise<void>((resolve,reject) => {
  3302. try {
  3303. let songs = this.videoLocalList
  3304. if(songs.length > 40000){
  3305. this.alphaBet = []
  3306. resolve()
  3307. return
  3308. }
  3309. let alphabetSet = new Set<string>();
  3310. for (let song of songs) {
  3311. let text = this.isShowFileName?song.fileName:
  3312. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  3313. if(this.sortType === 0||this.sortType==1){
  3314. text = song.artist
  3315. }else if(this.sortType === 2||this.sortType==3){
  3316. text = song.album
  3317. }
  3318. if(text){
  3319. let firstPinyin = getFirstLetter(text)
  3320. if(!alphabetSet.has(firstPinyin)){
  3321. alphabetSet.add(firstPinyin)
  3322. }
  3323. }
  3324. // const pyStr = song.pyStr
  3325. // if(pyStr){
  3326. // if(!alphabetSet.has(pyStr)){
  3327. // alphabetSet.add(pyStr)
  3328. // }
  3329. // }
  3330. }
  3331. this.alphaBet = Array.from(alphabetSet).sort((a,b)=>{
  3332. if(this.sortType ===4||this.sortType==0||this.sortType==2||this.sortType==6){
  3333. return a.localeCompare(b)
  3334. }else{
  3335. return b.localeCompare(a)
  3336. }
  3337. })
  3338. if(this.videoLocalList.length > 0){
  3339. this.listScroller.scrollToIndex(0)
  3340. this.selectAlphaBetIndex = 0
  3341. }
  3342. resolve()
  3343. }catch (e) {
  3344. console.error('testTag','排序字母表出错',JSON.stringify(e))
  3345. resolve()
  3346. }
  3347. })
  3348. }
  3349. @Builder
  3350. topTitleBar(){
  3351. Column() {
  3352. Row({ space: 15 }) {
  3353. if (!this.isSearchMode ) {
  3354. //左侧滑动按钮
  3355. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3356. SymbolGlyph(this.rightTopImage)
  3357. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3358. }
  3359. .attributeModifier(new ButtonFancyModifier(40, 40))
  3360. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3361. .animation({ duration: 300, curve: Curve.Ease })
  3362. .onClick(() => {
  3363. this.doSwipBack()
  3364. })
  3365. .attributeModifier(new ShadowModifier())
  3366. .zIndex(0)
  3367. }else{
  3368. //左侧搜索返回按钮
  3369. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3370. SymbolGlyph($r('sys.symbol.chevron_left'))
  3371. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3372. }
  3373. .attributeModifier(new ButtonFancyModifier(40, 40))
  3374. .margin({bottom:5})
  3375. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3376. .animation({ duration: 300, curve: Curve.Ease })
  3377. .onClick(() => {
  3378. this.isSearchMode = false
  3379. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  3380. this.searchText = ''
  3381. this.getSortedFiles(this.currentPath)
  3382. return
  3383. }
  3384. this.onSearchInput('')
  3385. })
  3386. .attributeModifier(new ShadowModifier())
  3387. .zIndex(0)
  3388. }
  3389. if (!this.isSearchMode) {
  3390. Text(this.titleName)
  3391. .margin({left:3,right:10})
  3392. .fontColor($r('app.color.text_color'))
  3393. .fontSize(this.twoFingerType==3?19:this.twoFingerType==2?17:15)
  3394. .maxLines(1)
  3395. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3396. .layoutWeight(1)
  3397. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3398. }
  3399. //搜索框
  3400. Search({ controller: this.searchController,value: this.searchText, placeholder: '搜索标题、艺术家...' })
  3401. .searchButton('搜索',{fontColor:this.themeColor})
  3402. .searchIcon({
  3403. src: $r('sys.media.ohos_ic_public_search_filled')
  3404. })
  3405. .cancelButton({
  3406. style: CancelButtonStyle.CONSTANT,
  3407. icon: {
  3408. src: $r('sys.media.ohos_ic_public_cancel_filled')
  3409. }
  3410. })
  3411. .layoutWeight(1)
  3412. .height(40)
  3413. .maxLength(20)
  3414. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  3415. .placeholderColor(Color.Grey)
  3416. .placeholderFont({ size: 14, weight: 400 })
  3417. .textFont({ size: 14, weight: 400 })
  3418. .onSubmit((value: string) => {
  3419. console.log('onecold onSubmit ='+value)
  3420. this.searchController.stopEditing()
  3421. this.onSearchInput(this.searchText);
  3422. })
  3423. .onChange((value: string) => {
  3424. console.log('onecold onChange ='+value)
  3425. this.onSearchInput(value);
  3426. })
  3427. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  3428. .animation({ duration: 300, curve: Curve.Ease })
  3429. //搜索按钮
  3430. if (!this.isSearchMode) {
  3431. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3432. SymbolGlyph($r('sys.symbol.magnifyingglass'))
  3433. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3434. }
  3435. .attributeModifier(new ButtonFancyModifier(40, 40))
  3436. .animation({ duration: 300, curve: Curve.Ease })
  3437. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3438. .attributeModifier(new ShadowModifier())
  3439. .zIndex(0)
  3440. .onClick(()=>{
  3441. this.isSearchMode = true
  3442. })
  3443. //排序按钮
  3444. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3445. SymbolGlyph($r('sys.symbol.list_number'))
  3446. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3447. }
  3448. .attributeModifier(new ButtonFancyModifier(40, 40))
  3449. .animation({ duration: 300, curve: Curve.Ease })
  3450. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3451. .bindMenu((this.modeType==2&&!this.isCanBack)||(this.modeType==3&&!this.isCanBack)
  3452. ?this.SortMenuForArtistAblumBuilder:this.SortMenuBuilder)
  3453. .attributeModifier(new ShadowModifier())
  3454. .zIndex(0)
  3455. //添加按钮
  3456. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3457. SymbolGlyph($r('sys.symbol.plus'))
  3458. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3459. }
  3460. .attributeModifier(new ButtonFancyModifier(40, 40))
  3461. .animation({ duration: 300, curve: Curve.Ease })
  3462. .visibility(this.modeType==0||this.modeType==1?Visibility.Visible:Visibility.None)
  3463. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3464. .bindSheet($$this.showAddSheet, this.addSheet(), {
  3465. height: SheetSize.FIT_CONTENT,
  3466. dragBar: true,
  3467. showClose: true,
  3468. preferType: SheetType.CENTER ,
  3469. title: {
  3470. title: '导入音乐'
  3471. }
  3472. })
  3473. .onClick(() => {
  3474. this.showAddSheet = !this.showAddSheet;
  3475. })
  3476. .attributeModifier(new ShadowModifier())
  3477. .zIndex(0)
  3478. }
  3479. }
  3480. }
  3481. .padding({ top: this.topSafeHeight+10, left: 10, right: 10 })
  3482. .width('100%')
  3483. .visibility(this.isShowTitleBar?Visibility.Visible:
  3484. this.autoHideTitle?Visibility.None:Visibility.Visible)
  3485. .animation({
  3486. duration: 500,
  3487. curve: Curve.Friction // 可选动画曲线
  3488. })
  3489. }
  3490. @Builder
  3491. addSheet() {
  3492. Scroll() {
  3493. Column() {
  3494. Column() {
  3495. Row() {
  3496. Text('导入音乐复制到DownLoad目录')
  3497. .margin({ left: 18 })
  3498. .fontSize(14)
  3499. .fontColor($r('app.color.text_color'))
  3500. .fontWeight(480)
  3501. .layoutWeight(1)
  3502. Toggle({ type: ToggleType.Switch, isOn: this.isCopyFileToDownLoad })
  3503. .selectedColor(this.themeColor)
  3504. .switchPointColor(Color.White)
  3505. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  3506. .margin({ right: 18 })
  3507. .onChange((checked: boolean) => {
  3508. this.isCopyFileToDownLoad = checked;
  3509. PreferencesUtil.put(SettingPage.IS_COPYFILE_TO_DOWNLOAD, this.isCopyFileToDownLoad)
  3510. })
  3511. .width(50)
  3512. .height(30);
  3513. }
  3514. .height(88)
  3515. }
  3516. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3517. .backgroundColor($r('app.color.start_window_background'))
  3518. .borderRadius(15)
  3519. .margin({
  3520. left: 30,
  3521. right: 30,
  3522. top: 10,
  3523. bottom: 10
  3524. })
  3525. .padding(0)
  3526. .border({
  3527. color: Color.White,
  3528. width: 1.8
  3529. })
  3530. Menu() {
  3531. MenuItem({
  3532. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder_badge_plus')),
  3533. content: "新建文件夹"
  3534. })
  3535. .backgroundColor($r('app.color.silvery'))
  3536. .border({
  3537. width: { bottom: 1 },
  3538. color: '#12ec5c87'
  3539. })
  3540. .margin(10)
  3541. .padding({left:15,right:15})
  3542. .onClick(async () => {
  3543. this.showMkDialog()
  3544. this.showAddSheet = !this.showAddSheet
  3545. })
  3546. MenuItem({
  3547. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder')),
  3548. content: $r('app.string.import_from_files')
  3549. })
  3550. .padding({left:15,right:15})
  3551. .backgroundColor($r('app.color.silvery'))
  3552. .border({
  3553. width: { bottom: 1 },
  3554. color: '#12ec5c87'
  3555. })
  3556. .margin(10)
  3557. .onClick(async () => {
  3558. this.callFilePickerSelectFile()
  3559. this.showAddSheet = !this.showAddSheet
  3560. })
  3561. MenuItem({
  3562. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square')),
  3563. content: '全选导入'
  3564. // content: '从下载文件夹导入(路径:Download/' +
  3565. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  3566. })
  3567. .padding({left:15,right:15})
  3568. .backgroundColor($r('app.color.silvery'))
  3569. .border({
  3570. width: { bottom: 1 },
  3571. color: '#12ec5c87'
  3572. })
  3573. .margin(10)
  3574. .onClick(async () => {
  3575. this.goSelectMusic()
  3576. this.showAddSheet = !this.showAddSheet
  3577. })
  3578. MenuItem({
  3579. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.save')),
  3580. content: '自动导入教程'
  3581. // content: '从下载文件夹导入(路径:Download/' +
  3582. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  3583. })
  3584. .padding({left:15,right:15})
  3585. .backgroundColor($r('app.color.silvery'))
  3586. .border({
  3587. width: { bottom: 1 },
  3588. color: '#12ec5c87'
  3589. })
  3590. .margin(10)
  3591. .onClick(async () => {
  3592. this.showTips()
  3593. this.showAddSheet = !this.showAddSheet
  3594. })
  3595. }.attributeModifier(new MenuModifier())
  3596. .margin({bottom:30})
  3597. }
  3598. .layoutWeight(1)
  3599. }
  3600. }
  3601. @Builder
  3602. TagsContentCoverBuilder() {
  3603. Scroll() {
  3604. Column() {
  3605. TagsContentCover(
  3606. {
  3607. selectedFiles:this.selectedFiles,
  3608. isOneKeyTags:this.isOneKeyTags,
  3609. onSeePath:(path:string)=>{
  3610. this.modeType = 0
  3611. this.deleteCache(path)
  3612. this.getSortedFiles(path)
  3613. },
  3614. onTagsResult:(result: boolean,deleteCache_path?:string)=>{
  3615. this.isMultiSelect = false
  3616. if(result){//如果嵌入成功,更新数据
  3617. this.listRefreshKey++
  3618. setTimeout(()=>{
  3619. this.doUpdateData()
  3620. },500)
  3621. }
  3622. console.info('onecold onTagsResult deleteCache_path =' +deleteCache_path)
  3623. if(deleteCache_path){
  3624. this.deleteCache(deleteCache_path)
  3625. }
  3626. }
  3627. }
  3628. )
  3629. }
  3630. }
  3631. .width('100%')
  3632. .height('100%')
  3633. }
  3634. @Builder
  3635. FixMessyViewBuilder() {
  3636. Scroll() {
  3637. Column() {
  3638. FixMessyView(
  3639. {
  3640. selectedFiles:this.selectedFiles,
  3641. isFixMessy:this.isFixMessy,
  3642. onFixResult:(result: boolean)=>{
  3643. this.isMultiSelect = false
  3644. if(result){//如果嵌入成功,更新数据
  3645. this.deleteCache(this.currentPath)
  3646. this.doUpdateData()
  3647. }
  3648. }
  3649. }
  3650. )
  3651. }
  3652. }
  3653. .width('100%')
  3654. .height('100%')
  3655. }
  3656. //剪辑音频
  3657. @Builder
  3658. EditAudioBuilder(item:VideoItem) {
  3659. Scroll() {
  3660. Column() {
  3661. EditAudio(
  3662. {
  3663. mVideoItem:item,
  3664. currentPath:this.currentPath,
  3665. videoUrl:this.videoUrl,
  3666. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3667. currentTime:this.currentTime,
  3668. progressValue:this.progressValue,
  3669. onBack:()=>{
  3670. this.isEditAudio = !this.isEditAudio
  3671. },
  3672. onSeeOutputPath:(outPutPath:string)=>{
  3673. this.isEditAudio = !this.isEditAudio
  3674. this.longItemFilePath = ''
  3675. this.modeType = 0
  3676. this.isShowFileName = true
  3677. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3678. },
  3679. onPlayOrPause:()=>{
  3680. if(this.videoUrl==item.filePath){
  3681. this.playOrPause()
  3682. }else{//如果不是当前播放的,则播放该文件
  3683. this.videoUrl==item.filePath
  3684. this.doPlay(item,0,false,true)
  3685. }
  3686. },
  3687. onSliderChange:(value:number)=>{
  3688. if(this.videoUrl!=item.filePath){
  3689. this.videoUrl==item.filePath
  3690. return
  3691. }
  3692. this.isSeekTo = true;
  3693. this.mDestroyPage = false;
  3694. this.showLoadIng();
  3695. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  3696. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3697. this.seekTo(seekValue + "");
  3698. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  3699. this.isSeekTo = false;
  3700. },
  3701. onResult:(result: boolean,outPath:string)=>{
  3702. if(result){//如果剪辑成功,更新数据
  3703. this.doUpdateData()
  3704. }else{
  3705. ToastUtil.showToast('剪辑失败')
  3706. }
  3707. }
  3708. }
  3709. )
  3710. }
  3711. }
  3712. .width('100%')
  3713. .height('100%')
  3714. }
  3715. //提取伴奏
  3716. @Builder
  3717. ConverterBuilder(item:VideoItem) {
  3718. Scroll() {
  3719. Column() {
  3720. AudioFormatConverter(
  3721. {
  3722. mVideoItem:item,
  3723. videoUrl:this.videoUrl,
  3724. currentPath:this.currentPath,
  3725. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3726. currentTime:this.currentTime,
  3727. progressValue:this.progressValue,
  3728. onBack:()=>{
  3729. this.isConverter = !this.isConverter
  3730. this.longItemFilePath = ''
  3731. },
  3732. onPlayOrPause:()=>{
  3733. if(this.videoUrl==item.filePath){
  3734. this.playOrPause()
  3735. }else{//如果不是当前播放的,则播放该文件
  3736. this.videoUrl==item.filePath
  3737. this.doPlay(item,0,false,true)
  3738. }
  3739. },
  3740. onSeeOutputPath:(outPutPath:string)=>{
  3741. this.isConverter = !this.isConverter
  3742. this.longItemFilePath = ''
  3743. this.modeType = 0
  3744. this.isShowFileName = true
  3745. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3746. },
  3747. onSliderChange:(value:number)=>{
  3748. if(this.videoUrl!=item.filePath){
  3749. this.videoUrl==item.filePath
  3750. return
  3751. }
  3752. this.isSeekTo = true;
  3753. this.mDestroyPage = false;
  3754. this.showLoadIng();
  3755. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3756. this.seekTo(seekValue + "");
  3757. this.isSeekTo = false;
  3758. },
  3759. onResult:(result: boolean,outPath:string)=>{
  3760. if(result){//如果成功,更新数据
  3761. this.doUpdateData()
  3762. }else{
  3763. ToastUtil.showToast('格式转化失败')
  3764. }
  3765. }
  3766. }
  3767. )
  3768. }
  3769. }
  3770. .width('100%')
  3771. .height('100%')
  3772. }
  3773. //提取伴奏
  3774. @Builder
  3775. ExtractAccBuilder(item:VideoItem) {
  3776. Scroll() {
  3777. Column() {
  3778. ExtractAccompaniment(
  3779. {
  3780. mVideoItem:item,
  3781. currentPath:this.currentPath,
  3782. videoUrl:this.videoUrl,
  3783. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3784. currentTime:this.currentTime,
  3785. progressValue:this.progressValue,
  3786. onBack:()=>{
  3787. this.isExtractAcc = !this.isExtractAcc
  3788. this.longItemFilePath = ''
  3789. },
  3790. onPlayOrPause:()=>{
  3791. if(this.videoUrl==item.filePath){
  3792. this.playOrPause()
  3793. }else{//如果不是当前播放的,则播放该文件
  3794. this.videoUrl==item.filePath
  3795. this.doPlay(item,0,false,true)
  3796. }
  3797. },
  3798. onSeeOutputPath:(outPutPath:string)=>{
  3799. this.isExtractAcc = !this.isExtractAcc
  3800. this.longItemFilePath = ''
  3801. this.modeType = 0
  3802. this.isShowFileName = true
  3803. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3804. },
  3805. onSliderChange:(value:number)=>{
  3806. if(this.videoUrl!=item.filePath){
  3807. this.videoUrl==item.filePath
  3808. return
  3809. }
  3810. this.isSeekTo = true;
  3811. this.mDestroyPage = false;
  3812. this.showLoadIng();
  3813. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3814. this.seekTo(seekValue + "");
  3815. this.isSeekTo = false;
  3816. },
  3817. onResult:(result: boolean,outPath:string)=>{
  3818. if(result){//如果成功,更新数据
  3819. this.doUpdateData()
  3820. }else{
  3821. ToastUtil.showToast('提取伴奏失败')
  3822. }
  3823. }
  3824. }
  3825. )
  3826. }
  3827. }
  3828. .width('100%')
  3829. .height('100%')
  3830. }
  3831. //AI人声分离
  3832. @Builder
  3833. AiBuilder(item:VideoItem) {
  3834. Scroll() {
  3835. Column() {
  3836. AIVoiceSeparation(
  3837. {
  3838. mVideoItem:item,
  3839. videoUrl:this.videoUrl,
  3840. currentPath:this.currentPath,
  3841. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3842. currentTime:this.currentTime,
  3843. progressValue:this.progressValue,
  3844. onBack:()=>{
  3845. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  3846. this.longItemFilePath = ''
  3847. },
  3848. onPlayOrPause:()=>{
  3849. if(this.videoUrl==item.filePath||this.isPlaying){
  3850. this.playOrPause()
  3851. }else{//如果不是当前播放的,则播放该文件
  3852. this.videoUrl==item.filePath
  3853. this.doPlay(item,0,false,true)
  3854. }
  3855. },
  3856. onPlayPath:(path:string)=>{
  3857. this.videoUrl==path
  3858. const itemP = Utility.getItemByFilePath(this.videoLocalList,path)
  3859. if(itemP)
  3860. this.doPlay(itemP,0,false,true)
  3861. },
  3862. onSeeOutputPath:(outPutPath:string)=>{
  3863. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  3864. this.longItemFilePath = ''
  3865. this.modeType = 0
  3866. this.isShowFileName = true
  3867. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3868. },
  3869. onSliderChange:(value:number)=>{
  3870. if(this.videoUrl!=item.filePath){
  3871. this.videoUrl==item.filePath
  3872. return
  3873. }
  3874. this.isSeekTo = true;
  3875. this.mDestroyPage = false;
  3876. this.showLoadIng();
  3877. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3878. this.seekTo(seekValue + "");
  3879. this.isSeekTo = false;
  3880. },
  3881. onResult:(result: boolean,outPath:string)=>{
  3882. if(result){//如果成功,更新数据
  3883. this.doUpdateData()
  3884. }else{
  3885. ToastUtil.showToast('Ai人声分离失败')
  3886. }
  3887. }
  3888. }
  3889. )
  3890. }
  3891. }
  3892. .width('100%')
  3893. .height('100%')
  3894. }
  3895. //变速变调
  3896. @Builder
  3897. ChangeToneBuilder(item:VideoItem) {
  3898. Scroll() {
  3899. Column() {
  3900. ChangeTone(
  3901. {
  3902. mVideoItem:item,
  3903. currentPath:this.currentPath,
  3904. videoUrl:this.videoUrl,
  3905. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3906. currentTime:this.currentTime,
  3907. progressValue:this.progressValue,
  3908. onBack:()=>{
  3909. this.isChangeTone = !this.isChangeTone
  3910. this.longItemFilePath = ''
  3911. },
  3912. onPlayOrPause:()=>{
  3913. if(this.videoUrl==item.filePath){
  3914. this.playOrPause()
  3915. }else{//如果不是当前播放的,则播放该文件
  3916. this.videoUrl==item.filePath
  3917. this.doPlay(item,0,false,true)
  3918. }
  3919. },
  3920. onSeeOutputPath:(outPutPath:string)=>{
  3921. this.isChangeTone = !this.isChangeTone
  3922. this.longItemFilePath = ''
  3923. this.modeType = 0
  3924. this.isShowFileName = true
  3925. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3926. },
  3927. onSliderChange:(value:number)=>{
  3928. if(this.videoUrl!=item.filePath){
  3929. this.videoUrl==item.filePath
  3930. return
  3931. }
  3932. this.isSeekTo = true;
  3933. this.mDestroyPage = false;
  3934. this.showLoadIng();
  3935. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3936. this.seekTo(seekValue + "");
  3937. this.isSeekTo = false;
  3938. },
  3939. onResult:(result: boolean,outPath:string)=>{
  3940. if(result){//如果成功,更新数据
  3941. this.doUpdateData()
  3942. }else{
  3943. ToastUtil.showToast('变速变调失败')
  3944. }
  3945. }
  3946. }
  3947. )
  3948. }
  3949. }
  3950. .width('100%')
  3951. .height('100%')
  3952. }
  3953. //提取视频中的音频
  3954. @Builder
  3955. extractAudioFromVideoBuilder(item:VideoItem) {
  3956. Scroll() {
  3957. Column() {
  3958. ExtractAudioFromVideo(
  3959. {
  3960. mVideoItem:item,
  3961. currentPath:this.currentPath,
  3962. videoUrl:this.videoUrl,
  3963. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3964. currentTime:this.currentTime,
  3965. progressValue:this.progressValue,
  3966. onBack:()=>{
  3967. this.isExtractAudio = !this.isExtractAudio
  3968. this.longItemFilePath = ''
  3969. },
  3970. onPlayOrPause:()=>{
  3971. if(this.videoUrl==item.filePath){
  3972. this.playOrPause()
  3973. }else{//如果不是当前播放的,则播放该文件
  3974. this.videoUrl==item.filePath
  3975. this.doPlay(item,0,false,true)
  3976. }
  3977. },
  3978. onSeeOutputPath:(outPutPath:string)=>{
  3979. this.isExtractAudio = !this.isExtractAudio
  3980. this.longItemFilePath = ''
  3981. this.modeType = 0
  3982. this.isShowFileName = true
  3983. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3984. },
  3985. onSliderChange:(value:number)=>{
  3986. if(this.videoUrl!=item.filePath){
  3987. this.videoUrl==item.filePath
  3988. return
  3989. }
  3990. this.isSeekTo = true;
  3991. this.mDestroyPage = false;
  3992. this.showLoadIng();
  3993. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3994. this.seekTo(seekValue + "");
  3995. this.isSeekTo = false;
  3996. },
  3997. onResult:(result: boolean,outPath:string)=>{
  3998. if(result){//如果成功,更新数据
  3999. this.doUpdateData()
  4000. }else{
  4001. ToastUtil.showToast('提取音频失败')
  4002. }
  4003. }
  4004. }
  4005. )
  4006. }
  4007. }
  4008. .width('100%')
  4009. .height('100%')
  4010. }
  4011. //合并音频
  4012. @Builder
  4013. MergeAudioBuilder() {
  4014. Scroll() {
  4015. Column() {
  4016. MergeAudio(
  4017. {
  4018. videoUrl:this.videoUrl,
  4019. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4020. currentPath:this.currentPath,
  4021. selectedFiles:this.selectedFiles,
  4022. currentTime:this.currentTime,
  4023. progressValue:this.progressValue,
  4024. onBack:()=>{
  4025. this.isMergeAudio = !this.isMergeAudio
  4026. this.longItemFilePath = ''
  4027. },
  4028. // onPlayPath:(path:string)=>{
  4029. // if(this.videoUrl==item.filePath){
  4030. // this.playOrPause()
  4031. // }else{//如果不是当前播放的,则播放该文件
  4032. // this.videoUrl==item.filePath
  4033. // this.doPlay(item,0,false,true)
  4034. // }
  4035. //
  4036. // },
  4037. onSeeOutputPath:(outPutPath:string)=>{
  4038. this.isMergeAudio = !this.isMergeAudio
  4039. this.longItemFilePath = ''
  4040. this.modeType = 0
  4041. this.isShowFileName = true
  4042. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4043. },
  4044. onResult:(result: boolean,outPath:string)=>{
  4045. if(result){//如果成功,更新数据
  4046. this.doUpdateData()
  4047. }else{
  4048. if(this.selectedFiles.length>=3){
  4049. ToastUtil.showToast('合并数量太多导致失败')
  4050. }else{
  4051. ToastUtil.showToast('合并失败')
  4052. }
  4053. }
  4054. }
  4055. }
  4056. )
  4057. }
  4058. }
  4059. .width('100%')
  4060. .height('100%')
  4061. }
  4062. asyncCurrentPathData() {
  4063. if (this.modeType == 0) {
  4064. workerInstance.postMessage({
  4065. code: 1,
  4066. data1: this.context,
  4067. data2: this.currentPath,
  4068. data3: this.lockPath,
  4069. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  4070. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  4071. });
  4072. }
  4073. }
  4074. // 处理文件选择的函数
  4075. handleFileSelection(item: VideoItem, checked: boolean) {
  4076. if (checked) {
  4077. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  4078. this.selectedFiles.push(item);
  4079. }
  4080. } else {
  4081. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  4082. if (index > -1) {
  4083. this.selectedFiles.splice(index, 1);
  4084. }
  4085. }
  4086. }
  4087. private deleteComponentId: number = 0
  4088. //多选删除文件
  4089. showWarnIsDelete(){
  4090. this.getUIContext().getPromptAction().openCustomDialog({
  4091. builder: () => {
  4092. this.deleteComptentBuilder()
  4093. },
  4094. isModal:true,
  4095. showInSubWindow:false,
  4096. maskColor: Color.Transparent,
  4097. dialogTransition: // 设置弹窗内容显示的过渡效果
  4098. TransitionEffect.translate({ x: 0, y: 290, z: 0 })
  4099. .animation({ duration: 600, curve: Curve.Smooth }),
  4100. maskTransition: // 设置蒙层显示的过渡效果
  4101. TransitionEffect.opacity(0)
  4102. .animation({ duration: 600, curve: Curve.Smooth })
  4103. }).then((dialogId: number) => {
  4104. this.deleteComponentId = dialogId
  4105. })
  4106. .catch((error: BusinessError) => {
  4107. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  4108. })
  4109. }
  4110. @Builder
  4111. deleteComptentBuilder(){
  4112. DeleteComptent({
  4113. selectedFiles:this.selectedFiles,
  4114. onCancel:()=>{
  4115. this.isMultiSelect = false
  4116. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  4117. },
  4118. onDeleteResult:(result: boolean)=>{
  4119. this.isMultiSelect = false
  4120. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  4121. if(result){//如果删除成功,更新数据
  4122. this.selectedFiles = [];
  4123. this.isAllSelected = false
  4124. this.cache.delete(this.currentPath);
  4125. this.getSortedFiles(this.currentPath, true);
  4126. }
  4127. }
  4128. })
  4129. }
  4130. //多选移动文件
  4131. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  4132. Logger.info('onecold showCutDialogForMultipleFiles')
  4133. let mList: Array<string> = []
  4134. let rPath = this.rootPath
  4135. if (isCurrent) {
  4136. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  4137. rPath = this.currentPath
  4138. } else {
  4139. mList = Utility.getNameList(this.dirList);
  4140. rPath = this.rootPath
  4141. }
  4142. let dataBean = new BubbleBean();
  4143. dataBean.data = mList;
  4144. dataBean.color = this.themeColor
  4145. dataBean.onItemClick = (i) => {
  4146. const newDirPath = rPath + '/' + mList[i];
  4147. // Logger.info('newDirPath = ' + newDirPath)
  4148. this.selectedFiles.forEach((item) => {
  4149. const newPath = newDirPath + '/' + item.fileName;
  4150. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  4151. ToastUtil.showToast('移动成功');
  4152. this.table.deleteData(item, () => {
  4153. this.cache.delete(this.currentPath); // 删除原路径缓存
  4154. this.cache.delete(newDirPath); // 删除目标路径缓存
  4155. this.getSortedFiles(this.currentPath, true);
  4156. });
  4157. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  4158. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  4159. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  4160. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  4161. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  4162. this.table.insert(newItem, (id: number) => {
  4163. //加入数据库
  4164. });
  4165. }
  4166. }).catch((error: Error) => {
  4167. console.error(error.message);
  4168. });
  4169. });
  4170. this.isMultiSelect = false
  4171. this.selectedFiles = [];
  4172. this.isAllSelected = false
  4173. XPopup.dismissTop();
  4174. };
  4175. let pup: XPopup
  4176. if (this.isDarkMode) {
  4177. pup = XPopup.Builder()
  4178. .setPopupPosition(PopupPosition.TOP)
  4179. .atView(viewId)
  4180. .setBackgroundColor(Color.Black)
  4181. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4182. .show();
  4183. } else {
  4184. pup = XPopup.Builder()
  4185. .setPopupPosition(PopupPosition.TOP)
  4186. .atView(viewId)
  4187. .setBackgroundColor(Color.White)
  4188. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4189. .show();
  4190. }
  4191. }
  4192. /**
  4193. * 加载所有歌单
  4194. */
  4195. async loadAllPlaylists() {
  4196. try {
  4197. this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
  4198. LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
  4199. } catch (error) {
  4200. LogUtil.error('heaunp Failed to load playlists: ' + error.message)
  4201. }
  4202. }
  4203. /**
  4204. * 显示添加到歌单对话框
  4205. */
  4206. async openAddToPlaylistDialog(items: VideoItem | VideoItem[]) {
  4207. const songs = Array.isArray(items) ? items : [items]
  4208. const musicItems = songs.filter(song => song.type !== CommonConstants.TYPE_IS_DIR)
  4209. if (musicItems.length === 0) {
  4210. ToastUtil.showToast('请选择要添加的歌曲')
  4211. return
  4212. }
  4213. // 加载最新的歌单列表
  4214. await this.loadAllPlaylists()
  4215. showAddToPlaylistDialog(
  4216. musicItems,
  4217. this.allPlaylists,
  4218. async (playlistId: string) => {
  4219. // 添加歌曲到歌单
  4220. const success = await this.playlistTable?.addSongsToPlaylist(playlistId,
  4221. musicItems.map(song => song.filePath))
  4222. if (success) {
  4223. const count = musicItems.length
  4224. ToastUtil.showToast(count > 1 ? `已添加 ${count} 首歌曲` : '已添加到歌单')
  4225. // 重新加载歌单列表
  4226. await this.loadAllPlaylists()
  4227. } else {
  4228. ToastUtil.showToast(musicItems.length > 1 ? '选中的歌曲已在该歌单中' : '歌曲已在该歌单中')
  4229. }
  4230. this.longItemFilePath = ''
  4231. if (this.isMultiSelect) {
  4232. this.isMultiSelect = false
  4233. this.isAllSelected = false
  4234. this.selectedFiles = []
  4235. }
  4236. },
  4237. () => {
  4238. LogUtil.info('取消添加到歌单')
  4239. },
  4240. () => {
  4241. // 创建新歌单
  4242. showCreatePlaylistDialog(
  4243. async (name: string, description: string, coverPath?: string) => {
  4244. const success = await this.playlistTable?.createPlaylist(name, description, coverPath)
  4245. if (success) {
  4246. ToastUtil.showToast('歌单创建成功')
  4247. // 重新加载歌单列表并打开添加对话框
  4248. await this.loadAllPlaylists()
  4249. await this.openAddToPlaylistDialog(musicItems)
  4250. } else {
  4251. ToastUtil.showToast('歌单创建失败')
  4252. }
  4253. },
  4254. () => {
  4255. // 取消创建歌单
  4256. }
  4257. )
  4258. }
  4259. )
  4260. }
  4261. doFav(item: VideoItem) {
  4262. LogUtil.info('onecold doFav isFav=' + item.isFav)
  4263. let isFav = 0
  4264. if (Utility.getIsFav(this.favList, item)) {
  4265. isFav = 0
  4266. } else {
  4267. isFav = 1
  4268. }
  4269. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  4270. if (result) {
  4271. if (isFav === 1) {
  4272. ToastUtil.showToast('收藏成功');
  4273. } else {
  4274. ToastUtil.showToast('取消收藏成功');
  4275. }
  4276. this.deleteCache(this.currentPath)
  4277. this.getFavList(false)
  4278. if (this.modeType === 0 && !this.isFavMusic) {
  4279. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  4280. this.getSortedFiles(this.currentPath)
  4281. }
  4282. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  4283. workerInstance.postMessage({ code: 3, data: this.context });
  4284. workerInstance.postMessage({ code: 4, data: this.context });
  4285. }
  4286. })
  4287. }
  4288. //多选复制文件
  4289. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  4290. console.log('onecold showCopyDialogForMultipleFiles');
  4291. let mList: Array<string> = []
  4292. let rPath = this.rootPath
  4293. if (isCurrent) {
  4294. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  4295. rPath = this.currentPath
  4296. } else {
  4297. mList = Utility.getNameList(this.dirList);
  4298. rPath = this.rootPath
  4299. }
  4300. let dataBean = new BubbleBean();
  4301. dataBean.data = mList;
  4302. dataBean.isCopy = true
  4303. dataBean.color = this.themeColor
  4304. dataBean.onItemClick = (i) => {
  4305. const newDirPath = rPath + '/' + mList[i];
  4306. // Logger.info('newDirPath = ' + newDirPath)
  4307. this.selectedFiles.forEach((item) => {
  4308. const newPath = newDirPath + '/' + item.fileName;
  4309. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  4310. ToastUtil.showToast('复制成功');
  4311. this.cache.delete(newDirPath); // 删除目标路径缓存
  4312. this.getSortedFiles(this.currentPath);
  4313. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  4314. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  4315. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  4316. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  4317. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  4318. this.table.insert(newItem, (id: number) => {
  4319. //加入数据库
  4320. });
  4321. }
  4322. }).catch((error: Error) => {
  4323. console.error(error.message);
  4324. });
  4325. });
  4326. this.isMultiSelect = false
  4327. this.selectedFiles = [];
  4328. this.isAllSelected = false
  4329. XPopup.dismissTop();
  4330. };
  4331. let pup: XPopup
  4332. if (this.isDarkMode) {
  4333. pup = XPopup.Builder()
  4334. .setPopupPosition(PopupPosition.TOP)
  4335. .atView(viewId)
  4336. .setBackgroundColor(Color.Black)
  4337. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4338. .show();
  4339. } else {
  4340. pup = XPopup.Builder()
  4341. .setPopupPosition(PopupPosition.TOP)
  4342. .atView(viewId)
  4343. .setBackgroundColor(Color.White)
  4344. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4345. .show();
  4346. }
  4347. }
  4348. @Builder
  4349. private DirItem(item: VideoItem, index?: number) {
  4350. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  4351. Row() {
  4352. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  4353. $r('app.media.music_group'))
  4354. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4355. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4356. .fillColor(this.themeColor)// .fontSize(33)
  4357. .alt($r('app.media.music_group'))
  4358. .borderRadius(this.isCoverRectangle?9:'100%')
  4359. .clip(true)
  4360. .shadow({
  4361. radius: 2,
  4362. type: ShadowType.BLUR,
  4363. color: 'on_primary'
  4364. })
  4365. .sourceSize({width:38, height:38})
  4366. .margin({ left: 20, top: 8, bottom: 8 })
  4367. Column() {
  4368. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4369. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4370. .maxLines(1)// .width('88%')
  4371. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4372. .animation({
  4373. duration: 555,
  4374. curve: 'ease-in-out',
  4375. })
  4376. .transition({
  4377. type: TransitionType.Insert,
  4378. opacity: 0,
  4379. translate: { x: 160 }
  4380. })
  4381. .margin({ left: 10, right: 20 })
  4382. .fontColor($r('app.color.text_color'))
  4383. Row() {
  4384. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  4385. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4386. .padding({ top: 8 })
  4387. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  4388. .fontColor($r('app.color.text_color'))
  4389. .margin({ left: 10 })
  4390. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  4391. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4392. .padding({ top: 8 })
  4393. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  4394. .fontColor($r('app.color.text_color'))
  4395. .margin({ left: 10 })
  4396. Blank()
  4397. }
  4398. }
  4399. .height('100%')
  4400. .layoutWeight(1)
  4401. .justifyContent(FlexAlign.Center)
  4402. .alignItems(HorizontalAlign.Start)
  4403. Blank()
  4404. Image($r('app.media.arrow_right'))
  4405. .height(25)
  4406. .alignSelf(ItemAlign.Center)
  4407. .id(item.filePath)
  4408. .visibility(this.isShowAlphaBet?Visibility.None:Visibility.Visible)
  4409. .animation({ duration: 300, curve: Curve.Ease })
  4410. }
  4411. }
  4412. .backgroundColor(Color.Transparent)
  4413. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  4414. .width('98%')
  4415. .reuseId('dir_item')
  4416. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  4417. .opacity(this.opacityItem) // 绑定透明度
  4418. }
  4419. isShowDir(dirName: string) {
  4420. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  4421. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  4422. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  4423. if (dirName === undefined) {
  4424. return true
  4425. }
  4426. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  4427. return this.isShowSimi
  4428. }
  4429. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  4430. return this.isShowFAV
  4431. }
  4432. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  4433. return this.isShowHistory
  4434. }
  4435. return true
  4436. }
  4437. @State opacityItem: number = 1; // 控制透明度的状态变量
  4438. @Builder
  4439. private MusicItem(item: VideoItem, index?: number) {
  4440. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  4441. Row() {
  4442. Stack() {
  4443. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  4444. .fillColor(this.themeColor)
  4445. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4446. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4447. .alt($r('app.media.music_red'))
  4448. .borderRadius(this.isCoverRectangle?9:'100%')
  4449. .clip(true)
  4450. .draggable(false)
  4451. .sourceSize({width:38, height:38})
  4452. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4453. // .autoResize(true) // 重采样,可减少内存占用
  4454. .opacity(this.opacityItem)// 绑定透明度
  4455. .margin({ left: 20 })
  4456. .shadow({
  4457. radius: StrUtil.isEmpty(item.pixelMapPath) ?6:14,
  4458. type: ShadowType.BLUR,
  4459. color: 'on_primary'
  4460. })
  4461. .gesture(LongPressGesture()
  4462. .onAction(async () => {
  4463. //如果是专辑和艺术家的首页,不能长按
  4464. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4465. return
  4466. //如果是我的收藏 最近播放等也不能长按
  4467. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4468. item.name === LocalMusic.STR_HISTORY_MUSIC
  4469. )
  4470. return
  4471. this.longItemFilePath = item.filePath
  4472. this.tempLyricContent = await this.getLyricContent(item)
  4473. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4474. })
  4475. .onActionEnd((event: GestureEvent) => {
  4476. }))
  4477. .onClick(()=>{
  4478. if (this.isMultiSelect) {
  4479. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4480. this.handleFileSelection(item, !isChecked);
  4481. } else {
  4482. this.doPlay(item,index)
  4483. this.setShowPlayTrue()
  4484. }
  4485. })
  4486. }
  4487. Column() {
  4488. Column() {
  4489. Text(this.isShowFileName?item.fileName :item.name)
  4490. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4491. .maxLines(1)
  4492. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4493. .animation({
  4494. duration: 555,
  4495. curve: 'Linear',
  4496. })
  4497. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4498. $r('app.color.text_color'))
  4499. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4500. .padding({right:25})
  4501. .bindPopup(this.longItemFilePath === item.filePath, {
  4502. builder: this.MenuBuilder(item,index,item.filePath),
  4503. placement: Placement.Top,
  4504. // autoCancel: true,
  4505. mask: {color:'#33000000'},
  4506. // popupColor: Color.Yellow,
  4507. enableArrow: false,//是否显示箭头
  4508. showInSubWindow: false,
  4509. onStateChange: (e) => {
  4510. if (!e.isVisible) {
  4511. this.longItemFilePath = ''
  4512. this.tempLyricContent = ''
  4513. }
  4514. }
  4515. })
  4516. .gesture(LongPressGesture()
  4517. .onAction(async () => {
  4518. //如果是专辑和艺术家的首页,不能长按
  4519. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4520. return
  4521. //如果是我的收藏 最近播放等也不能长按
  4522. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4523. item.name === LocalMusic.STR_HISTORY_MUSIC
  4524. )
  4525. return
  4526. this.longItemFilePath = item.filePath
  4527. this.tempLyricContent = await this.getLyricContent(item)
  4528. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4529. })
  4530. .onActionEnd((event: GestureEvent) => {
  4531. })
  4532. )
  4533. Row() {
  4534. Column(){
  4535. Text(item.md5Str?.includes('Lossless')?
  4536. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4537. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  4538. .padding({ top: 3,right:6,left:6,bottom:3 })
  4539. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4540. $r('app.color.text_color'))
  4541. .fontWeight(500)
  4542. .borderRadius(12)
  4543. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  4544. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4545. .backgroundColor('#FFC107')
  4546. }
  4547. .padding({ top: 8 })
  4548. Text(StrUtil.isEmpty(item.artist) ? item.duration
  4549. :this.twoFingerType==2? item.artist +' ' + item.duration
  4550. : item.artist + ' ' + item?.duration)
  4551. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4552. .padding({ top: 8 ,right:25})
  4553. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  4554. .maxLines(1)
  4555. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4556. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4557. Color.Gray)
  4558. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4559. Blank()
  4560. Text(this.isShowFileName?item.duration:item.size)
  4561. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4562. .padding({ top: 8 })
  4563. .maxLines(1)
  4564. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  4565. ? Visibility.Visible : Visibility.None)
  4566. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4567. Color.Gray)
  4568. .margin({ left: StrUtil.isEmpty(item.artist) ?0:10 })
  4569. }
  4570. .gesture(LongPressGesture()
  4571. .onAction(async () => {
  4572. //如果是专辑和艺术家的首页,不能长按
  4573. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4574. return
  4575. //如果是我的收藏 最近播放等也不能长按
  4576. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4577. item.name === LocalMusic.STR_HISTORY_MUSIC
  4578. )
  4579. return
  4580. this.longItemFilePath = item.filePath
  4581. this.tempLyricContent = await this.getLyricContent(item)
  4582. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4583. })
  4584. .onActionEnd((event: GestureEvent) => {
  4585. })
  4586. )
  4587. }
  4588. .height('100%')
  4589. .width('100%')
  4590. .margin({ right: 10 })
  4591. .justifyContent(FlexAlign.Center)
  4592. .alignItems(HorizontalAlign.Start)
  4593. }
  4594. .height('100%')
  4595. .margin({ left: 5 })
  4596. .layoutWeight(1)
  4597. Column() {
  4598. Checkbox({ name: 'checkbox' + index })
  4599. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  4600. .selectedColor(this.themeColor)
  4601. .shape(CheckBoxShape.CIRCLE)
  4602. .opacity(this.isMultiSelect ? 1 : 0)
  4603. .animation({
  4604. duration: 666,
  4605. curve: 'Smooth' // 可选动画曲线
  4606. })
  4607. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  4608. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  4609. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  4610. .width(22)
  4611. .height(22)
  4612. ImageAnimator()
  4613. .images(this.imagesF)// 动画数组
  4614. .duration(1000)// 持续
  4615. .state(this.animationState)// 动画状态
  4616. .fillMode(FillMode.Forwards)
  4617. .width(18)
  4618. .margin({ right: 20, top: 8, bottom: 8 })
  4619. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  4620. Visibility.None)
  4621. .height(18)
  4622. .iterations(-1) // 播放次数
  4623. }
  4624. }
  4625. }
  4626. .backgroundColor(Color.Transparent)
  4627. .width('100%')
  4628. .reuseId('file_item')
  4629. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  4630. }
  4631. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  4632. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  4633. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  4634. direction: Direction.Ltr,
  4635. buttonPadding:{top:12,bottom:12},
  4636. backgroundColor: Color.Transparent,
  4637. fontSize:14,
  4638. selectedFontSize:15,
  4639. selectedFontColor:Color.White,
  4640. selectedBackgroundColor: this.themeColor,
  4641. localizedTextPadding: {
  4642. end: LengthMetrics.vp(20),
  4643. start: LengthMetrics.vp(20)
  4644. }
  4645. })
  4646. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  4647. //当胶囊按钮的选择发生变化时调用此函数
  4648. capsuleSelectedIndexesChanged() {
  4649. this.modeType = this.tabSelectedIndexes[0]
  4650. }
  4651. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  4652. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  4653. isShowCoverHeader() {
  4654. if (!this.isShowHeader) {
  4655. return false
  4656. }
  4657. if (this.modeType == 0) {
  4658. if (this.isHistory || this.isFavMusic) {
  4659. return true
  4660. }
  4661. if (this.currentPath != this.rootPath) {
  4662. return true
  4663. }
  4664. }
  4665. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  4666. }
  4667. getCoverTitleBg(): ResourceStr | image.PixelMap {
  4668. if (this.isCustomizeBg) {
  4669. return ('rgba(255,255,255,0.2)')
  4670. }
  4671. if (this.isDarkMode) {
  4672. return $r('app.color.user_center_card_background')
  4673. }
  4674. return this.currentTitleCover
  4675. }
  4676. // 第二步:popup构造器定义弹框内容
  4677. @Builder popupBuilder() {
  4678. Column({ space: 2 }) {
  4679. Text('友情提示:双指缩放可以放大缩小列表')
  4680. .fontSize(12)
  4681. .fontWeight(FontWeight.Regular)
  4682. .fontColor($r('app.color.text_color'))
  4683. }
  4684. .justifyContent(FlexAlign.SpaceAround)
  4685. .width(220)
  4686. .height(55)
  4687. .padding(15)
  4688. }
  4689. //搜索功能的实现
  4690. @State searchText: string = ''; // 用户输入内容
  4691. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  4692. @State isSearchMode: boolean = false
  4693. // 实时搜索逻辑(带防抖)
  4694. private onSearchInput(value: string) {
  4695. this.searchText = value.trim();
  4696. let mSearchList: Array<VideoItem> = []
  4697. switch (this.modeType) {
  4698. case 0:
  4699. case 1:
  4700. mSearchList = this.mediaKuList
  4701. break;
  4702. case 2:
  4703. mSearchList = this.artistList
  4704. break;
  4705. case 3:
  4706. mSearchList = this.albumList
  4707. break;
  4708. default :
  4709. mSearchList = this.videoLocalList
  4710. break;
  4711. }
  4712. // 新增条件判断:空输入时显示所有数据
  4713. if (this.searchText === '') {
  4714. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  4715. } else {
  4716. this.filteredList = mSearchList.filter((item: VideoItem) => {
  4717. //支持模糊匹配和艺术家 专辑匹配
  4718. const regex = new RegExp(this.searchText.toLowerCase().replace(/\s+/g, '.*'), 'i');
  4719. return regex.test(item.name.toLowerCase())||
  4720. regex.test(item.fileName?.toLowerCase() ?? "") ||
  4721. regex.test(item.artist?.toLowerCase() ?? "") ||
  4722. regex.test(item.album?.toLowerCase() ?? "")
  4723. });
  4724. }
  4725. this.updateListData(this.filteredList);
  4726. // this.isSearchMode = false; // 根据业务需求决定是否启用
  4727. }
  4728. @State dragItem: number = -1
  4729. @State scaleItem: number = -1
  4730. @State neighborItem: number = -1
  4731. @State neighborScale: number = -1
  4732. @State offsetY: number = 0
  4733. private dragRefOffset: number = 0
  4734. private ITEM_INTV: number = 78
  4735. scaleSelect(item: number): number {
  4736. if (this.scaleItem === item) {
  4737. return 1.05
  4738. } else if (this.neighborItem === item) {
  4739. return this.neighborScale
  4740. } else {
  4741. return 1
  4742. }
  4743. }
  4744. itemMove(index: number, newIndex: number): void {
  4745. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  4746. return;
  4747. }
  4748. let tmp = this.videoLocalList.splice(index, 1);
  4749. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  4750. this.dataSource.pushArrayData(this.videoLocalList)
  4751. if(this.modeType==4&&this.playlistTable){
  4752. updateAllSongsSortOrder(this.playlistTable, this.videoLocalList,this.currentSongListID)
  4753. }
  4754. }
  4755. //瀑布流布局 支持双指缩放
  4756. @State columns: number = 2;
  4757. @State waterFlowScale: number = 1;
  4758. @State imageScale: number = 1;
  4759. @State waterFlowOpacity: number = 1;
  4760. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  4761. private columnChanged: boolean = false;
  4762. private oldColumn: number = this.columns;
  4763. private pinchTime: number = 0;
  4764. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  4765. changeColumns(scale: number) {
  4766. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  4767. this.columns--;
  4768. this.columnChanged = true;
  4769. } else if (scale < 1 && this.columns < 4) {
  4770. this.columns++;
  4771. this.columnChanged = true;
  4772. }
  4773. }
  4774. @Builder
  4775. getWaterView(){
  4776. Scroll(this.scroller) {
  4777. Column() {
  4778. Blank().height(this.topSafeHeight + 55)
  4779. WaterFlow({
  4780. scroller:this.waterScroller,
  4781. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  4782. }) {
  4783. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  4784. FlowItem() {
  4785. this.MusicWaterCardItem(item,index)
  4786. }
  4787. .width('100%')
  4788. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  4789. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  4790. {
  4791. preview: MenuPreviewMode.IMAGE,
  4792. previewAnimationOptions: { scale: [0.8, 1.0] },
  4793. })
  4794. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  4795. {
  4796. preview: MenuPreviewMode.IMAGE,
  4797. previewAnimationOptions: { scale: [0.8, 1.0] },
  4798. })
  4799. .transition(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }))
  4800. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  4801. TransitionEffect.scale({ x: 0, y: 0 })))
  4802. .gesture(
  4803. GestureGroup(GestureMode.Exclusive,
  4804. SwipeGesture({ direction: SwipeDirection.Horizontal })
  4805. .onAction((event: GestureEvent) => {
  4806. if (event) {
  4807. // this.sideBarController.openSideBar()
  4808. }
  4809. }),
  4810. TapGesture({ count: 1, fingers: 1 })
  4811. .onAction(async () => {
  4812. })
  4813. )
  4814. )
  4815. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  4816. }
  4817. // .columnsTemplate('repeat(auto-fit, 160)')
  4818. .id('waterflow') // 设置id用于截图
  4819. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  4820. .columnsGap(12) // 列间距
  4821. .rowsGap(16) // 行间距
  4822. .cachedCount(6)
  4823. .padding({bottom:this.bottomBarHeight+10})
  4824. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4825. .animation({ duration: 500, curve: Curve.Ease }))
  4826. .scrollBar(BarState.Off)
  4827. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  4828. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  4829. .edgeEffect(EdgeEffect.Spring, { alwaysEnabled: true })
  4830. .width('90%')
  4831. .height('100%')
  4832. .opacity(this.waterFlowOpacity)
  4833. .scale({
  4834. x: this.waterFlowScale,
  4835. y: this.waterFlowScale,
  4836. centerX: 0,
  4837. centerY: 0
  4838. })
  4839. .onAppear(() => {
  4840. this.scroller.scrollEdge(Edge.Top)
  4841. })
  4842. .nestedScroll({
  4843. scrollForward: NestedScrollMode.PARENT_FIRST,
  4844. scrollBackward: NestedScrollMode.SELF_FIRST
  4845. })
  4846. .priorityGesture(
  4847. PinchGesture()
  4848. .onActionStart((event: GestureEvent) => {
  4849. // 双指捏合手势识别成功时截图
  4850. this.pinchTime = event.timestamp;
  4851. this.columnChanged = false;
  4852. this.oldColumn = this.columns;
  4853. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  4854. if (error) {
  4855. console.info('error:' + JSON.stringify(error));
  4856. return;
  4857. }
  4858. this.waterFlowSnapshot = pixmap;
  4859. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  4860. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  4861. if (this.oldColumn ===4) {
  4862. this.twoFingerType =3
  4863. this.isGridMusic = true
  4864. }else if (this.oldColumn ===1) {
  4865. this.twoFingerType =1
  4866. this.isGridMusic = false
  4867. }
  4868. return;
  4869. }
  4870. })
  4871. })
  4872. .onActionUpdate((event: GestureEvent) => {
  4873. // 手势更新:处理缩放逻辑和视觉效果
  4874. // 边界限制:防止超出列数范围时继续缩放
  4875. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  4876. return;
  4877. }
  4878. // 节流处理:避免过于频繁的更新,提升性能
  4879. if (event.timestamp - this.pinchTime < 10000000) {
  4880. return;
  4881. }
  4882. this.pinchTime = event.timestamp;
  4883. this.waterFlowScale = event.scale;
  4884. this.imageScale = event.scale;
  4885. // 根据缩放比例设置WaterFlow透明度
  4886. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  4887. this.waterFlowOpacity *= 3;
  4888. if (!this.columnChanged) {
  4889. this.changeColumns(event.scale);
  4890. }
  4891. // 列数改变后的缩放比例调整:避免出现空白区域
  4892. if (this.columnChanged) {
  4893. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  4894. // 限制缩放范围,确保视觉效果自然
  4895. if (event.scale < 1) {
  4896. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  4897. } else {
  4898. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  4899. }
  4900. }
  4901. })
  4902. .onActionEnd((event: GestureEvent) => {
  4903. // 手势结束:执行归位动画并保存状态
  4904. // 执行归位动画:平滑过渡到正常状态
  4905. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  4906. this.waterFlowScale = 1;
  4907. this.waterFlowOpacity = 1;
  4908. })
  4909. // 持久化保存当前列数:下次启动时恢复
  4910. PreferencesUtil.putSync('lastColumns', this.columns);
  4911. })
  4912. )
  4913. .onScrollFrameBegin((offset: number) => {
  4914. // 获取当前滚动偏移量
  4915. if(this.autoHideTitle){
  4916. const currentOffsetY = this.waterScroller.currentOffset().yOffset;
  4917. // 判断滚动方向
  4918. if (currentOffsetY > this.prevOffsetY) {
  4919. console.log("onecold 向上滚动");
  4920. this.isShowTitleBar = false
  4921. } else if (currentOffsetY < this.prevOffsetY) {
  4922. console.log("onecold 向下滚动");
  4923. this.isShowTitleBar = true
  4924. }
  4925. // 更新前一次偏移量
  4926. this.prevOffsetY = currentOffsetY;
  4927. }
  4928. return { offsetRemain: offset };
  4929. })
  4930. //允许拖拽音乐和视频到List或Grid上自动导入视频
  4931. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  4932. .onDrop((event?: DragEvent) => {
  4933. try {
  4934. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  4935. if (dragData !== undefined) {
  4936. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  4937. if (records.length > 0) {
  4938. for (let i = 0; i < records.length; i++) {
  4939. let types = records[i].getTypes();
  4940. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  4941. const fileUriUds =
  4942. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  4943. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  4944. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  4945. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  4946. this.targetFile = fileUriUds.oriUri;
  4947. this.saveVideoDatas([this.targetFile])
  4948. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  4949. }
  4950. }
  4951. }
  4952. } else {
  4953. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  4954. }
  4955. } else {
  4956. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  4957. }
  4958. } catch (error) {
  4959. const err = error as BusinessError;
  4960. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  4961. }
  4962. })
  4963. }
  4964. }
  4965. .scrollBar(BarState.Off)
  4966. }
  4967. //瀑布流卡片布局
  4968. @Builder
  4969. private MusicWaterCardItem(item: VideoItem, index: number) {
  4970. Button({ type: ButtonType.Normal, stateEffect: false }) {
  4971. Stack() {
  4972. Column() {
  4973. Image(item.pixelMapPath)
  4974. .backgroundImageSize(ImageSize.Auto)
  4975. .borderRadius({
  4976. topLeft: 12,
  4977. topRight : 12,
  4978. bottomLeft: 0,
  4979. bottomRight: 0
  4980. })
  4981. .draggable(false)// 禁止长按手势拖动
  4982. .autoResize(true) // 重采样,可减少内存占用
  4983. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4984. .width('100%')
  4985. .height('auto')
  4986. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  4987. .objectFit(ImageFit.Auto)
  4988. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  4989. height: '99%' ,
  4990. dragBar: true,
  4991. onDisappear: () => {
  4992. this.longItemFilePath = '';
  4993. this.tempLyricContent = ''
  4994. },
  4995. showClose: true,
  4996. preferType: SheetType.CENTER ,
  4997. title: { title: '编辑标签' }
  4998. })
  4999. .draggable(false)
  5000. .opacity(this.opacityItem)// 绑定透明度
  5001. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  5002. // .animation({ duration: 500, curve: Curve.Ease }))
  5003. .animation({
  5004. duration: 666,
  5005. curve: 'ease-in-out' // 可选动画曲线
  5006. })
  5007. .margin({
  5008. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5009. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5010. })
  5011. Column() {
  5012. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5013. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  5014. .maxLines(1)
  5015. .fontWeight(FontWeight.Bold)
  5016. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5017. .animation({
  5018. duration: 555,
  5019. curve: 'Linear',
  5020. })
  5021. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  5022. height: '95%',
  5023. dragBar: true,
  5024. showClose: true,
  5025. onDisappear: () => {
  5026. this.longItemFilePathDetail = '';
  5027. },
  5028. blurStyle:BlurStyle.Thin,
  5029. backgroundColor:Color.Transparent,
  5030. preferType: SheetType.CENTER ,
  5031. title: { title: '详情' }
  5032. })
  5033. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5034. $r('app.color.text_color'))
  5035. Column() {
  5036. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  5037. .fontSize(11)
  5038. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  5039. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5040. .fontColor($r('app.color.text_color'))
  5041. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  5042. .fontSize(11)
  5043. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  5044. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5045. .fontColor($r('app.color.text_color'))
  5046. Row(){
  5047. Column(){
  5048. Text(item.md5Str?.includes('Lossless')?
  5049. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5050. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  5051. .padding({ top: 3,right:6,left:6,bottom:3 })
  5052. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5053. $r('app.color.text_color'))
  5054. .fontWeight(500)
  5055. .borderRadius(12)
  5056. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5057. .backgroundColor('#FFC107')
  5058. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  5059. }
  5060. .margin({ top: 2 ,right:6})
  5061. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  5062. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  5063. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  5064. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  5065. .maxLines(1)
  5066. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5067. .margin({ top: 2})
  5068. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  5069. || item.type == CommonConstants.TYPE_IS_ALBUM
  5070. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5071. .fontWeight(FontWeight.Medium)
  5072. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5073. $r('app.color.text_color'))
  5074. }
  5075. }
  5076. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  5077. }
  5078. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  5079. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  5080. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  5081. .width('100%')
  5082. .justifyContent(FlexAlign.Center)
  5083. .margin({
  5084. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5085. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5086. })
  5087. }
  5088. .width('100%')
  5089. .borderRadius(12)
  5090. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  5091. .backgroundImageSize({ height: '100%', width: '100%' })
  5092. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  5093. .animation({ curve: Curve.Sharp, duration: 300 })
  5094. Checkbox({ name: 'checkbox' + index })
  5095. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  5096. .selectedColor(this.themeColor)
  5097. .shape(CheckBoxShape.CIRCLE)
  5098. .opacity(this.isMultiSelect ? 1 : 0)
  5099. .animation({
  5100. duration: 666,
  5101. curve: 'Smooth' // 可选动画曲线
  5102. })
  5103. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  5104. Visibility.None)
  5105. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5106. .margin({ left: 20, top: 8, bottom: 8 })
  5107. .width(38)
  5108. .height(38)
  5109. }
  5110. }
  5111. .backgroundColor(Color.Transparent)
  5112. .width('100%')
  5113. .height('auto')
  5114. .padding({top:2})
  5115. .shadow({
  5116. radius: 10,
  5117. type: ShadowType.BLUR,
  5118. color: 'on_primary'
  5119. })
  5120. .reuseId('card_item')
  5121. .onClick(() => {
  5122. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5123. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5124. this.handleFileSelection(item, !isChecked);
  5125. } else {
  5126. this.doPlay(item, index)
  5127. }
  5128. })
  5129. }
  5130. // Grid布局的开始
  5131. private dragRefOffSetX: number = 0;
  5132. private dragRefOffSetY: number = 0;
  5133. private FIX_VP_X: number = 180;
  5134. private FIX_VP_Y: number = 84;
  5135. isDraggable(index: number): boolean {
  5136. return index >= 0;
  5137. }
  5138. getRowEnd(item: number) {
  5139. if (item.toString() === '0') {
  5140. return 1;
  5141. } else {
  5142. return 0;
  5143. }
  5144. }
  5145. isInLeft(index: number) {
  5146. return index % 2 == 0;
  5147. }
  5148. down(index: number): void {
  5149. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  5150. return;
  5151. }
  5152. this.offsetY -= this.FIX_VP_Y;
  5153. this.dragRefOffSetY += this.FIX_VP_Y;
  5154. this.itemMove(index, index + 1);
  5155. }
  5156. up(index: number): void {
  5157. if (!this.isDraggable(index - 2)) {
  5158. return;
  5159. }
  5160. this.offsetY += this.FIX_VP_Y;
  5161. this.dragRefOffSetY -= this.FIX_VP_Y;
  5162. this.itemMove(index, index - 1);
  5163. }
  5164. left(index: number): void {
  5165. if (this.isInLeft(index)) {
  5166. return;
  5167. }
  5168. if (!this.isDraggable(index - 1)) {
  5169. return;
  5170. }
  5171. this.offsetX += this.FIX_VP_X;
  5172. this.dragRefOffSetX -= this.FIX_VP_X;
  5173. this.itemMove(index, index - 1)
  5174. }
  5175. right(index: number): void {
  5176. if (!this.isInLeft(index)) {
  5177. return;
  5178. }
  5179. if (!this.isDraggable(index + 1)) {
  5180. return;
  5181. }
  5182. this.offsetX -= this.FIX_VP_X;
  5183. this.dragRefOffSetX += this.FIX_VP_X;
  5184. this.itemMove(index, index + 1)
  5185. }
  5186. private scroller: Scroller = new Scroller();
  5187. private waterScroller: Scroller = new Scroller();
  5188. @State startIndex: number = 0
  5189. @State endIndex: number = 0
  5190. @State scaleValue: number = 1
  5191. @State pinchValue: number = 1
  5192. layoutOptionsForHeader: GridLayoutOptions = {
  5193. regularSize: [1, 1], // 只支持[1, 1]
  5194. irregularIndexes: [0], // 索引为0的GridItem占用一行
  5195. };
  5196. @Builder
  5197. getGridView() {
  5198. Grid(this.scroller, this.layoutOptionsForHeader) {
  5199. GridItem() {
  5200. Column(){
  5201. Blank().height(this.topSafeHeight + 45)
  5202. }
  5203. }
  5204. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5205. GridItem() {
  5206. Stack({ alignContent: Alignment.Center }) {
  5207. this.MusicItemGrid(item, index)
  5208. }
  5209. }
  5210. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  5211. {
  5212. preview: MenuPreviewMode.IMAGE,
  5213. previewAnimationOptions: { scale: [0.8, 1.0] },
  5214. })
  5215. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  5216. {
  5217. preview: MenuPreviewMode.IMAGE,
  5218. previewAnimationOptions: { scale: [0.8, 1.0] },
  5219. })
  5220. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  5221. TransitionEffect.scale({ x: 0, y: 0 })))
  5222. .clickEffect({ level: ClickEffectLevel.LIGHT })
  5223. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  5224. .zIndex(this.dragItem === index ? 1 : 0)
  5225. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  5226. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5227. }
  5228. .width('94%')
  5229. .height('100%')
  5230. .editMode(true)
  5231. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  5232. .animation({ duration: 500, curve: Curve.Ease }))
  5233. .padding({bottom:this.bottomBarHeight+this.bottomSafeHeight+10})
  5234. .reuseId('grid_item')
  5235. .layoutWeight(1)
  5236. .scrollBar(BarState.Off)
  5237. .supportAnimation(true)
  5238. .cachedCount(this.twoFingerType==1?5:this.twoFingerType==2?4:3)
  5239. .columnsTemplate(
  5240. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  5241. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  5242. )
  5243. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  5244. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  5245. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5246. .gesture(PinchGesture({ fingers: 2 })
  5247. .onActionEnd((event: GestureEvent) => {
  5248. this.setGridTwoFingers()
  5249. })
  5250. .onActionUpdate(e => {
  5251. this.scaleValue = this.pinchValue * e.scale
  5252. })
  5253. .onActionStart(e => {
  5254. }))
  5255. .enableScrollInteraction(true)
  5256. .onScrollIndex((start: number, end: number) => {
  5257. this.startIndex = start
  5258. this.endIndex = end
  5259. })
  5260. .onScrollFrameBegin((offset: number) => {
  5261. if(this.autoHideTitle){
  5262. const currentOffsetY = this.scroller.currentOffset().yOffset;
  5263. // 判断滚动方向
  5264. if (currentOffsetY > this.prevOffsetY) {
  5265. console.log("onecold 向上滚动");
  5266. this.isShowTitleBar = false
  5267. } else if (currentOffsetY < this.prevOffsetY) {
  5268. console.log("onecold 向下滚动");
  5269. this.isShowTitleBar = true
  5270. }
  5271. // 更新前一次偏移量
  5272. this.prevOffsetY = currentOffsetY;
  5273. }
  5274. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  5275. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  5276. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  5277. if (this.isScrollHide) {
  5278. this.setBarHeightHide2(offset)
  5279. } else {
  5280. this.setBarHeightNormal()
  5281. }
  5282. } else {
  5283. this.setBarHeightHide(offset)
  5284. }
  5285. return { offsetRemain: offset };
  5286. })
  5287. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  5288. .onDrop((event?: DragEvent) => {
  5289. try {
  5290. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  5291. if (dragData !== undefined) {
  5292. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  5293. if (records.length > 0) {
  5294. for (let i = 0; i < records.length; i++) {
  5295. let types = records[i].getTypes();
  5296. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  5297. const fileUriUds =
  5298. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  5299. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  5300. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  5301. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  5302. this.targetFile = fileUriUds.oriUri;
  5303. this.saveVideoDatas([this.targetFile])
  5304. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  5305. }
  5306. }
  5307. }
  5308. } else {
  5309. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  5310. }
  5311. } else {
  5312. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  5313. }
  5314. } catch (error) {
  5315. const err = error as BusinessError;
  5316. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  5317. }
  5318. })
  5319. }
  5320. @State targetFile: string = '';
  5321. setGridTwoFingers() {
  5322. this.pinchValue = this.scaleValue;
  5323. Logger.info('this.pinchValue = ' + this.pinchValue);
  5324. if (this.pinchValue >= 1) {
  5325. this.twoFingerType++
  5326. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  5327. if(this.twoFingerType >= 4){
  5328. this.twoFingerType = 4//切换成瀑布流
  5329. this.columns = 4
  5330. }
  5331. } else {
  5332. this.twoFingerType--
  5333. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  5334. if (this.twoFingerType < 1) {
  5335. this.twoFingerType = 3
  5336. this.isGridMusic = false
  5337. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5338. }
  5339. }
  5340. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5341. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5342. this.pinchValue = 1;
  5343. this.scaleValue = 1;
  5344. }
  5345. @State longItemFilePath: string = ''
  5346. @State tempLyricContent: string = ''
  5347. @State editingItem: VideoItem | null = null
  5348. @Builder
  5349. private MusicItemGrid(item: VideoItem, index: number) {
  5350. Button({ type: ButtonType.Normal, stateEffect: false }) {
  5351. Stack() {
  5352. Column() {
  5353. Image(item.pixelMapPath)
  5354. .height(this.getGridHeight())
  5355. .width(this.getGridWight())
  5356. .draggable(false)
  5357. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  5358. .autoResize(true) // 重采样,可减少内存占用
  5359. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  5360. .clip(true)
  5361. .borderRadius({
  5362. topLeft: 12,
  5363. topRight: 12,
  5364. bottomLeft: 0,
  5365. bottomRight: 0
  5366. })
  5367. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  5368. height: '99%' ,
  5369. dragBar: true,
  5370. onDisappear: () => {
  5371. this.longItemFilePath = '';
  5372. this.tempLyricContent = ''
  5373. },
  5374. showClose: true,
  5375. preferType: SheetType.CENTER ,
  5376. title: { title: '编辑标签' }
  5377. })
  5378. .draggable(false)
  5379. .opacity(this.opacityItem)// 绑定透明度
  5380. .animation({
  5381. duration: 666,
  5382. curve: 'ease-in-out' // 可选动画曲线
  5383. })
  5384. .margin({
  5385. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5386. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5387. })
  5388. Column() {
  5389. Text(this.isShowFileName&&item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5390. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5391. .maxLines(1)
  5392. .fontWeight(FontWeight.Bold)
  5393. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5394. .animation({
  5395. duration: 555,
  5396. curve: 'Linear',
  5397. })
  5398. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  5399. height: '95%',
  5400. dragBar: true,
  5401. showClose: true,
  5402. onDisappear: () => {
  5403. this.longItemFilePathDetail = '';
  5404. },
  5405. blurStyle:BlurStyle.Thin,
  5406. backgroundColor:Color.Transparent,
  5407. preferType: SheetType.CENTER ,
  5408. title: { title: '详情' }
  5409. })
  5410. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5411. $r('app.color.text_color'))
  5412. Column() {
  5413. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  5414. .fontSize(11)
  5415. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  5416. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5417. .fontColor($r('app.color.text_color'))
  5418. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  5419. .fontSize(11)
  5420. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  5421. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5422. .fontColor($r('app.color.text_color'))
  5423. Row(){
  5424. Column(){
  5425. Text(item.md5Str?.includes('Lossless')?
  5426. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5427. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5428. .padding({ top: 3,right:6,left:6,bottom:3 })
  5429. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5430. $r('app.color.text_color'))
  5431. .fontWeight(500)
  5432. .borderRadius(12)
  5433. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5434. .backgroundColor('#FFC107')
  5435. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  5436. }
  5437. .margin({ top: 2 ,right:6})
  5438. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  5439. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  5440. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  5441. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  5442. .maxLines(1)
  5443. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5444. .margin({ top: 2})
  5445. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  5446. || item.type == CommonConstants.TYPE_IS_ALBUM
  5447. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5448. .fontWeight(FontWeight.Medium)
  5449. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5450. $r('app.color.text_color'))
  5451. }
  5452. }
  5453. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  5454. }
  5455. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  5456. .width(this.getGridWight())
  5457. .justifyContent(FlexAlign.Center)
  5458. .margin({
  5459. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5460. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5461. })
  5462. }
  5463. .width(this.getGridWight())
  5464. .borderRadius(12)
  5465. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?undefined:item.pixelMapPath)
  5466. .backgroundImageSize({ height: '100%', width: '100%' })
  5467. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  5468. .animation({ curve: Curve.Sharp, duration: 300 })
  5469. Checkbox({ name: 'checkbox' + index })
  5470. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  5471. .selectedColor(this.themeColor)
  5472. .shape(CheckBoxShape.CIRCLE)
  5473. .opacity(this.isMultiSelect ? 1 : 0)
  5474. .animation({
  5475. duration: 666,
  5476. curve: 'Smooth' // 可选动画曲线
  5477. })
  5478. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  5479. Visibility.None)
  5480. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5481. .margin({ left: 20, top: 8, bottom: 8 })
  5482. .width(38)
  5483. .height(38)
  5484. }
  5485. }
  5486. .backgroundColor(Color.Transparent)
  5487. .width('100%')
  5488. .padding({ top: 15 })
  5489. .height(this.getGridAllHeight())
  5490. .onClick(() => {
  5491. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5492. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5493. this.handleFileSelection(item, !isChecked);
  5494. } else {
  5495. this.doPlay(item, index)
  5496. }
  5497. })
  5498. }
  5499. getGridAllHeight() {
  5500. let heightG = 222
  5501. switch (this.twoFingerType) {
  5502. case 1:
  5503. heightG = 143
  5504. break;
  5505. case 2:
  5506. heightG = 178
  5507. break;
  5508. case 3:
  5509. heightG = 222
  5510. break;
  5511. }
  5512. return heightG
  5513. }
  5514. getGridHeight() {
  5515. let heightG = 150
  5516. switch (this.twoFingerType) {
  5517. case 1:
  5518. heightG = 80
  5519. break;
  5520. case 2:
  5521. heightG = 110
  5522. break;
  5523. case 3:
  5524. heightG = 150
  5525. break;
  5526. }
  5527. return heightG
  5528. }
  5529. getGridWight() {
  5530. let wightG = 158
  5531. switch (this.twoFingerType) {
  5532. case 1:
  5533. wightG = 80
  5534. break;
  5535. case 2:
  5536. wightG = 110
  5537. break;
  5538. case 3:
  5539. wightG = 158
  5540. break;
  5541. }
  5542. return wightG
  5543. }
  5544. @State isShowDetail:boolean = false
  5545. @State longItemFilePathDetail:string =''
  5546. @Builder
  5547. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  5548. if(
  5549. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  5550. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5551. item.name === LocalMusic.STR_HISTORY_MUSIC)
  5552. ){
  5553. //如果是专辑和艺术家的首页,不能长按
  5554. //如果是我的收藏 最近播放等也不能长按
  5555. }else{
  5556. Scroll() {
  5557. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  5558. Menu() {
  5559. MenuItem({
  5560. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  5561. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  5562. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  5563. })
  5564. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5565. .onClick(() => {
  5566. if (item) {
  5567. this.doFav(item)
  5568. }
  5569. this.longItemFilePath = ''
  5570. })
  5571. MenuItem({
  5572. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  5573. content: '下一首播放'
  5574. })
  5575. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5576. .onClick(() => {
  5577. this.addToNextPlay(item);
  5578. this.longItemFilePath = ''
  5579. })
  5580. MenuItem({
  5581. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  5582. content: '添加到歌单'
  5583. })
  5584. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5585. .onClick(async () => {
  5586. this.longItemFilePath = ''
  5587. await this.openAddToPlaylistDialog(item)
  5588. })
  5589. MenuItem({
  5590. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  5591. content: '编辑标签'
  5592. })
  5593. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  5594. height: '99%',
  5595. dragBar: true,
  5596. showClose: true,
  5597. preferType: SheetType.CENTER ,
  5598. title: { title: '编辑标签' }
  5599. })
  5600. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5601. .onClick(async() => {
  5602. this.initEditFields(item)
  5603. this.tempLyricContent = await this.getLyricContent(item);
  5604. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  5605. this.lyricConStr = this.tempLyricContent
  5606. }
  5607. if(this.isGridMusic||this.twoFingerType==4){
  5608. this.longItemFilePath = item.filePath
  5609. }else{
  5610. this.isShowEdit = !this.isShowEdit;
  5611. }
  5612. })
  5613. MenuItem({
  5614. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  5615. content: $r('app.string.select_all')
  5616. })
  5617. .onClick(() => {
  5618. this.isMultiSelect = !this.isMultiSelect
  5619. this.longItemFilePath = ''
  5620. this.selectedFiles.push(item)
  5621. })
  5622. MenuItem({
  5623. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.cut')),
  5624. content: $r('app.string.edit_audio')
  5625. })
  5626. .bindContentCover($$this.isEditAudio, this.EditAudioBuilder(item), {
  5627. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5628. })
  5629. .onClick(() => {
  5630. this.isEditAudio = !this.isEditAudio
  5631. })
  5632. MenuItem({
  5633. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  5634. content: $r('app.string.extract_accompaniment')
  5635. })
  5636. .bindContentCover($$this.isExtractAcc, this.ExtractAccBuilder(item), {
  5637. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5638. })
  5639. .onClick(() => {
  5640. if (!Utility.isNoble()) {
  5641. this.showVipDialog()
  5642. return
  5643. }
  5644. this.isExtractAcc = !this.isExtractAcc
  5645. })
  5646. MenuItem({
  5647. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.repeat')),
  5648. content: $r('app.string.converter_audio')
  5649. })
  5650. .bindContentCover($$this.isConverter, this.ConverterBuilder(item), {
  5651. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5652. })
  5653. .onClick(() => {
  5654. if (!Utility.isNoble()) {
  5655. this.showVipDialog()
  5656. return
  5657. }
  5658. this.isConverter = !this.isConverter
  5659. })
  5660. MenuItem({
  5661. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.ai_edit')),
  5662. content: $r('app.string.vocal_separation')
  5663. })
  5664. .bindContentCover($$this.isAIVoiceSeparation, this.AiBuilder(item), {
  5665. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5666. })
  5667. .onClick(() => {
  5668. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  5669. })
  5670. MenuItem({
  5671. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_counterclockwise_clock')),
  5672. content: $r('app.string.change_tone')
  5673. })
  5674. .bindContentCover($$this.isChangeTone, this.ChangeToneBuilder(item), {
  5675. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5676. })
  5677. .onClick(() => {
  5678. this.isChangeTone = !this.isChangeTone
  5679. })
  5680. if(Utility.isVideoByExtension(item.filePath)){
  5681. MenuItem({
  5682. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.identify_song')),
  5683. content: $r('app.string.extract_audio')
  5684. })
  5685. .bindContentCover($$this.isExtractAudio, this.extractAudioFromVideoBuilder(item), {
  5686. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5687. })
  5688. .onClick(() => {
  5689. this.isExtractAudio = !this.isExtractAudio
  5690. })
  5691. }
  5692. MenuItem({
  5693. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.phone')),
  5694. content: $r('app.string.set_ring')
  5695. })
  5696. .onClick(async () => {
  5697. await PermissionUtil.activatePermission(item.filePath)
  5698. // if(item.filePath.includes(this.packName)){
  5699. setRingTone(this.context, item.filePath,item.name)
  5700. // }else{
  5701. // ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限设置铃声')
  5702. // }
  5703. this.longItemFilePath = ''
  5704. })
  5705. MenuItem({
  5706. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  5707. content: $r('app.string.rename')
  5708. })
  5709. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  5710. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5711. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  5712. .onClick(() => {
  5713. this.showReNameDialog(item, index + '', filePath)
  5714. this.longItemFilePath = ''
  5715. })
  5716. MenuItem({
  5717. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  5718. content: $r('app.string.delete')
  5719. })
  5720. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  5721. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5722. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  5723. .onClick(() => {
  5724. this.selectedFiles.push(item)
  5725. this.showWarnIsDelete()
  5726. this.longItemFilePath = ''
  5727. })
  5728. MenuItem({
  5729. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  5730. content: $r('app.string.detail')
  5731. })
  5732. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  5733. height:'95%',
  5734. dragBar: true,
  5735. showClose: true,
  5736. blurStyle:BlurStyle.Thin,
  5737. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  5738. backgroundColor:Color.Transparent,
  5739. title: { title: '详情信息' }
  5740. })
  5741. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5742. .onClick(() => {
  5743. if(this.isGridMusic||this.twoFingerType==4){
  5744. this.longItemFilePathDetail = item.filePath
  5745. }else{
  5746. this.isShowDetail = !this.isShowDetail
  5747. }
  5748. })
  5749. MenuItem({
  5750. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  5751. content: $r('app.string.share')
  5752. })
  5753. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5754. .onClick(() => {
  5755. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  5756. this.longItemFilePath = ''
  5757. })
  5758. }
  5759. .font({ size: 14, weight: FontWeight.Normal })
  5760. }
  5761. .width(180)
  5762. }
  5763. .height('auto')
  5764. .scrollBar(this.isGridMusic?BarState.On:BarState.Off)
  5765. }
  5766. }
  5767. private listMaxScrollOffsetY: number = 0
  5768. @State selectedIndex: number = -1
  5769. setlistTwoFingers() {
  5770. this.pinchValue = this.scaleValue;
  5771. Logger.info('this.pinchValue = ' + this.pinchValue);
  5772. if (this.pinchValue >= 1) {
  5773. this.twoFingerType++
  5774. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  5775. if (this.twoFingerType > 3) {
  5776. this.twoFingerType = 1
  5777. this.isGridMusic = true
  5778. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5779. }
  5780. } else {
  5781. this.twoFingerType--
  5782. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  5783. if (this.twoFingerType < 1) {
  5784. this.twoFingerType = 4
  5785. this.columns = 1
  5786. }
  5787. }
  5788. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5789. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5790. this.pinchValue = 1;
  5791. this.scaleValue = 1;
  5792. }
  5793. @Builder
  5794. getList(){
  5795. Stack() {
  5796. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  5797. this.getListView()
  5798. }
  5799. .pullDownRatio(this.ratioL)
  5800. .pullToRefresh(true)
  5801. .refreshOffset(0)
  5802. .onOffsetChange((offset: number) => {
  5803. // 越接近最大距离,下拉跟手系数越小。
  5804. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  5805. })
  5806. .onStateChange((refreshStatus: RefreshStatus) => {
  5807. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  5808. })
  5809. .onRefreshing(async () => {
  5810. if(this.modeType==0){
  5811. this.getHistoryList(false)
  5812. this.asyncCurrentPathOnlyFile()
  5813. }else if(this.modeType == 1){
  5814. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  5815. }else if(this.modeType == 2){
  5816. workerInstance.postMessage({ code: 3, data: this.context });
  5817. }else if(this.modeType == 3){
  5818. workerInstance.postMessage({ code: 4, data: this.context });
  5819. }else if(this.modeType == 4){
  5820. this.doSongListTask()
  5821. }
  5822. console.log('onRefreshing test');
  5823. })
  5824. }
  5825. }
  5826. // 扫描当前目录下的文件,不扫描子目录
  5827. asyncCurrentPathOnlyFile(){
  5828. if(this.modeType==0){
  5829. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  5830. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  5831. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  5832. if(this.modeType==0){
  5833. setTimeout(()=>{
  5834. this.isRefreshing =false
  5835. this.deleteCache(this.currentPath)
  5836. this.getSortedFiles(this.currentPath)
  5837. },500)
  5838. }
  5839. }).catch((e:object)=>{
  5840. this.isRefreshing =false
  5841. console.info("onecold task1 catch e: " + e);
  5842. })
  5843. }
  5844. }
  5845. @Builder
  5846. getListView() {
  5847. List({ scroller: this.listScroller }) {
  5848. // ListItemGroup({ header: this.coverHeader() }) {
  5849. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5850. ListItem() {
  5851. Column() {
  5852. if (item.type === CommonConstants.TYPE_IS_DIR
  5853. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  5854. this.DirItem(item, index)
  5855. } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
  5856. } else {
  5857. this.MusicItem(item, index)
  5858. }
  5859. }
  5860. .shadow(this.scaleItem === index ? {
  5861. radius: 70,
  5862. color: '#15000000',
  5863. offsetX: 0,
  5864. offsetY: 0
  5865. } :
  5866. {
  5867. radius: 0,
  5868. color: '#15000000',
  5869. offsetX: 0,
  5870. offsetY: 0
  5871. })
  5872. .animation({ curve: Curve.Sharp, duration: 300 })
  5873. }
  5874. // .transition(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }))
  5875. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.9, y: 0.9 })
  5876. .animation({ duration: 500 }),
  5877. TransitionEffect.scale({ x: 0, y: 0 })))
  5878. .clickEffect({ level: ClickEffectLevel.LIGHT })
  5879. .swipeAction((
  5880. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  5881. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  5882. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  5883. start:null,edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  5884. .onClick(() => {
  5885. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5886. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5887. this.handleFileSelection(item, !isChecked);
  5888. } else {
  5889. this.doPlay(item, index)
  5890. }
  5891. })
  5892. //拖动List关键代码开始
  5893. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  5894. .zIndex(this.dragItem === index ? 1 : 0)
  5895. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  5896. .gesture(
  5897. GestureGroup(GestureMode.Sequence,
  5898. LongPressGesture({ repeat: true })
  5899. .onAction((event?: GestureEvent) => {
  5900. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5901. this.scaleItem = index
  5902. })
  5903. })
  5904. .onActionEnd(() => {
  5905. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5906. this.scaleItem = -1
  5907. })
  5908. }),
  5909. PanGesture({ fingers: 1, direction: null, distance: 0 })
  5910. .onActionStart(() => {
  5911. this.dragItem = index // 记录当前拖动项索引
  5912. this.dragRefOffset = 0 // 重置偏移基准
  5913. })
  5914. .onActionUpdate((event: GestureEvent) => {
  5915. this.offsetY = event.offsetY - this.dragRefOffset;
  5916. this.neighborItem = -1;
  5917. let indexA = this.videoLocalList.indexOf(item);
  5918. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  5919. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  5920. let value: number = 0;
  5921. if (this.offsetY < 0) {
  5922. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  5923. this.neighborItem = indexA - 1;
  5924. this.neighborScale = 1 - value / 20;
  5925. } else if (this.offsetY > 0) {
  5926. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  5927. this.neighborItem = indexA + 1;
  5928. this.neighborScale = 1 - value / 20;
  5929. }
  5930. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  5931. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5932. this.offsetY -= this.ITEM_INTV;
  5933. this.dragRefOffset += this.ITEM_INTV;
  5934. this.itemMove(indexA, indexA + 1);
  5935. });
  5936. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  5937. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5938. this.offsetY += this.ITEM_INTV;
  5939. this.dragRefOffset -= this.ITEM_INTV;
  5940. this.itemMove(indexA, indexA - 1);
  5941. });
  5942. }
  5943. let curListOffset = this.listScroller.currentOffset()
  5944. // 获取手指信息
  5945. let fingerInfo = event.fingerList[0]
  5946. let clickPercentY =
  5947. (fingerInfo.globalY - Number(this.listArea.globalPosition.y)) / Number(this.listArea.height)
  5948. if (clickPercentY > 0.8 && !this.listScroller.isAtEnd()) {
  5949. let scrollVelocity = clickPercentY > 0.9 ? 4 : 2
  5950. if (this.listMaxScrollOffsetY - curListOffset.yOffset > scrollVelocity + 5) {
  5951. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset += scrollVelocity })
  5952. }
  5953. } else if (clickPercentY < 0.2 && curListOffset.yOffset >= 0) {
  5954. let scrollVelocity = clickPercentY < 0.1 ? 4 : 2
  5955. if (curListOffset.yOffset > scrollVelocity + 5) {
  5956. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset -= scrollVelocity })
  5957. }
  5958. }
  5959. })
  5960. .onActionEnd((event: GestureEvent) => {
  5961. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5962. this.dragItem = -1
  5963. this.neighborItem = -1
  5964. })
  5965. animateTo({
  5966. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5967. }, () => {
  5968. this.scaleItem = -1
  5969. })
  5970. })
  5971. )
  5972. .onCancel(() => {
  5973. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5974. this.dragItem = -1
  5975. this.neighborItem = -1
  5976. })
  5977. animateTo({
  5978. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5979. }, () => {
  5980. this.scaleItem = -1
  5981. })
  5982. })
  5983. ) //拖动List关键代码结束
  5984. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5985. // }
  5986. }
  5987. .onScrollStart(() => {
  5988. this.isScrolling = true
  5989. this.isShowAlphaBet = true
  5990. })
  5991. .onScrollIndex((start: number,center:number,end:number) => {
  5992. this.selectedIndex = start
  5993. if(start >= 0 && start < this.videoLocalList.length){
  5994. this.selectAlphaBetIndex = this.findAlphaBetIndex(this.videoLocalList[start])
  5995. }
  5996. })
  5997. .onScrollStop(() => {
  5998. if(this.isScrolling){
  5999. this.isScrolling = false
  6000. }
  6001. this.isShowAlphaBet = false
  6002. })
  6003. .scrollBar(BarState.Off)
  6004. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  6005. .gesture(PinchGesture({ fingers: 2 })
  6006. .onActionEnd((event: GestureEvent) => {
  6007. this.setlistTwoFingers()
  6008. })
  6009. .onActionUpdate(e => {
  6010. this.scaleValue = this.pinchValue * e.scale
  6011. })
  6012. .onActionStart(e => {
  6013. }))
  6014. .contentStartOffset(this.topSafeHeight + 55)
  6015. .scrollBar(BarState.Off)
  6016. .contentEndOffset(this.bottomBarHeight+this.bottomSafeHeight)
  6017. .cachedCount(10)
  6018. // .reuseId('list_item')
  6019. .borderRadius(20)
  6020. .layoutWeight(1)
  6021. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  6022. .lanes(
  6023. new BreakpointType<number>({
  6024. sm: 1,
  6025. md: 2,
  6026. lg: 2,
  6027. xl: 3,
  6028. xxl: 4
  6029. }).getValue(this.currentBreakpoint),
  6030. new BreakpointType<number>({
  6031. sm: 0,
  6032. md: 12,
  6033. lg: 12,
  6034. xl: 16,
  6035. xxl: 20
  6036. }).getValue(this.currentBreakpoint)
  6037. )
  6038. .onAreaChange((oldValue: Area, newValue: Area) => {
  6039. this.listArea = newValue
  6040. if (this.twoFingerType == 3) {
  6041. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  6042. } else if (this.twoFingerType == 2) {
  6043. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  6044. } else if (this.twoFingerType == 1) {
  6045. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  6046. }
  6047. })
  6048. .onScrollFrameBegin((offset: number) => {
  6049. // 获取当前滚动偏移量
  6050. if(this.autoHideTitle){
  6051. const currentOffsetY = this.listScroller.currentOffset().yOffset;
  6052. // 判断滚动方向
  6053. if (currentOffsetY > this.prevOffsetY) {
  6054. console.log("onecold 向上滚动");
  6055. this.isShowTitleBar = false
  6056. } else if (currentOffsetY < this.prevOffsetY) {
  6057. console.log("onecold 向下滚动");
  6058. this.isShowTitleBar = true
  6059. }
  6060. // 更新前一次偏移量
  6061. this.prevOffsetY = currentOffsetY;
  6062. }
  6063. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  6064. // if (this.isPhoneLan()) {
  6065. // this.setBarHeightHide(offset)
  6066. // } else
  6067. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  6068. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  6069. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  6070. if (this.isScrollHide) {
  6071. this.setBarHeightHide2(offset)
  6072. } else {
  6073. this.setBarHeightNormal()
  6074. }
  6075. } else {
  6076. this.setBarHeightHide(offset)
  6077. }
  6078. return { offsetRemain: offset };
  6079. })
  6080. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  6081. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  6082. .onDrop((event?: DragEvent) => {
  6083. try {
  6084. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  6085. if (dragData !== undefined) {
  6086. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  6087. if (records.length > 0) {
  6088. for (let i = 0; i < records.length; i++) {
  6089. let types = records[i].getTypes();
  6090. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  6091. const fileUriUds =
  6092. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  6093. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  6094. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  6095. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  6096. this.targetFile = fileUriUds.oriUri;
  6097. this.saveVideoDatas([this.targetFile])
  6098. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  6099. }
  6100. }
  6101. }
  6102. } else {
  6103. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  6104. }
  6105. } else {
  6106. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  6107. }
  6108. } catch (error) {
  6109. const err = error as BusinessError;
  6110. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  6111. }
  6112. })
  6113. }
  6114. setBarHeightNormal() {
  6115. this.hideDone = false;
  6116. this.getUIContext().animateTo({
  6117. duration: 300
  6118. }, () => {
  6119. this.bottomBarHeight = 68 + 0;
  6120. this.topBarHeight = 50 + 0;
  6121. this.barOpacity = 1;
  6122. this.barBottomOpacity = 1
  6123. this.currentYOffset = 0;
  6124. this.isHiding = false;
  6125. });
  6126. }
  6127. setBarHeightHide(offset: number) {
  6128. if (offset > 0 && !this.hideDone) {
  6129. this.currentYOffset += offset;
  6130. if (this.currentYOffset <= 100) {
  6131. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  6132. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  6133. this.barOpacity = 1 - this.currentYOffset / 100;
  6134. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  6135. } else {
  6136. this.topBarHeight = 0;
  6137. this.bottomBarHeight = 0;
  6138. this.barBottomOpacity = 0
  6139. this.barOpacity = 0;
  6140. this.hideDone = true;
  6141. }
  6142. this.isHiding = true;
  6143. }
  6144. if (offset < 0 && this.isHiding) {
  6145. this.hideDone = false;
  6146. this.getUIContext().animateTo({
  6147. duration: 300
  6148. }, () => {
  6149. this.bottomBarHeight = 68 + 0;
  6150. this.topBarHeight = 50 + 0;
  6151. this.barOpacity = 1;
  6152. this.barBottomOpacity = 1
  6153. this.currentYOffset = 0;
  6154. this.isHiding = false;
  6155. });
  6156. }
  6157. }
  6158. //这个方法没隐藏bottomBar,只隐藏topbar
  6159. setBarHeightHide2(offset: number) {
  6160. if (offset > 0 && !this.hideDone) {
  6161. this.currentYOffset += offset;
  6162. if (this.currentYOffset <= 100) {
  6163. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  6164. this.barOpacity = 1 - this.currentYOffset / 100;
  6165. } else {
  6166. this.topBarHeight = 0;
  6167. this.barOpacity = 0;
  6168. this.hideDone = true;
  6169. }
  6170. this.isHiding = true;
  6171. }
  6172. if (offset < 0 && this.isHiding) {
  6173. this.hideDone = false;
  6174. this.getUIContext().animateTo({
  6175. duration: 300
  6176. }, () => {
  6177. this.topBarHeight = 50 + 0;
  6178. this.barOpacity = 1;
  6179. this.currentYOffset = 0;
  6180. this.isHiding = false;
  6181. });
  6182. }
  6183. }
  6184. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  6185. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  6186. switch (item.type) {
  6187. case CommonConstants.TYPE_IS_DIR:
  6188. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  6189. let offsetB = 0
  6190. if(this.twoFingerType==4){
  6191. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6192. let cur = this.waterScroller.currentOffset()
  6193. if (cur && typeof cur.yOffset === 'number') {
  6194. offsetB = cur.yOffset
  6195. }
  6196. }
  6197. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  6198. }else
  6199. if (this.isGridMusic) {
  6200. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6201. let cur = this.scroller.currentOffset()
  6202. if (cur && typeof cur.yOffset === 'number') {
  6203. offsetB = cur.yOffset
  6204. }
  6205. }
  6206. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  6207. } else {
  6208. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6209. let cur = this.listScroller.currentOffset()
  6210. if (cur && typeof cur.yOffset === 'number') {
  6211. offsetB = cur.yOffset
  6212. }
  6213. }
  6214. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  6215. }
  6216. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  6217. this.showVerifyDialog()
  6218. this.currentTitleName = '私密音频'
  6219. this.currentTitleCover = $r('app.media.alt')
  6220. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  6221. this.titleName = '最近播放'
  6222. this.currentTitleCover = $r('app.media.alt')
  6223. this.currentTitleName = '最近播放'
  6224. //加载动画效果
  6225. this.updateListData(this.historyList, true)
  6226. // this.videoLocalList = this.historyList
  6227. if (ArrayUtil.isEmpty(this.historyList)) {
  6228. ToastUtil.showToast('最近播放记录空空如也')
  6229. } else {
  6230. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  6231. }
  6232. this.isHistory = true
  6233. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  6234. this.titleName = '我的收藏'
  6235. this.currentTitleName = '我的收藏'
  6236. this.currentTitleCover = $r('app.media.alt')
  6237. //加载动画效果
  6238. this.updateListData(this.favList)
  6239. if (ArrayUtil.isEmpty(this.favList)) {
  6240. ToastUtil.showToast('无音乐收藏记录')
  6241. } else {
  6242. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  6243. }
  6244. this.isFavMusic = true
  6245. } else {
  6246. this.currentTitleName = item.name
  6247. this.currentPath = item.filePath
  6248. this.currentTitleCover = $r('app.media.alt')
  6249. this.getSortedFiles(this.currentPath)
  6250. }
  6251. //进入歌单的时候的滚动位置在顶部
  6252. if(this.twoFingerType==4){
  6253. setTimeout(() => {
  6254. this.waterScroller.scrollEdge(Edge.Top)
  6255. this.scroller.scrollEdge(Edge.Top)
  6256. }, 380)
  6257. }else{
  6258. if (this.isGridMusic) {
  6259. this.scroller.scrollEdge(Edge.Top)
  6260. }else{
  6261. this.listScroller.scrollEdge(Edge.Top)
  6262. }
  6263. }
  6264. this.rightTopImage = $r('sys.symbol.chevron_left')
  6265. break;
  6266. case CommonConstants.TYPE_IS_ARTIST:
  6267. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  6268. let offsetA = 0
  6269. if(this.twoFingerType==4){
  6270. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6271. let cur = this.waterScroller.currentOffset()
  6272. if (cur && typeof cur.yOffset === 'number') {
  6273. offsetA = cur.yOffset
  6274. }
  6275. }
  6276. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  6277. }else
  6278. if (this.isGridMusic) {
  6279. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6280. let cur = this.scroller.currentOffset()
  6281. if (cur && typeof cur.yOffset === 'number') {
  6282. offsetA = cur.yOffset
  6283. }
  6284. }
  6285. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  6286. } else {
  6287. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6288. let cur = this.listScroller.currentOffset()
  6289. if (cur && typeof cur.yOffset === 'number') {
  6290. offsetA = cur.yOffset
  6291. }
  6292. }
  6293. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  6294. }
  6295. let mList = this.artistMap.get(item.name)
  6296. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  6297. Utility.doSortListAscending(mList)
  6298. this.isCanBack = true
  6299. this.titleName = item.name
  6300. this.currentTitleName = '艺术家:' + item.name
  6301. if (item.pixelMapPath) {
  6302. this.currentTitleCover = item.pixelMapPath
  6303. }
  6304. this.updateListData(mList)
  6305. }
  6306. this.rightTopImage = $r('sys.symbol.chevron_left')
  6307. //进入歌单的时候的滚动位置在顶部
  6308. if(this.twoFingerType==4){
  6309. setTimeout(() => {
  6310. this.waterScroller.scrollEdge(Edge.Top)
  6311. this.scroller.scrollEdge(Edge.Top)
  6312. }, 380)
  6313. }else{
  6314. if (this.isGridMusic) {
  6315. this.scroller.scrollEdge(Edge.Top)
  6316. }else{
  6317. this.listScroller.scrollEdge(Edge.Top)
  6318. }
  6319. }
  6320. break;
  6321. case CommonConstants.TYPE_IS_ALBUM:
  6322. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  6323. let offset = 0
  6324. if(this.twoFingerType==4){
  6325. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6326. let cur = this.waterScroller.currentOffset()
  6327. if (cur && typeof cur.yOffset === 'number') {
  6328. offset = cur.yOffset
  6329. }
  6330. }
  6331. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  6332. }else
  6333. if (this.isGridMusic) {
  6334. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6335. let cur = this.scroller.currentOffset()
  6336. if (cur && typeof cur.yOffset === 'number') {
  6337. offset = cur.yOffset
  6338. }
  6339. }
  6340. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  6341. } else {
  6342. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6343. let cur = this.listScroller.currentOffset()
  6344. if (cur && typeof cur.yOffset === 'number') {
  6345. offset = cur.yOffset
  6346. }
  6347. }
  6348. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  6349. }
  6350. let albumList = this.albumMap.get(item.name)
  6351. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  6352. Utility.doSortListAscending(albumList)
  6353. this.isCanBack = true
  6354. this.titleName = item.name
  6355. this.currentTitleName = '专辑:' + item.name
  6356. if (item.pixelMapPath) {
  6357. this.currentTitleCover = item.pixelMapPath
  6358. }
  6359. this.updateListData(albumList)
  6360. this.mScrollMap.set(item.name, this.selectedIndex)
  6361. this.rightTopImage = $r('sys.symbol.chevron_left')
  6362. }
  6363. //进入歌单的时候的滚动位置在顶部
  6364. if(this.twoFingerType==4){
  6365. setTimeout(() => {
  6366. this.waterScroller.scrollEdge(Edge.Top)
  6367. this.scroller.scrollEdge(Edge.Top)
  6368. }, 380)
  6369. }else{
  6370. if (this.isGridMusic) {
  6371. this.scroller.scrollEdge(Edge.Top)
  6372. }else{
  6373. this.listScroller.scrollEdge(Edge.Top)
  6374. }
  6375. }
  6376. break;
  6377. case CommonConstants.TYPE_IS_CSJAD:
  6378. return
  6379. break;
  6380. case CommonConstants.TYPE_LOCAL:
  6381. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  6382. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  6383. const cueTracks:CueTrack[] = cueinfo.tracks
  6384. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  6385. if(ArrayUtil.isNotEmpty(cueTracks)){
  6386. this.showCueDialog(cueTracks,cueinfo)
  6387. }
  6388. // this.showCueSheet = !this.showCueSheet
  6389. return
  6390. }
  6391. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6392. this.stop();
  6393. }
  6394. if (isOpen) {
  6395. this.currentSong = item
  6396. if (index !== undefined) {
  6397. this.curIndex = index
  6398. }
  6399. this.songList = []
  6400. this.songList.push(item)
  6401. this.sonDataSource.pushArrayData(this.songList)
  6402. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  6403. this.currentSong = item
  6404. if (index !== undefined) {
  6405. this.curIndex = index
  6406. }
  6407. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  6408. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  6409. }else {
  6410. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  6411. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  6412. this.songList = globalVideoList
  6413. this.sonDataSource.pushArrayData(this.songList)
  6414. this.currentSong = globalVideoList[this.curIndex]
  6415. }
  6416. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  6417. this.videoUrl = this.currentSong.filePath
  6418. this.name = this.currentSong.name
  6419. this.cover = this.currentSong.pixelMapPath
  6420. this.artist = this.currentSong.artist
  6421. LogUtil.info('onecold this.currentSong.cover =' + this.currentSong.pixelMapPath)
  6422. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  6423. this.startPlayOrResumePlay()
  6424. break;
  6425. case CommonConstants.TYPE_WEBDAV:
  6426. case CommonConstants.TYPE_SMB:
  6427. case CommonConstants.TYPE_NAVIDROME:
  6428. case CommonConstants.TYPE_FTP:
  6429. // 处理网络音频播放(WebDAV/SMB)
  6430. Logger.info(`heanup 处理云端音频播放: ${item.name}, URL: ${item.filePath}`)
  6431. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6432. this.stop();
  6433. }
  6434. if (isOpen) {
  6435. this.currentSong = item
  6436. if (index !== undefined) {
  6437. this.curIndex = index
  6438. }
  6439. this.songList = []
  6440. this.songList.push(item)
  6441. this.sonDataSource.pushArrayData(this.songList)
  6442. } else if (isFromSonPlayList) {
  6443. // 点击来自右下角的播放列表
  6444. this.currentSong = item
  6445. if (index !== undefined) {
  6446. this.curIndex = index
  6447. }
  6448. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  6449. Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  6450. } else {
  6451. // 从全局网络音频列表中查找
  6452. let globalVideoList = this.videoLocalList.filter(video => isRemoteCloudType(video.type)) as VideoItem[];
  6453. this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
  6454. if (this.curIndex === -1 && index !== undefined) {
  6455. this.curIndex = index;
  6456. }
  6457. this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
  6458. this.currentSong = this.songList[this.curIndex];
  6459. this.sonDataSource.pushArrayData(this.songList)
  6460. }
  6461. await this.hydrateRemoteSongFromDb(this.currentSong);
  6462. await this.hydrateRemoteSongFromDb(this.currentSong);
  6463. AppStorage.setOrCreate('currentSong', this.currentSong);
  6464. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  6465. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  6466. context: this.context,
  6467. autoParseMusicName: this.autoParseMusicName
  6468. });
  6469. Logger.info(TAG, `WebDAV URL同步构建完成(分支2): ${this.videoUrl}`);
  6470. this.name = this.currentSong.name
  6471. this.cover = this.currentSong.pixelMapPath
  6472. this.artist = this.currentSong.artist
  6473. Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 完整URL: ${this.videoUrl}`)
  6474. this.startPlayOrResumePlay()
  6475. break;
  6476. }
  6477. }
  6478. private cueComponentId: number = 0
  6479. //显示cue分轨列表对话框
  6480. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  6481. this.getUIContext().getPromptAction().openCustomDialog({
  6482. builder: () => {
  6483. this.cueComptentBuilder(cueTracks,cueinfo)
  6484. },
  6485. isModal:true,
  6486. showInSubWindow:false,
  6487. maskColor: Color.Transparent,
  6488. dialogTransition: // 设置弹窗内容显示的过渡效果
  6489. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  6490. .animation({ duration: 600, curve: Curve.Smooth }),
  6491. maskTransition: // 设置蒙层显示的过渡效果
  6492. TransitionEffect.opacity(0.5)
  6493. .animation({ duration: 600, curve: Curve.Smooth })
  6494. }).then((dialogId: number) => {
  6495. this.cueComponentId = dialogId
  6496. })
  6497. .catch((error: BusinessError) => {
  6498. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  6499. })
  6500. }
  6501. @Builder
  6502. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  6503. CueComptent({
  6504. title:cueinfo.title,
  6505. cueTracks:cueTracks,
  6506. isLongNameRoLL:this.isLongNameRoLL,
  6507. onCancel:()=>{
  6508. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  6509. },
  6510. onDoItemClick: async (item: CueTrack, index: number)=>{
  6511. //获取cueinfo对应的filePath
  6512. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  6513. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  6514. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  6515. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  6516. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  6517. if (this.currentSong){
  6518. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6519. this.stop();//播放之前先停止之前播放。
  6520. }
  6521. this.songList = globalVideoList
  6522. this.sonDataSource.pushArrayData(this.songList)
  6523. if (this.currentSong) {
  6524. try {
  6525. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  6526. context: this.context,
  6527. autoParseMusicName: this.autoParseMusicName
  6528. });
  6529. } catch (error) {
  6530. Logger.error(TAG, `CUE 点播构建播放地址失败: ${(error as Error).message}`);
  6531. this.videoUrl = this.currentSong.filePath;
  6532. }
  6533. }
  6534. this.name = item.title||this.currentSong.name
  6535. this.cover = this.currentSong.pixelMapPath
  6536. this.artist = item.performer||this.currentSong.artist
  6537. this.currentSong.name = this.name
  6538. this.currentSong.artist = this.artist
  6539. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  6540. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  6541. }
  6542. }
  6543. })
  6544. }
  6545. @State isFrontWhite: boolean = false
  6546. setShowPlayTrue(){
  6547. this.getUIContext()?.animateTo({
  6548. duration: 500,
  6549. curve: Curve.Friction
  6550. }, () => {
  6551. this.isShowPlay = true;
  6552. });
  6553. }
  6554. setShowPlayFalse(){
  6555. this.getUIContext()?.animateTo({
  6556. duration: 500,
  6557. curve: Curve.Friction
  6558. }, () => {
  6559. this.isShowPlay = false;
  6560. });
  6561. }
  6562. //打开播放页
  6563. showPlayerView() {
  6564. console.info('onecold showPlayerView this.songList'+ JSON.stringify(this.songList))
  6565. if (ArrayUtil.isNotEmpty(this.songList)) {
  6566. // this.setShowPlayTrue()
  6567. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  6568. this.initLyric(lyricPath);
  6569. this.startAutoHide();
  6570. } else {
  6571. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  6572. }
  6573. }
  6574. //打开播放列表
  6575. openPlayList(){
  6576. if (ArrayUtil.isNotEmpty(this.songList)) {
  6577. this.isShowSheet = !this.isShowSheet;
  6578. this.isFrontWhite = false
  6579. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  6580. this.scrollIndex()
  6581. } else {
  6582. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6583. }
  6584. }
  6585. scrollIndex(){
  6586. try {
  6587. setTimeout(() => {
  6588. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  6589. if(this.curIndex>60){
  6590. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  6591. }else{
  6592. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  6593. }
  6594. })
  6595. }, 123)
  6596. }catch (error) {
  6597. console.error(`onecold scrollIndex出错: ${error}`);
  6598. }
  6599. }
  6600. //播放列表布局
  6601. @Builder
  6602. PlayListSheet() {
  6603. Column() {
  6604. this.PlayList()
  6605. }
  6606. .width('100%')
  6607. .height('100%')
  6608. }
  6609. @State titleStr: string = ''
  6610. @State ablumStr: string = ''
  6611. @State artistStr: string = ''
  6612. @State lyricConStr: string = ''
  6613. @State currentEditItem: string = ''
  6614. @State yearStr: string = ''
  6615. @State trackStr: string = ''
  6616. @State genreStr: string = ''
  6617. @State imagePathStr: string = ''
  6618. @State albumArtistStr: string = ''
  6619. @State composerStr: string = ''
  6620. @State lyricistStr: string = ''
  6621. @State commentStr: string = ''
  6622. @State discStr: string = ''
  6623. doUpdateData() {
  6624. setTimeout(() => {
  6625. if (this.modeType === 0) {
  6626. this.deleteCache(this.currentPath)
  6627. this.getSortedFiles(this.currentPath)
  6628. }else if (this.modeType === 1){
  6629. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6630. }
  6631. }, 500)
  6632. }
  6633. doAllUpdateData() {
  6634. setTimeout(() => {
  6635. if (this.modeType === 0) {
  6636. this.deleteCache(this.currentPath)
  6637. this.getSortedFiles(this.currentPath)
  6638. }
  6639. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6640. workerInstance.postMessage({ code: 3, data: this.context });
  6641. workerInstance.postMessage({ code: 4, data: this.context });
  6642. }, 999)
  6643. }
  6644. //编辑信息
  6645. async doEdit(item: VideoItem) {
  6646. if (!item) {
  6647. return
  6648. }
  6649. if (StrUtil.isEmpty(this.titleStr)) {
  6650. ToastUtil.showToast('标题不能为空')
  6651. return
  6652. }
  6653. //内嵌音乐标签不能开启监听
  6654. // this.deletionWatcher?.stop();
  6655. DialogHelper.showLoadingDialog()
  6656. await PermissionUtil.activatePermission(item.filePath)
  6657. let tempOutPath = ''
  6658. // 如果不是 packName 包下的文件,则直接路径用this.currentPath
  6659. if(!item.filePath.toLowerCase().includes(this.packName)){
  6660. tempOutPath = this.currentPath + '/' + item.fileName
  6661. }
  6662. console.info('onecold tempOutPath ='+tempOutPath)
  6663. //用户更改了封面,那就内嵌下封面
  6664. if(StrUtil.isNotEmpty(this.imagePathStr)){
  6665. const resultCover:boolean = await changeMusicCover(this.context,
  6666. item.filePath,this.imagePathStr,true,tempOutPath);
  6667. this.imagePathStr = ''
  6668. if(resultCover){
  6669. ToastUtil.showToast('内嵌封面成功')
  6670. }
  6671. }
  6672. const metadata:FFMpegTags = {
  6673. title: this.titleStr,
  6674. artist: this.artistStr,
  6675. album: this.ablumStr,
  6676. TYER:this.yearStr,
  6677. genre:this.genreStr,
  6678. track:this.trackStr,
  6679. album_artist:this.albumArtistStr,
  6680. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  6681. COMPOSER:this.composerStr,
  6682. lyricist:this.lyricistStr,
  6683. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  6684. comment:this.commentStr,
  6685. disc:this.discStr,
  6686. };
  6687. let newInput = item.filePath
  6688. //内嵌标签歌路径如果不是包含包名,输入newInput要赋值tempOutPath,然后tempOutPath为空
  6689. if(!item.filePath.toLowerCase().includes(this.packName)&&FileUtil.accessSync(tempOutPath)){
  6690. newInput = tempOutPath
  6691. tempOutPath = ''
  6692. }
  6693. const isWav:boolean = newInput.toLowerCase().endsWith('.wav');
  6694. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  6695. const result:boolean = await repairAudioMetadata(
  6696. newInput,
  6697. this.lyricConStr,
  6698. metadata,
  6699. true,
  6700. tempOutPath
  6701. );
  6702. if (result||isWav) {
  6703. if(!item.filePath.includes(this.packName)){
  6704. //内嵌成功的歌路径如果不是包含包名,则要入库
  6705. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newInput,
  6706. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  6707. this.table.insert(newItem, (id: number) => {
  6708. //加入数据库
  6709. if(this.modeType==0){
  6710. this.deleteCache(this.currentPath)
  6711. this.getSortedFiles(this.currentPath)
  6712. }
  6713. });
  6714. }
  6715. const task = new taskpool.Task(
  6716. updateInfoDb,
  6717. this.context,
  6718. item.filePath,
  6719. this.titleStr,
  6720. this.artistStr,
  6721. this.ablumStr,
  6722. this.lyricConStr,
  6723. this.yearStr,this.genreStr,
  6724. this.trackStr,this.albumArtistStr,
  6725. this.composerStr, this.lyricistStr,
  6726. this.commentStr,this.discStr
  6727. );
  6728. taskpool.execute(task, taskpool.Priority.HIGH).then((result) => {
  6729. if (result) {
  6730. console.log(" onecold 编辑信息成功,数据库已同步");
  6731. if(isWav){
  6732. ToastUtil.showToast('wav格式有可能内嵌失败,但是编辑信息成功')
  6733. }else{
  6734. ToastUtil.showToast('内嵌音乐标签成功')
  6735. }
  6736. this.isShowMoreView = false
  6737. this.name = this.titleStr
  6738. this.syncEditedFields(item)
  6739. if (item.filePath == this.currentSong?.filePath) {
  6740. this.currentSong.name = this.titleStr
  6741. this.artist = this.artistStr
  6742. this.currentSong.artist = this.artistStr
  6743. this.currentSong.album = this.ablumStr
  6744. this.currentSong.year = this.yearStr
  6745. this.currentSong.genre = this.genreStr
  6746. this.currentSong.track = this.trackStr
  6747. this.currentSong.lyricContent = this.lyricConStr
  6748. this.currentSong.ALBUMARTIST = this.albumArtistStr
  6749. this.currentSong.COMPOSER = this.composerStr
  6750. this.currentSong.LYRICIST = this.lyricistStr
  6751. this.currentSong.COMMENT = this.commentStr
  6752. }
  6753. this.syncListsAfterEdit(item.filePath)
  6754. this.doUpateEditedFields(item)
  6755. //this.doUpdateData()
  6756. } else {
  6757. // ToastUtil.showToast('保存失败' + error?.toString())
  6758. console.error(" onecold 编辑信息数据库失败 ");
  6759. }
  6760. // 关闭进度条
  6761. DialogHelper.closeLoading();
  6762. }).catch((error: Error) => {
  6763. // 关闭进度条
  6764. DialogHelper.closeLoading();
  6765. console.error('onecold Subtitle sync failed:', error);
  6766. });
  6767. console.log(' onecold 元数据标签更新成功,');
  6768. } else {
  6769. // 关闭进度条
  6770. DialogHelper.closeLoading();
  6771. ToastUtil.showToast('内嵌音乐标签失败')
  6772. console.log('onecold 内嵌音乐标签失败');
  6773. }
  6774. this.longItemFilePath = ''
  6775. this.tempLyricContent = ''
  6776. this.isShowEdit = false
  6777. }
  6778. // 内嵌标签更新当前内嵌的Item
  6779. async doUpateEditedFields(item: VideoItem) {
  6780. // 找到当前项在 videoLocalList 中的索引
  6781. const index = this.videoLocalList.findIndex(video => video.filePath === item.filePath);
  6782. if (index !== -1) {
  6783. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  6784. const updatedItem = await this.table.queryVideoByFilePath(item.filePath)
  6785. // 只有当查询结果不为 null 时才更新列表
  6786. if (updatedItem !== null) {
  6787. // 更新 videoLocalList 中的项(通过创建新数组触发响应式更新)
  6788. this.videoLocalList = [
  6789. ...this.videoLocalList.slice(0, index),
  6790. updatedItem,
  6791. ...this.videoLocalList.slice(index + 1)
  6792. ];
  6793. // 同步更新 LazyDataSource
  6794. this.dataSource.pushArrayData(this.videoLocalList)
  6795. } else {
  6796. ToastUtil.showToast('未找到更新的数据');
  6797. }
  6798. }
  6799. DialogHelper.closeLoading();
  6800. }
  6801. @Builder
  6802. editSheet(item: VideoItem) {
  6803. Scroll() {
  6804. Column() {
  6805. this.editDetail(item)
  6806. }
  6807. }
  6808. .width('100%')
  6809. .height('100%')
  6810. }
  6811. @Builder
  6812. editDetail(item: VideoItem) {
  6813. Column() {
  6814. if (item) {
  6815. Row() {
  6816. Stack() {
  6817. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  6818. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  6819. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  6820. item.pixelMapPath)
  6821. .fillColor(this.themeColor)
  6822. .height(88)
  6823. .width(88)
  6824. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  6825. .borderRadius(12)
  6826. .clip(true)
  6827. .opacity(this.opacityItem)// 绑定透明度
  6828. .margin({ left: 25 })
  6829. }
  6830. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  6831. .onClick(async () => {
  6832. const imagePath:string | undefined = await this.goSelectImage(item);
  6833. if (imagePath) {
  6834. //用户更改过图片
  6835. this.imagePathStr = imagePath
  6836. }
  6837. })
  6838. .width('28%')
  6839. Row() {
  6840. Column() {
  6841. Text(item.name)
  6842. .fontSize(17)
  6843. .maxLines(1)
  6844. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6845. .animation({
  6846. duration: 555,
  6847. curve: 'Linear',
  6848. })
  6849. .fontColor(this.themeColor)
  6850. .margin({ left: 8 })
  6851. Row() {
  6852. Text(item.artist)
  6853. .fontSize(14)
  6854. .maxLines(1)
  6855. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6856. .padding({ top: 8 })
  6857. .fontColor(this.themeColor)
  6858. .margin({ left: 8 })
  6859. }
  6860. }
  6861. .height('100%')
  6862. .width(100)
  6863. .layoutWeight(1)
  6864. .justifyContent(FlexAlign.Center)
  6865. .alignItems(HorizontalAlign.Start)
  6866. Column() {
  6867. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6868. Row(){
  6869. SymbolGlyph($r('sys.symbol.picture'))
  6870. .fontSize(18)
  6871. .fontColor([Color.White])
  6872. Text('获取封面')
  6873. .margin({ left: 4 })
  6874. .fontSize(11)
  6875. .fontColor(Color.White)
  6876. .fontWeight(480)
  6877. .textAlign(TextAlign.Center)
  6878. }
  6879. .justifyContent(FlexAlign.Center)
  6880. }
  6881. .height(38)
  6882. .width(100)
  6883. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6884. .backgroundColor(this.themeColor)
  6885. .stateEffect(true)
  6886. .margin({ right: 35 })
  6887. .onClick(async () => {
  6888. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  6889. this.showTipsDialog();
  6890. return; // Return empty string when no API is configured
  6891. }
  6892. const imagePath:string | undefined = await this.doSearchCover(item,
  6893. this.titleStr,this.artistStr);
  6894. console.info('onecold imagePath = '+imagePath)
  6895. if (StrUtil.isNotEmpty(imagePath)) {
  6896. //用户更改过图片
  6897. this.imagePathStr = imagePath
  6898. ToastUtil.showToast('获取封面成功')
  6899. }else{
  6900. ToastUtil.showToast('获取封面失败,请重试')
  6901. }
  6902. })
  6903. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6904. Row(){
  6905. SymbolGlyph($r('sys.symbol.input_mode'))
  6906. .fontSize(18)
  6907. .fontColor([Color.White])
  6908. Text('获取歌词')
  6909. .margin({ left: 4 })
  6910. .fontSize(11)
  6911. .fontColor(Color.White)
  6912. .fontWeight(480)
  6913. .textAlign(TextAlign.Center)
  6914. }
  6915. .justifyContent(FlexAlign.Center)
  6916. }
  6917. .height(38)
  6918. .width(100)
  6919. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6920. .backgroundColor(this.themeColor)
  6921. .stateEffect(true)
  6922. .margin({ top: 9, right: 35 })
  6923. .onClick(async () => {
  6924. //判断有没有设置api
  6925. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  6926. if (StrUtil.isEmpty(apiUrl)) {
  6927. this.isLyricSetting = false
  6928. this.showTipsDialog()
  6929. return
  6930. }
  6931. let res: string | undefined = await getApiLyric(apiUrl,
  6932. this.titleStr, this.artistStr, false);
  6933. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  6934. this.lyricConStr = res;
  6935. ToastUtil.showToast('获取歌词成功')
  6936. }else{
  6937. ToastUtil.showToast('获取歌词失败,请重试')
  6938. }
  6939. })
  6940. }
  6941. .justifyContent(FlexAlign.Start)
  6942. }
  6943. .height('100%')
  6944. .justifyContent(FlexAlign.Start)
  6945. .layoutWeight(1)
  6946. }
  6947. .width('100%')
  6948. .height(98)
  6949. Row() {
  6950. Text('标题:')
  6951. .fontSize(14)
  6952. .fontColor($r('app.color.text_color'))
  6953. .margin({ left: 22 })
  6954. TextInput({ text: this.titleStr||item.name })
  6955. .height(40)
  6956. .maxLines(1)
  6957. .fontSize(14)
  6958. .layoutWeight(1)
  6959. .fontColor($r('app.color.text_color'))
  6960. .margin({ right: 15, left: 10 })
  6961. .onChange((val: string) => {
  6962. this.titleStr = val
  6963. })
  6964. Button('修复乱码',{ type: ButtonType.Capsule, stateEffect: true})
  6965. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6966. .backgroundColor(this.themeColor)
  6967. .fontSize(10)
  6968. .margin({ right: 20})
  6969. .onClick(async () => {
  6970. let hwTags = await extractHwMediaMetadata(item.filePath)
  6971. let artist = hwTags?.artist|| '';
  6972. let title = hwTags?.title|| '';
  6973. let album = hwTags?.album|| '';
  6974. console.info('onecold 乱码修正 artist='+artist);
  6975. console.info('onecold 乱码修正 title='+title);
  6976. console.info('onecold 乱码修正 album='+album);
  6977. this.titleStr = title;
  6978. this.artistStr = artist;
  6979. this.ablumStr = album;
  6980. })
  6981. }
  6982. .width('100%')
  6983. .margin({ top: 10, bottom: 10 })
  6984. .justifyContent(FlexAlign.Start)
  6985. Row() {
  6986. Text('艺术家:')
  6987. .fontSize(14)
  6988. .fontColor($r('app.color.text_color'))
  6989. .margin({ left: 22 })
  6990. TextInput({ text: this.artistStr||item.artist })
  6991. .height(40)
  6992. .maxLines(1)
  6993. .fontSize(14)
  6994. .layoutWeight(1)
  6995. .fontColor($r('app.color.text_color'))
  6996. .margin({ right: 20, left: 10 })
  6997. .onChange((val: string) => {
  6998. this.artistStr = val
  6999. })
  7000. }
  7001. .width('100%')
  7002. .margin({ top: 10, bottom: 10 })
  7003. .justifyContent(FlexAlign.Start)
  7004. Row() {
  7005. Text('专辑名:')
  7006. .fontSize(14)
  7007. .fontColor($r('app.color.text_color'))
  7008. .margin({ left: 22 })
  7009. TextInput({ text: this.ablumStr||item.album })
  7010. .height(40)
  7011. .maxLines(1)
  7012. .fontSize(14)
  7013. .layoutWeight(1)
  7014. .fontColor($r('app.color.text_color'))
  7015. .margin({ right: 20, left: 10 })
  7016. .onChange((val: string) => {
  7017. this.ablumStr = val
  7018. })
  7019. }
  7020. .width('100%')
  7021. .margin({ top: 10, bottom: 10 })
  7022. .justifyContent(FlexAlign.Start)
  7023. Row() {
  7024. Column(){
  7025. Column(){
  7026. Text('歌词:')
  7027. .fontSize(14)
  7028. .fontColor($r('app.color.text_color'))
  7029. .margin({ top:9,left: 22 })
  7030. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7031. SymbolGlyph($r('sys.symbol.trash_fill'))
  7032. .fontSize(25)
  7033. .alignSelf(ItemAlign.Center)
  7034. .margin({ left: 22,top:25})
  7035. }
  7036. .backgroundColor(Color.Transparent)
  7037. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7038. Visibility.None:Visibility.Visible)
  7039. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7040. .onClick(()=>{
  7041. this.lyricConStr = ''
  7042. this.lyricContent = ''
  7043. this.tempLyricContent = ''
  7044. })
  7045. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7046. SymbolGlyph($r('sys.symbol.plus'))
  7047. .fontSize(25)
  7048. .alignSelf(ItemAlign.Center)
  7049. .margin({ left: 22,top:25})
  7050. }
  7051. .backgroundColor(Color.Transparent)
  7052. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7053. .onClick( ()=>{
  7054. this.callFilePickerSelectFileForLyric()
  7055. })
  7056. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7057. SymbolGlyph($r('sys.symbol.traditional_square'))
  7058. .fontSize(25)
  7059. .alignSelf(ItemAlign.Center)
  7060. .margin({ left: 22,top:25})
  7061. }
  7062. .backgroundColor(Color.Transparent)
  7063. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7064. Visibility.None:Visibility.Visible)
  7065. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7066. .onClick( ()=>{
  7067. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  7068. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  7069. })
  7070. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7071. Image($r('app.media.jianti'))
  7072. .height(25)
  7073. .fillColor($r('app.color.text_color'))
  7074. .alignSelf(ItemAlign.Center)
  7075. .margin({ left: 22,top:25})
  7076. }
  7077. .backgroundColor(Color.Transparent)
  7078. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7079. Visibility.None:Visibility.Visible)
  7080. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7081. .onClick( ()=>{
  7082. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  7083. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  7084. })
  7085. }
  7086. .layoutWeight(1)
  7087. }
  7088. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  7089. this.tempLyricContent })
  7090. .type(TextAreaType.NORMAL)
  7091. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  7092. .fontSize(14)
  7093. .layoutWeight(1)
  7094. .fontColor($r('app.color.text_color'))
  7095. .margin({ right: 20, left: 10 })
  7096. .onChange((val: string) => {
  7097. this.lyricConStr = val
  7098. })
  7099. }
  7100. .width('100%')
  7101. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  7102. .margin({ top: 10, bottom: 10 })
  7103. .justifyContent(FlexAlign.Start)
  7104. Row() {
  7105. Text('年份:')
  7106. .fontSize(14)
  7107. .fontColor($r('app.color.text_color'))
  7108. .margin({ left: 22 })
  7109. TextInput({ text: item.year })
  7110. .height(40)
  7111. .maxLines(1)
  7112. .fontSize(14)
  7113. .type(InputType.Number)
  7114. .layoutWeight(1)
  7115. .fontColor($r('app.color.text_color'))
  7116. .margin({ right: 20, left: 10 })
  7117. .onChange((val: string) => {
  7118. this.yearStr = val
  7119. })
  7120. }
  7121. .width('100%')
  7122. .margin({ top: 10, bottom: 10 })
  7123. .justifyContent(FlexAlign.Start)
  7124. Row() {
  7125. Text('音轨号:')
  7126. .fontSize(14)
  7127. .fontColor($r('app.color.text_color'))
  7128. .margin({ left: 22 })
  7129. TextInput({ text:item.track=='未知'?'': item.track })
  7130. .height(40)
  7131. .maxLines(1)
  7132. .fontSize(14)
  7133. .type(InputType.Number)
  7134. .layoutWeight(1)
  7135. .fontColor($r('app.color.text_color'))
  7136. .margin({ right: 20, left: 10 })
  7137. .onChange((val: string) => {
  7138. this.trackStr = val
  7139. })
  7140. }
  7141. .width('100%')
  7142. .margin({ top: 10, bottom: 10 })
  7143. .justifyContent(FlexAlign.Start)
  7144. Row() {
  7145. Text('碟号:')
  7146. .fontSize(14)
  7147. .fontColor($r('app.color.text_color'))
  7148. .margin({ left: 22 })
  7149. TextInput({ text:item.disc })
  7150. .height(40)
  7151. .maxLines(1)
  7152. .fontSize(14)
  7153. .type(InputType.Number)
  7154. .layoutWeight(1)
  7155. .fontColor($r('app.color.text_color'))
  7156. .margin({ right: 20, left: 10 })
  7157. .onChange((val: string) => {
  7158. this.discStr = val
  7159. })
  7160. }
  7161. .width('100%')
  7162. .margin({ top: 10, bottom: 10 })
  7163. .justifyContent(FlexAlign.Start)
  7164. Row() {
  7165. Text('风格:')
  7166. .fontSize(14)
  7167. .fontColor($r('app.color.text_color'))
  7168. .margin({ left: 22 })
  7169. TextInput({ text: item.genre })
  7170. .height(40)
  7171. .maxLines(1)
  7172. .fontSize(14)
  7173. .layoutWeight(1)
  7174. .fontColor($r('app.color.text_color'))
  7175. .margin({ right: 20, left: 10 })
  7176. .onChange((val: string) => {
  7177. this.genreStr = val
  7178. })
  7179. }
  7180. .width('100%')
  7181. .margin({ top: 10, bottom: 10 })
  7182. .justifyContent(FlexAlign.Start)
  7183. Row() {
  7184. Text('专辑艺术家:')
  7185. .fontSize(14)
  7186. .fontColor($r('app.color.text_color'))
  7187. .margin({ left: 22 })
  7188. TextInput({ text: item.ALBUMARTIST })
  7189. .height(40)
  7190. .maxLines(1)
  7191. .fontSize(14)
  7192. .layoutWeight(1)
  7193. .fontColor($r('app.color.text_color'))
  7194. .margin({ right: 20, left: 10 })
  7195. .onChange((val: string) => {
  7196. this.albumArtistStr = val
  7197. })
  7198. }
  7199. .width('100%')
  7200. .margin({ top: 10, bottom: 10 })
  7201. .justifyContent(FlexAlign.Start)
  7202. Row() {
  7203. Text('作曲:')
  7204. .fontSize(14)
  7205. .fontColor($r('app.color.text_color'))
  7206. .margin({ left: 22 })
  7207. TextInput({ text: item.COMPOSER })
  7208. .height(40)
  7209. .maxLines(1)
  7210. .fontSize(14)
  7211. .layoutWeight(1)
  7212. .fontColor($r('app.color.text_color'))
  7213. .margin({ right: 20, left: 10 })
  7214. .onChange((val: string) => {
  7215. this.composerStr = val
  7216. })
  7217. }
  7218. .width('100%')
  7219. .margin({ top: 10, bottom: 10 })
  7220. .justifyContent(FlexAlign.Start)
  7221. Row() {
  7222. Text('作词:')
  7223. .fontSize(14)
  7224. .fontColor($r('app.color.text_color'))
  7225. .margin({ left: 22 })
  7226. TextInput({ text: item.LYRICIST })
  7227. .height(40)
  7228. .maxLines(1)
  7229. .fontSize(14)
  7230. .layoutWeight(1)
  7231. .fontColor($r('app.color.text_color'))
  7232. .margin({ right: 20, left: 10 })
  7233. .onChange((val: string) => {
  7234. this.lyricistStr = val
  7235. })
  7236. }
  7237. .width('100%')
  7238. .margin({ top: 10, bottom: 10 })
  7239. .justifyContent(FlexAlign.Start)
  7240. Row() {
  7241. Text('注释:')
  7242. .fontSize(14)
  7243. .fontColor($r('app.color.text_color'))
  7244. .margin({ left: 22 })
  7245. TextInput({ text: item.COMMENT })
  7246. .height(40)
  7247. .maxLines(1)
  7248. .fontSize(14)
  7249. .layoutWeight(1)
  7250. .fontColor($r('app.color.text_color'))
  7251. .margin({ right: 20, left: 10 })
  7252. .onChange((val: string) => {
  7253. this.commentStr = val
  7254. })
  7255. }
  7256. .width('100%')
  7257. .margin({ top: 10, bottom: 10 })
  7258. .justifyContent(FlexAlign.Start)
  7259. Row() {
  7260. Button('保存')
  7261. .fontColor(Color.White)
  7262. .layoutWeight(1)
  7263. .height(50)
  7264. .width(100)
  7265. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7266. .backgroundColor(this.themeColor)
  7267. .stateEffect(true)
  7268. .margin({ right: 20, bottom: 20 })
  7269. .onClick(async () => {
  7270. this.doEdit(item)
  7271. })
  7272. Button('取消')
  7273. .fontColor(Color.White)
  7274. .layoutWeight(1)
  7275. .height(50)
  7276. .width(100)
  7277. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7278. .backgroundColor(this.themeColor)
  7279. .stateEffect(true)
  7280. .margin({ left: 20, bottom: 20 })
  7281. .onClick(async () => {
  7282. if(this.isGridMusic){
  7283. this.longItemFilePath =''
  7284. }else{
  7285. this.isShowEdit = false
  7286. }
  7287. this.setEditStrEmpty()
  7288. if(this.isShowPlay){
  7289. this.isShowEdit = false
  7290. }
  7291. })
  7292. }
  7293. .margin({
  7294. left: 38,
  7295. right: 38,
  7296. top: 10,
  7297. bottom: 10
  7298. })
  7299. .width(250)
  7300. .height(60)
  7301. }
  7302. }
  7303. .margin({ bottom: 20 })
  7304. }
  7305. setEditStrEmpty(){
  7306. this.imagePathStr = ''
  7307. this.lyricConStr = ''
  7308. this.artistStr = ''
  7309. this.titleStr = ''
  7310. this.ablumStr = ''
  7311. this.genreStr = ''
  7312. this.yearStr = ''
  7313. this.trackStr = ''
  7314. this.albumArtistStr = ''
  7315. this.composerStr = ''
  7316. this.lyricistStr = ''
  7317. this.commentStr = ''
  7318. this.discStr = ''
  7319. }
  7320. initEditFields(item?: VideoItem) {
  7321. if (!item) {
  7322. this.setEditStrEmpty()
  7323. return
  7324. }
  7325. this.imagePathStr = ''
  7326. this.titleStr = item.name ?? ''
  7327. this.artistStr = item.artist ?? ''
  7328. this.ablumStr = item.album ?? ''
  7329. this.genreStr = item.genre ?? ''
  7330. this.yearStr = item.year ?? ''
  7331. this.trackStr = item.track ?? ''
  7332. this.albumArtistStr = item.ALBUMARTIST ?? ''
  7333. this.composerStr = item.COMPOSER ?? ''
  7334. this.lyricistStr = item.LYRICIST ?? ''
  7335. this.commentStr = item.COMMENT ?? ''
  7336. this.discStr = item.disc ?? ''
  7337. this.lyricConStr = item.lyricContent ?? ''
  7338. }
  7339. private syncEditedFields(target?: VideoItem) {
  7340. if (!target) {
  7341. return
  7342. }
  7343. target.name = this.titleStr
  7344. target.artist = this.artistStr
  7345. target.album = this.ablumStr
  7346. target.lyricContent = this.lyricConStr
  7347. target.year = this.yearStr
  7348. target.genre = this.genreStr
  7349. target.track = this.trackStr
  7350. target.ALBUMARTIST = this.albumArtistStr
  7351. target.COMPOSER = this.composerStr
  7352. target.LYRICIST = this.lyricistStr
  7353. target.COMMENT = this.commentStr
  7354. target.disc = this.discStr
  7355. }
  7356. private replaceItemInList(list: Array<VideoItem> | undefined, filePath: string,
  7357. apply?: (next: Array<VideoItem>) => void) {
  7358. if (!list || ArrayUtil.isEmpty(list)) {
  7359. return
  7360. }
  7361. const index = list.findIndex((video: VideoItem) => video.filePath === filePath)
  7362. if (index < 0) {
  7363. return
  7364. }
  7365. const nextList = [...list]
  7366. this.syncEditedFields(nextList[index])
  7367. apply?.(nextList)
  7368. }
  7369. private syncListsAfterEdit(filePath: string) {
  7370. this.replaceItemInList(this.videoLocalList, filePath, (next: Array<VideoItem>) => {
  7371. this.videoLocalList = next
  7372. this.dataSource.pushArrayData(next)
  7373. })
  7374. this.replaceItemInList(this.songList, filePath, (next: Array<VideoItem>) => {
  7375. this.songList = next
  7376. this.sonDataSource.pushArrayData(next)
  7377. })
  7378. this.replaceItemInList(this.favList, filePath, (next: Array<VideoItem>) => {
  7379. this.favList = next
  7380. })
  7381. this.replaceItemInList(this.historyList, filePath, (next: Array<VideoItem>) => {
  7382. this.historyList = next
  7383. })
  7384. this.replaceItemInList(this.currentSongList, filePath, (next: Array<VideoItem>) => {
  7385. this.currentSongList = next
  7386. })
  7387. this.replaceItemInList(this.mediaKuList, filePath, (next: Array<VideoItem>) => {
  7388. this.mediaKuList = next
  7389. })
  7390. this.replaceItemInList(this.filteredList, filePath, (next: Array<VideoItem>) => {
  7391. this.filteredList = next
  7392. })
  7393. this.replaceItemInList(this.artistList, filePath, (next: Array<VideoItem>) => {
  7394. this.artistList = next
  7395. })
  7396. this.replaceItemInList(this.albumList, filePath, (next: Array<VideoItem>) => {
  7397. this.albumList = next
  7398. })
  7399. this.listRefreshKey++
  7400. }
  7401. private refreshLazyListViews(mainListUpdated: boolean, playlistUpdated: boolean): void {
  7402. if (!mainListUpdated && !playlistUpdated) {
  7403. return;
  7404. }
  7405. this.listRefreshKey++;
  7406. if (mainListUpdated) {
  7407. this.dataSource.notifyDataReload();
  7408. }
  7409. if (playlistUpdated) {
  7410. this.sonDataSource.notifyDataReload();
  7411. }
  7412. }
  7413. @Builder
  7414. detailSheet(item:VideoItem) {
  7415. Scroll() {
  7416. Column() {
  7417. this.songDetail(item)
  7418. }
  7419. }
  7420. .width('100%')
  7421. .height('100%')
  7422. }
  7423. @Builder
  7424. songDetail(currentItem:VideoItem) {
  7425. Column() {
  7426. if (currentItem) {
  7427. Row() {
  7428. Stack() {
  7429. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.music_red') :
  7430. currentItem.pixelMapPath)
  7431. .fillColor(this.themeColor)
  7432. .height(80)
  7433. .width(80)
  7434. .borderRadius(10)
  7435. .opacity(this.opacityItem)// 绑定透明度
  7436. .margin({ left: 22 })
  7437. }
  7438. Column() {
  7439. Column() {
  7440. Text(currentItem.name)
  7441. .fontSize(16)
  7442. .maxLines(1)
  7443. .animation({
  7444. duration: 555,
  7445. curve: 'Linear',
  7446. })
  7447. .fontColor($r('app.color.text_color'))
  7448. .margin({ left: 15 })
  7449. }
  7450. .height('100%')
  7451. .width('100%')
  7452. .justifyContent(FlexAlign.Center)
  7453. .alignItems(HorizontalAlign.Start)
  7454. }
  7455. .height('100%')
  7456. }
  7457. .width('100%')
  7458. .height(90)
  7459. .justifyContent(FlexAlign.SpaceBetween)
  7460. Row() {
  7461. Text('艺术家:')
  7462. .fontSize(14)
  7463. .fontColor($r('app.color.text_color'))
  7464. .margin({ left: 22 })
  7465. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  7466. .fontSize(14)
  7467. .fontColor($r('app.color.text_color'))
  7468. .margin({ left: 10 })
  7469. .layoutWeight(1)
  7470. }
  7471. .width('100%')
  7472. .margin({ top: 10, bottom: 10 })
  7473. .justifyContent(FlexAlign.Start)
  7474. Row() {
  7475. Text('专辑名:')
  7476. .fontSize(14)
  7477. .fontColor($r('app.color.text_color'))
  7478. .margin({ left: 22 })
  7479. Text(currentItem?.album ?currentItem.album : '未知专辑')
  7480. .fontSize(14)
  7481. .margin({ left: 10 })
  7482. .fontColor($r('app.color.text_color'))
  7483. .layoutWeight(1)
  7484. }
  7485. .width('100%')
  7486. .margin({ top: 10, bottom: 10 })
  7487. .justifyContent(FlexAlign.Start)
  7488. Row() {
  7489. Text('时长:')
  7490. .fontSize(14)
  7491. .fontColor($r('app.color.text_color'))
  7492. .margin({ left: 22 })
  7493. Text(StrUtil.isEmpty(currentItem.duration)?
  7494. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  7495. .fontSize(14)
  7496. .margin({ left: 10 })
  7497. .fontColor($r('app.color.text_color'))
  7498. .layoutWeight(1)
  7499. }
  7500. .width('100%')
  7501. .margin({ top: 10, bottom: 10 })
  7502. .justifyContent(FlexAlign.Start)
  7503. Row() {
  7504. Text('采样率:')
  7505. .fontSize(14)
  7506. .fontColor($r('app.color.text_color'))
  7507. .margin({ left: 22 })
  7508. Text(Utility.convertToKHz(currentItem.sampleRate))
  7509. .fontSize(14)
  7510. .margin({ left: 10 })
  7511. .fontColor($r('app.color.text_color'))
  7512. .layoutWeight(1)
  7513. }
  7514. .width('100%')
  7515. .margin({ top: 10, bottom: 10 })
  7516. .justifyContent(FlexAlign.Start)
  7517. Row() {
  7518. Text('比特率:')
  7519. .fontSize(14)
  7520. .fontColor($r('app.color.text_color'))
  7521. .margin({ left: 22 })
  7522. Text(currentItem.bit_rate)
  7523. .fontSize(14)
  7524. .margin({ left: 10 })
  7525. .fontColor($r('app.color.text_color'))
  7526. .layoutWeight(1)
  7527. }
  7528. .width('100%')
  7529. .margin({ top: 10, bottom: 10 })
  7530. .justifyContent(FlexAlign.Start)
  7531. Row() {
  7532. Text('位深:')
  7533. .fontSize(14)
  7534. .fontColor($r('app.color.text_color'))
  7535. .margin({ left: 22 })
  7536. Text(`${currentItem.bits_per_raw_sample} bits`)
  7537. .fontSize(14)
  7538. .margin({ left: 10 })
  7539. .fontColor($r('app.color.text_color'))
  7540. .layoutWeight(1)
  7541. }
  7542. .width('100%')
  7543. .margin({ top: 10, bottom: 10 })
  7544. .justifyContent(FlexAlign.Start)
  7545. Row() {
  7546. Text('声道:')
  7547. .fontSize(14)
  7548. .fontColor($r('app.color.text_color'))
  7549. .margin({ left: 22 })
  7550. Text(`${currentItem.channels}`)
  7551. .fontSize(14)
  7552. .margin({ left: 10 })
  7553. .fontColor($r('app.color.text_color'))
  7554. .layoutWeight(1)
  7555. }
  7556. .width('100%')
  7557. .margin({ top: 10, bottom: 10 })
  7558. .justifyContent(FlexAlign.Start)
  7559. Row() {
  7560. Text('声道布局:')
  7561. .fontSize(14)
  7562. .fontColor($r('app.color.text_color'))
  7563. .margin({ left: 22 })
  7564. Text(`${currentItem.channel_layout}`)
  7565. .fontSize(14)
  7566. .margin({ left: 10 })
  7567. .fontColor($r('app.color.text_color'))
  7568. .layoutWeight(1)
  7569. }
  7570. .width('100%')
  7571. .margin({ top: 10, bottom: 10 })
  7572. .justifyContent(FlexAlign.Start)
  7573. Row() {
  7574. Text('起始播放点:')
  7575. .fontSize(14)
  7576. .fontColor($r('app.color.text_color'))
  7577. .margin({ left: 22 })
  7578. Text(`${currentItem.start_time}`)
  7579. .fontSize(14)
  7580. .margin({ left: 10 })
  7581. .fontColor($r('app.color.text_color'))
  7582. .layoutWeight(1)
  7583. }
  7584. .width('100%')
  7585. .margin({ top: 10, bottom: 10 })
  7586. .justifyContent(FlexAlign.Start)
  7587. Row() {
  7588. Text('风格:')
  7589. .fontSize(14)
  7590. .fontColor($r('app.color.text_color'))
  7591. .margin({ left: 22 })
  7592. Text(currentItem.genre)
  7593. .fontSize(14)
  7594. .margin({ left: 10 })
  7595. .fontColor($r('app.color.text_color'))
  7596. .layoutWeight(1)
  7597. }
  7598. .width('100%')
  7599. .margin({ top: 10, bottom: 10 })
  7600. .justifyContent(FlexAlign.Start)
  7601. Row() {
  7602. Text('发行时间:')
  7603. .fontSize(14)
  7604. .fontColor($r('app.color.text_color'))
  7605. .margin({ left: 22 })
  7606. Text(currentItem.year)
  7607. .fontSize(14)
  7608. .margin({ left: 10 })
  7609. .fontColor($r('app.color.text_color'))
  7610. .layoutWeight(1)
  7611. }
  7612. .width('100%')
  7613. .margin({ top: 10, bottom: 10 })
  7614. .justifyContent(FlexAlign.Start)
  7615. Row() {
  7616. Text('质量评分:')
  7617. .fontSize(14)
  7618. .fontColor($r('app.color.text_color'))
  7619. .margin({ left: 22 })
  7620. Text(currentItem.probe_score+"")
  7621. .fontSize(14)
  7622. .margin({ left: 10 })
  7623. .fontColor($r('app.color.text_color'))
  7624. .layoutWeight(1)
  7625. }
  7626. .width('100%')
  7627. .margin({ top: 10, bottom: 10 })
  7628. .justifyContent(FlexAlign.Start)
  7629. Row() {
  7630. Text('音轨号:')
  7631. .fontSize(14)
  7632. .fontColor($r('app.color.text_color'))
  7633. .margin({ left: 22 })
  7634. Text(currentItem.track)
  7635. .fontSize(14)
  7636. .margin({ left: 10 })
  7637. .fontColor($r('app.color.text_color'))
  7638. .layoutWeight(1)
  7639. }
  7640. .width('100%')
  7641. .margin({ top: 10, bottom: 10 })
  7642. .justifyContent(FlexAlign.Start)
  7643. Row() {
  7644. Text('碟号:')
  7645. .fontSize(14)
  7646. .fontColor($r('app.color.text_color'))
  7647. .margin({ left: 22 })
  7648. Text(currentItem.disc)
  7649. .fontSize(14)
  7650. .margin({ left: 10 })
  7651. .fontColor($r('app.color.text_color'))
  7652. .layoutWeight(1)
  7653. }
  7654. .width('100%')
  7655. .margin({ top: 10, bottom: 10 })
  7656. .justifyContent(FlexAlign.Start)
  7657. Row() {
  7658. Text('专辑艺术家:')
  7659. .fontSize(14)
  7660. .fontColor($r('app.color.text_color'))
  7661. .margin({ left: 22 })
  7662. Text(currentItem.ALBUMARTIST)
  7663. .fontSize(14)
  7664. .margin({ left: 10 })
  7665. .fontColor($r('app.color.text_color'))
  7666. .layoutWeight(1)
  7667. }
  7668. .width('100%')
  7669. .margin({ top: 10, bottom: 10 })
  7670. .justifyContent(FlexAlign.Start)
  7671. Row() {
  7672. Text('作曲家:')
  7673. .fontSize(14)
  7674. .fontColor($r('app.color.text_color'))
  7675. .margin({ left: 22 })
  7676. Text(currentItem.COMPOSER)
  7677. .fontSize(14)
  7678. .margin({ left: 10 })
  7679. .fontColor($r('app.color.text_color'))
  7680. .layoutWeight(1)
  7681. }
  7682. .width('100%')
  7683. .margin({ top: 10, bottom: 10 })
  7684. .justifyContent(FlexAlign.Start)
  7685. Row() {
  7686. Text('作词家:')
  7687. .fontSize(14)
  7688. .fontColor($r('app.color.text_color'))
  7689. .margin({ left: 22 })
  7690. Text(currentItem.LYRICIST)
  7691. .fontSize(14)
  7692. .margin({ left: 10 })
  7693. .fontColor($r('app.color.text_color'))
  7694. .layoutWeight(1)
  7695. }
  7696. .width('100%')
  7697. .margin({ top: 10, bottom: 10 })
  7698. .justifyContent(FlexAlign.Start)
  7699. Row() {
  7700. Text('注释:')
  7701. .fontSize(14)
  7702. .fontColor($r('app.color.text_color'))
  7703. .margin({ left: 22 })
  7704. Text(currentItem.COMMENT)
  7705. .fontSize(14)
  7706. .margin({ left: 10 })
  7707. .fontColor($r('app.color.text_color'))
  7708. .layoutWeight(1)
  7709. }
  7710. .width('100%')
  7711. .margin({ top: 10, bottom: 10 })
  7712. .justifyContent(FlexAlign.Start)
  7713. Row() {
  7714. Text('格式:')
  7715. .fontSize(14)
  7716. .fontColor($r('app.color.text_color'))
  7717. .margin({ left: 22 })
  7718. Text(Utility.formatMimeType(currentItem.mimeType))
  7719. .fontSize(14)
  7720. .margin({ left: 10 })
  7721. .fontColor($r('app.color.text_color'))
  7722. .layoutWeight(1)
  7723. }
  7724. .width('100%')
  7725. .margin({ top: 10, bottom: 10 })
  7726. .justifyContent(FlexAlign.Start)
  7727. Row() {
  7728. Text('播放次数:')
  7729. .fontSize(14)
  7730. .fontColor($r('app.color.text_color'))
  7731. .margin({ left: 22 })
  7732. Text(currentItem.playCount?.toString())
  7733. .fontSize(14)
  7734. .margin({ left: 10 })
  7735. .fontColor($r('app.color.text_color'))
  7736. .layoutWeight(1)
  7737. }
  7738. .width('100%')
  7739. .margin({ top: 10, bottom: 10 })
  7740. .justifyContent(FlexAlign.Start)
  7741. Row() {
  7742. Text('流数量:')
  7743. .fontSize(14)
  7744. .fontColor($r('app.color.text_color'))
  7745. .margin({ left: 22 })
  7746. Text(currentItem.nb_streams?.toString())
  7747. .fontSize(14)
  7748. .margin({ left: 10 })
  7749. .fontColor($r('app.color.text_color'))
  7750. .layoutWeight(1)
  7751. }
  7752. .width('100%')
  7753. .margin({ top: 10, bottom: 10 })
  7754. .justifyContent(FlexAlign.Start)
  7755. Row() {
  7756. Text('文件大小:')
  7757. .fontSize(14)
  7758. .fontColor($r('app.color.text_color'))
  7759. .margin({ left: 22 })
  7760. Text(currentItem.size)
  7761. .fontSize(14)
  7762. .margin({ left: 10 })
  7763. .fontColor($r('app.color.text_color'))
  7764. .layoutWeight(1)
  7765. }
  7766. .width('100%')
  7767. .margin({ top: 10, bottom: 10 })
  7768. .justifyContent(FlexAlign.Start)
  7769. Row() {
  7770. Text('文件名:')
  7771. .fontSize(14)
  7772. .fontColor($r('app.color.text_color'))
  7773. .margin({ left: 22 })
  7774. Text(currentItem.fileName)
  7775. .fontSize(14)
  7776. .margin({ left: 10 })
  7777. .fontColor($r('app.color.text_color'))
  7778. .layoutWeight(1)
  7779. }
  7780. .width('100%')
  7781. .margin({ top: 10, bottom: 10 })
  7782. .justifyContent(FlexAlign.Start)
  7783. Row() {
  7784. Text('修改时间:')
  7785. .fontSize(14)
  7786. .fontColor($r('app.color.text_color'))
  7787. .margin({ left: 22 })
  7788. Text(currentItem.cTime)
  7789. .fontSize(14)
  7790. .margin({ left: 10 })
  7791. .fontColor($r('app.color.text_color'))
  7792. .layoutWeight(1)
  7793. }
  7794. .width('100%')
  7795. .margin({ top: 10, bottom: 10 })
  7796. .justifyContent(FlexAlign.Start)
  7797. Row() {
  7798. Text('存放目录:')
  7799. .fontSize(14)
  7800. .fontColor($r('app.color.text_color'))
  7801. .margin({ left: 22 })
  7802. Text(currentItem.filePath)
  7803. .fontSize(12)
  7804. .margin({ left: 10 })
  7805. .fontColor($r('app.color.text_color'))
  7806. .layoutWeight(1)
  7807. }
  7808. .margin({ top: 10, bottom: 10 })
  7809. .width('100%')
  7810. .justifyContent(FlexAlign.Start)
  7811. Row() {
  7812. Text('内嵌歌词:')
  7813. .fontSize(14)
  7814. .fontColor($r('app.color.text_color'))
  7815. .margin({ left: 22 })
  7816. Text(currentItem.lyricContent)
  7817. .fontSize(12)
  7818. .copyOption(CopyOptions.InApp)
  7819. .margin({ left: 10 })
  7820. .fontColor($r('app.color.text_color'))
  7821. .layoutWeight(1)
  7822. }
  7823. .margin({ top: 10, bottom: 10 })
  7824. .width('100%')
  7825. .justifyContent(FlexAlign.Start)
  7826. }
  7827. }
  7828. .margin({ bottom: 20 })
  7829. }
  7830. //定时关闭布局
  7831. @Builder
  7832. TimeCloseSheet() {
  7833. Scroll() {
  7834. Column() {
  7835. this.TimeClose()
  7836. }
  7837. }
  7838. .width('100%')
  7839. .height('100%')
  7840. }
  7841. //倒计时关闭音乐,退出App功能实现。
  7842. @State selectedMinutes: number = 0 // 0表示未开启
  7843. @State remainingSeconds: number = 0
  7844. // 预设时间选项
  7845. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  7846. private formatTime(seconds: number): string {
  7847. const mins = Math.floor(seconds / 60)
  7848. const secs = seconds % 60
  7849. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  7850. }
  7851. // 开始倒计时
  7852. private handleTimeSelect(minutes: number) {
  7853. if (minutes === this.selectedMinutes) {
  7854. this.stopCountdown();
  7855. this.selectedMinutes = 0;
  7856. return;
  7857. }
  7858. this.selectedMinutes = minutes;
  7859. this.remainingSeconds = minutes * 60;
  7860. this.startCountdown(); // 新增调用
  7861. }
  7862. @Builder
  7863. TimeClose() {
  7864. Column() {
  7865. // 倒计时显示区域
  7866. Text(this.selectedMinutes > 0 ?
  7867. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  7868. "定时关闭未开启")
  7869. .fontSize(17)
  7870. .fontColor($r('app.color.text_color'))
  7871. .margin({ top: 2, bottom: 8 });
  7872. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  7873. ForEach(this.presetTimes, (minutes: number, index: number) => {
  7874. // 单行时间选项容器
  7875. Row() {
  7876. // 文字描述区域
  7877. Text(this.getDisplayText(minutes))
  7878. .fontSize(15)
  7879. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  7880. $r('app.color.text_color'))// 选中态颜色变化
  7881. .textAlign(TextAlign.Start)
  7882. .layoutWeight(1); // 占据剩余空间
  7883. // 复选框样式的选择器
  7884. Row() {
  7885. if (minutes === this.selectedMinutes) {
  7886. // 选中状态 - 带勾号的圆形复选框
  7887. Row() {
  7888. // 使用系统内置的勾号图标
  7889. Image($r('sys.media.ohos_ic_public_ok'))
  7890. .width(14)
  7891. .height(14)
  7892. .fillColor(Color.White)
  7893. }
  7894. .width(24)
  7895. .height(24)
  7896. .borderRadius(12)
  7897. .backgroundColor(this.themeColor)
  7898. .justifyContent(FlexAlign.Center)
  7899. .alignItems(VerticalAlign.Center)
  7900. } else {
  7901. // 未选中状态的圆形边框
  7902. Row()
  7903. .width(24)
  7904. .height(24)
  7905. .borderRadius(12)
  7906. .border({
  7907. width: 2,
  7908. color: $r('app.color.text_color'),
  7909. style: BorderStyle.Solid
  7910. })
  7911. .backgroundColor(Color.Transparent)
  7912. }
  7913. }
  7914. .width(24)
  7915. .height(24)
  7916. .margin({ left: 20 })
  7917. .justifyContent(FlexAlign.Center)
  7918. .alignItems(VerticalAlign.Center)
  7919. }
  7920. .width('100%')
  7921. .padding({
  7922. top: 18,
  7923. bottom: 18,
  7924. left: 18,
  7925. right: 18
  7926. })
  7927. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  7928. $r('app.color.bottom_control_background')) // 选中背景高亮
  7929. .borderRadius(12)
  7930. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7931. .margin({ bottom: 18 })
  7932. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  7933. });
  7934. }
  7935. .width('100%')
  7936. .padding(16)
  7937. }
  7938. }
  7939. // 获取显示文本
  7940. private getDisplayText(minutes: number): string {
  7941. if (minutes === -1) {
  7942. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  7943. }
  7944. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  7945. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  7946. }
  7947. // 处理选择事件
  7948. private handleSelect(minutes: number): void {
  7949. if (minutes === -1) { // 自定义
  7950. // 弹出自定义时间对话框
  7951. DialogHelper.showTextInputDialog({
  7952. title: '自定义时间',
  7953. maskColor: Color.Transparent,
  7954. inputType: InputType.Number,
  7955. text: '',
  7956. onChange: (text) => {
  7957. console.error("onChange: " + text);
  7958. },
  7959. onAction: (action, dialogId, content) => {
  7960. if (action == DialogAction.TWO) {
  7961. const customMinutes = Number(content);
  7962. if (customMinutes > 0) {
  7963. this.handleTimeSelect(customMinutes); // 设置自定义时间
  7964. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  7965. }
  7966. }
  7967. }
  7968. });
  7969. } else {
  7970. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  7971. }
  7972. }
  7973. // 添加定时器引用
  7974. private timerId: number = -1;
  7975. // 启动/重置倒计时
  7976. private startCountdown() {
  7977. // 清除旧定时器
  7978. if (this.timerId !== -1) {
  7979. clearInterval(this.timerId);
  7980. }
  7981. // 创建新定时器
  7982. if (this.selectedMinutes > 0) {
  7983. this.timerId = setInterval(() => {
  7984. if (this.remainingSeconds === 15) {
  7985. this.showConfirmationDialog();
  7986. }
  7987. if (this.remainingSeconds > 0) {
  7988. this.remainingSeconds -= 1;
  7989. } else {
  7990. this.stopCountdown();
  7991. this.handleTimeout();
  7992. }
  7993. }, 1000);
  7994. }
  7995. }
  7996. // 15倒计时后再次提示显示确认是否关闭App对话框
  7997. private showConfirmationDialog() {
  7998. DialogHelper.showAlertDialog({
  7999. backgroundColor: $r('app.color.btn_green'),
  8000. title: '确认关闭',
  8001. maskColor: Color.Transparent,
  8002. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  8003. borderStyle: BorderStyle.Dashed,
  8004. primaryButton: '暂不关闭',
  8005. secondaryButton: '确定',
  8006. onAction: (action) => {
  8007. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  8008. this.stopCountdown();
  8009. this.selectedMinutes = 0
  8010. } else if (action == DialogAction.TWO) {
  8011. }
  8012. }
  8013. })
  8014. }
  8015. // 停止倒计时
  8016. private stopCountdown() {
  8017. if (this.timerId !== -1) {
  8018. clearInterval(this.timerId);
  8019. this.timerId = -1;
  8020. }
  8021. }
  8022. // 超时处理
  8023. private handleTimeout() {
  8024. // 执行播放器关闭逻辑
  8025. this.selectedMinutes = 0;
  8026. ToastUtil.showToast(" 定时关闭已完成");
  8027. this.stop(); // 假设存在的播放器实例
  8028. //退出APP
  8029. const mContext = getContext(this) as common.UIAbilityContext
  8030. mContext.terminateSelf();
  8031. AvSessionController.getInstance(true).unregisterSessionListener()
  8032. }
  8033. //倒计时关闭音乐,退出App功能实现结束。
  8034. //播放列表的拖动List 重新排序
  8035. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  8036. //左滑操作 移动文件 重命名 删除等操作
  8037. @Builder
  8038. sonButton(item: VideoItem, index: number, filePath: string) {
  8039. Row() {
  8040. //加入下一首播放
  8041. Button() {
  8042. Image($r('app.media.next_to_play'))
  8043. .fillColor(Color.White)
  8044. .width(20)
  8045. }
  8046. .width(40)
  8047. .height(40)
  8048. .type(ButtonType.Circle)
  8049. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8050. .backgroundColor(this.themeColor)
  8051. .margin(5)
  8052. .onClick(() => {
  8053. this.addToNextPlay(item);
  8054. })
  8055. Button() {
  8056. Image($r('app.media.close'))
  8057. .fillColor(Color.White)
  8058. .width(20)
  8059. }
  8060. .width(40)
  8061. .height(40)
  8062. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8063. .type(ButtonType.Circle)
  8064. .backgroundColor(this.themeColor)
  8065. .margin(5)
  8066. .onClick(() => {
  8067. this.songList.splice(Number(index), 1)
  8068. this.sonDataSource.pushArrayData(this.songList)
  8069. })
  8070. Button() {
  8071. Image($r('app.media.share2'))
  8072. .fillColor(Color.White)
  8073. .width(20)
  8074. }
  8075. .width(40)
  8076. .height(40)
  8077. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8078. .type(ButtonType.Circle)
  8079. .backgroundColor(this.themeColor)
  8080. .margin(5)
  8081. .onClick(() => {
  8082. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  8083. })
  8084. }
  8085. }
  8086. itemMoveSon(index: number, newIndex: number): void {
  8087. if (newIndex < 0 || newIndex >= this.songList.length) {
  8088. return;
  8089. }
  8090. let tmp = this.songList.splice(index, 1);
  8091. this.songList.splice(newIndex, 0, tmp[0]);
  8092. this.sonDataSource.pushArrayData(this.songList)
  8093. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  8094. if(this.modeType==4&&this.playlistTable){
  8095. updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
  8096. }
  8097. }
  8098. @Builder
  8099. PlayList() {
  8100. List({ scroller: this.playListScroller }) {
  8101. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  8102. ListItem() {
  8103. this.MusicItemSon(item, index)
  8104. }
  8105. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  8106. .animation({
  8107. duration: 666,
  8108. curve: 'ease-in-out' // 可选动画曲线
  8109. })
  8110. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 600 }),
  8111. TransitionEffect.scale({ x: 0, y: 0 })))
  8112. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  8113. //拖动List关键代码开始
  8114. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  8115. .zIndex(this.dragItem === index ? 1 : 0)
  8116. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  8117. .gesture(
  8118. GestureGroup(GestureMode.Sequence,
  8119. LongPressGesture({ repeat: true })
  8120. .onAction((event?: GestureEvent) => {
  8121. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  8122. this.scaleItem = index
  8123. })
  8124. })
  8125. .onActionEnd(() => {
  8126. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  8127. this.scaleItem = -1
  8128. })
  8129. }),
  8130. PanGesture({ fingers: 1, direction: null, distance: 0 })
  8131. .onActionStart(() => {
  8132. this.dragItem = index // 记录当前拖动项索引
  8133. this.dragRefOffset = 0 // 重置偏移基准
  8134. })
  8135. .onActionUpdate((event: GestureEvent) => {
  8136. this.offsetY = event.offsetY - this.dragRefOffset;
  8137. this.neighborItem = -1;
  8138. let indexA = this.songList.indexOf(item);
  8139. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  8140. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  8141. let value: number = 0;
  8142. if (this.offsetY < 0) {
  8143. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  8144. this.neighborItem = indexA - 1;
  8145. this.neighborScale = 1 - value / 20;
  8146. } else if (this.offsetY > 0) {
  8147. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  8148. this.neighborItem = indexA + 1;
  8149. this.neighborScale = 1 - value / 20;
  8150. }
  8151. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  8152. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8153. this.offsetY -= this.ITEM_INTV;
  8154. this.dragRefOffset += this.ITEM_INTV;
  8155. this.itemMoveSon(indexA, indexA + 1);
  8156. });
  8157. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  8158. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8159. this.offsetY += this.ITEM_INTV;
  8160. this.dragRefOffset -= this.ITEM_INTV;
  8161. this.itemMoveSon(indexA, indexA - 1);
  8162. });
  8163. }
  8164. })
  8165. .onActionEnd((event: GestureEvent) => {
  8166. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8167. this.dragItem = -1
  8168. this.neighborItem = -1
  8169. })
  8170. animateTo({
  8171. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  8172. }, () => {
  8173. this.scaleItem = -1
  8174. })
  8175. })
  8176. )
  8177. .onCancel(() => {
  8178. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8179. this.dragItem = -1
  8180. this.neighborItem = -1
  8181. })
  8182. animateTo({
  8183. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  8184. }, () => {
  8185. this.scaleItem = -1
  8186. })
  8187. })
  8188. ) //拖动List关键代码结束
  8189. .onClick(() => {
  8190. this.doPlay(item, index, true)
  8191. })
  8192. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  8193. }
  8194. .width('100%')
  8195. .height('100%')
  8196. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  8197. // .animation({ duration: 500, curve: Curve.Ease }))
  8198. .cachedCount(10)
  8199. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  8200. .gesture(PinchGesture({ fingers: 2 })
  8201. .onActionEnd((event: GestureEvent) => {
  8202. this.setSonListTwoFingers()
  8203. })
  8204. .onActionUpdate(e => {
  8205. this.scaleValue = this.pinchValue * e.scale
  8206. })
  8207. .onActionStart(e => {
  8208. }))
  8209. .padding({
  8210. bottom: 0
  8211. })
  8212. }
  8213. setSonListTwoFingers() {
  8214. this.pinchValue = this.scaleValue;
  8215. Logger.info('this.pinchValue = ' + this.pinchValue);
  8216. if (this.pinchValue >= 1) {
  8217. this.sonTwoFingerType++
  8218. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  8219. if (this.sonTwoFingerType > 3) {
  8220. this.sonTwoFingerType = 1
  8221. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  8222. }
  8223. } else {
  8224. this.sonTwoFingerType--
  8225. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  8226. if (this.sonTwoFingerType < 1) {
  8227. this.sonTwoFingerType = 1
  8228. }
  8229. }
  8230. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  8231. this.pinchValue = 1;
  8232. this.scaleValue = 1;
  8233. }
  8234. @State sonTwoFingerType:number = 3
  8235. @Builder
  8236. private MusicItemSon(item: VideoItem, index?: number) {
  8237. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8238. Row() {
  8239. Stack() {
  8240. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  8241. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  8242. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  8243. .alt($r('app.media.music_red'))
  8244. .fillColor(this.themeColor)
  8245. .borderRadius(this.isCoverRectangle?11:'100%')
  8246. .clip(true)
  8247. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  8248. .draggable(false)// 禁止长按手势拖动
  8249. .autoResize(true) // 重采样,可减少内存占用
  8250. .margin({ left: 20 })
  8251. }
  8252. .width('15%')
  8253. Column() {
  8254. Column() {
  8255. Text(this.isShowFileName?item.fileName :item.name)
  8256. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  8257. .fontColor(this.curIndex === index ? this.themeColor :
  8258. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  8259. .maxLines(1)
  8260. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  8261. Row() {
  8262. Column(){
  8263. Text(item.md5Str?.includes('Lossless')?
  8264. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  8265. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  8266. .padding({ top: 3,right:6,left:6,bottom:3 })
  8267. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  8268. $r('app.color.text_color'))
  8269. .fontWeight(500)
  8270. .borderRadius(12)
  8271. .visibility(StrUtil.isEmpty(item.md5Str) ? Visibility.None : Visibility.Visible)
  8272. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  8273. .backgroundColor('#FFC107')
  8274. }
  8275. .padding({ top: 8 })
  8276. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  8277. item.artist + ' ' + item?.duration)
  8278. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  8279. .padding({ top: 8 })
  8280. .maxLines(1)
  8281. .fontColor(this.curIndex === index ? this.themeColor :
  8282. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  8283. .margin({ left: StrUtil.isEmpty(item.md5Str)? 12 :this.sonTwoFingerType == 3 ? 5 : 3 })
  8284. Blank()
  8285. Text(item.size)
  8286. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  8287. .padding({ top: 8 })
  8288. .maxLines(1)
  8289. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  8290. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  8291. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  8292. .margin({ left: 10 })
  8293. }
  8294. }
  8295. .height('100%')
  8296. .width('100%')
  8297. .justifyContent(FlexAlign.Center)
  8298. .alignItems(HorizontalAlign.Start)
  8299. }
  8300. .height('100%')
  8301. .width('65%')
  8302. Column() {
  8303. ImageAnimator()
  8304. .images(this.imagesF)// 动画数组
  8305. .duration(1000)// 持续
  8306. .state(this.animationState)// 动画状态
  8307. .fillMode(FillMode.Forwards)
  8308. .width(18)
  8309. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  8310. Visibility.None)
  8311. .height(18)
  8312. .iterations(-1) // 播放次数
  8313. }
  8314. .width('20%')
  8315. }
  8316. }
  8317. .backgroundColor(Color.Transparent)
  8318. .width('100%')
  8319. .reuseId('son_item')
  8320. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  8321. .shadow(this.scaleItem === index ? {
  8322. radius: 70,
  8323. color: '#15000000',
  8324. offsetX: 0,
  8325. offsetY: 0
  8326. } :
  8327. {
  8328. radius: 0,
  8329. color: '#15000000',
  8330. offsetX: 0,
  8331. offsetY: 0
  8332. })
  8333. .animation({ curve: Curve.Sharp, duration: 300 })
  8334. }
  8335. @Builder
  8336. MusicPlayBuilder() {
  8337. Column() {
  8338. this.IjkMusicPlayerView()
  8339. }
  8340. .transition(TransitionEffect.asymmetric(
  8341. TransitionEffect.opacity(1),
  8342. TransitionEffect.OPACITY
  8343. ))
  8344. .visualEffect(deviceInfo.sdkApiVersion>=20&&this.bgController?
  8345. new hdsEffect.HdsEffectBuilder()
  8346. .shaderEffect({
  8347. effectType: hdsEffect.EffectType.UV_BACKGROUND_FLOW_LIGHT,
  8348. animation: {
  8349. duration: 10000,
  8350. iterations: -1,
  8351. autoPlay: true,
  8352. onFinish: ()=> {
  8353. console.info('Succeeded in finishing');
  8354. }
  8355. },
  8356. controller: this.bgController,
  8357. })
  8358. .buildEffect():null)
  8359. .height('100%')
  8360. .width('100%')
  8361. .onDisAppear(() => {
  8362. this.translateY = 0;
  8363. })
  8364. .translate({ y: this.translateY })
  8365. .gesture(
  8366. PanGesture(this.panOption)
  8367. .onActionUpdate((event?: GestureEvent) => {
  8368. if (event) {
  8369. // 只允许向下滑动,向上滑动时限制为0
  8370. this.translateY = Math.max(0, event.offsetY);
  8371. this.getUIContext().animateTo({
  8372. duration: 500,
  8373. curve: Curve.Sharp
  8374. }, () => {
  8375. this.scaleValueImage = Math.min(1, Math.max(0.5, 1 - event.offsetY / 600));
  8376. console.info('onecold scaleValueImage:', this.scaleValueImage)
  8377. this.scaleValueText =Math.min(1, Math.max(0.6, 1 - event.offsetY / 700));
  8378. })
  8379. }
  8380. })
  8381. .onActionEnd((event?: GestureEvent) => {
  8382. // 使用更低的阈值和滑动速度判断
  8383. const minDistance = 300; // 最小滑动距离 100vp
  8384. const minVelocity = 500; // 最小滑动速度
  8385. // 获取滑动速度(如果可用)
  8386. const velocity = event?.velocityY || 0;
  8387. // 判断是否应该关闭:距离足够 或者 速度足够快
  8388. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  8389. if (shouldClose) {
  8390. // 添加关闭动画
  8391. this.getUIContext().animateTo({
  8392. duration: 600,
  8393. curve: Curve.Friction
  8394. }, () => {
  8395. this.isShowPlay = false;
  8396. this.scaleValueImage = 1
  8397. this.scaleValueText = 1
  8398. this.translateY = 0;
  8399. })
  8400. } else {
  8401. // 回弹动画
  8402. this.getUIContext().animateTo({
  8403. duration: 600,
  8404. curve: Curve.Friction
  8405. }, () => {
  8406. this.scaleValueImage = 1
  8407. this.scaleValueText = 1
  8408. this.translateY = 0;
  8409. })
  8410. }
  8411. })
  8412. )
  8413. }
  8414. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  8415. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  8416. HeightBreakpoint.HEIGHT_LG;
  8417. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  8418. @State topBarHeight: number = 50
  8419. @State barOpacity: number = 1
  8420. @State barBottomOpacity: number = 1
  8421. private hideDone: boolean = false;
  8422. @State currentYOffset: number = 0;
  8423. @State bottomBarHeight: number = 68;
  8424. private isHiding: boolean = false;
  8425. //是否是Pura X外屏,或者小屏幕
  8426. isPuraWP() {
  8427. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  8428. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  8429. }
  8430. //是否是Pura X外屏,或者小屏幕,手机横屏
  8431. /**
  8432. * 是否是Pura X外屏,或者小屏幕,手机横屏
  8433. * @returns
  8434. */
  8435. isCoverOpacity() {
  8436. if (this.isPuraWP()) {
  8437. return true
  8438. }
  8439. if (this.isPhoneLan()) {
  8440. return true
  8441. }
  8442. if (deviceInfo.marketName.includes('Pura X')
  8443. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  8444. return true
  8445. }
  8446. return false
  8447. }
  8448. //是不是手机横屏
  8449. isPhoneLan() {
  8450. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  8451. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  8452. logHiCarWindow(`isPhoneLan width=${this.windowWidth}`);
  8453. logHiCarWindow(`isPhoneLan height=${this.windowHeight}`);
  8454. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarStatus=${this.isHiCarStatus}`);
  8455. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, curDisplayIsHiCar=${this.curDisplayIsHiCar}`);
  8456. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall=${this.isHiCarSmall()}`);
  8457. if (this.isHiCarKuanBianPing()) {
  8458. return true
  8459. }
  8460. if (this.isHiCar()) {
  8461. return false
  8462. }
  8463. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8464. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  8465. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  8466. return true
  8467. }
  8468. return false
  8469. }
  8470. //是不是1920x720的hicar的屏幕分辨率
  8471. isHiCarKuanBianPing(){
  8472. if(!this.isHiCar()){
  8473. return false
  8474. }
  8475. const hiCarAspectRatios: HiCarAspectRatio[] = [
  8476. { ratio: 1920 / 720, name: "1920x720" },
  8477. ];
  8478. const currentRatio: number = this.windowWidth / this.windowHeight;
  8479. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  8480. logHiCarWindow(`HiCarKuanBianPing currentRatio=${currentRatio}`)
  8481. for (const hiCarRatio of hiCarAspectRatios) {
  8482. logHiCarWindow(`HiCarKuanBianPing hiCarRatio=${hiCarRatio.ratio}`)
  8483. logHiCarWindow(`HiCarKuanBianPing diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  8484. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  8485. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  8486. //宽扁平的尺寸设置列表展示
  8487. this.twoFingerType ==3
  8488. this.isGridMusic = false
  8489. return true;
  8490. }
  8491. }
  8492. return false;
  8493. }
  8494. //是不是hicar的屏幕分辨率
  8495. isHiCarSmall() {
  8496. if(!this.isHiCar()){
  8497. return false
  8498. }
  8499. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  8500. {
  8501. this.columns = 6
  8502. return false
  8503. }
  8504. const hiCarAspectRatios: HiCarAspectRatio[] = [
  8505. { ratio: 800 / 480, name: "800x480" },
  8506. { ratio: 1280 / 720, name: "1280x720" },
  8507. { ratio: 1920 / 1080, name: "1920x1080" },
  8508. ];
  8509. const currentRatio: number = this.windowWidth / this.windowHeight;
  8510. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  8511. logHiCarWindow(`HiCarSmall currentRatio=${currentRatio}`)
  8512. for (const hiCarRatio of hiCarAspectRatios) {
  8513. logHiCarWindow(`HiCarSmall hiCarRatio=${hiCarRatio.ratio}`)
  8514. logHiCarWindow(`HiCarSmall diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  8515. logHiCarWindow(`HiCarSmall isHiCarStatus=${this.isHiCarStatus}`);
  8516. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  8517. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  8518. //宽扁平的尺寸设置列表展示
  8519. return true;
  8520. }
  8521. }
  8522. return false;
  8523. }
  8524. isHiCar() {
  8525. return this.isHiCarStatus&&this.curDisplayIsHiCar;
  8526. }
  8527. //是不是正常的手机竖屏
  8528. isPhonePortrait() {
  8529. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  8530. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  8531. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  8532. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8533. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  8534. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  8535. return true
  8536. }
  8537. return false
  8538. }
  8539. @State showSpeedDialog: boolean = false
  8540. @State longPressSpeed: number = 3 //长按默认倍数
  8541. @Builder
  8542. SpeedDialog() {
  8543. Stack() {
  8544. Column() {
  8545. Text('已切换至' + this.longPressSpeed + '倍速播放')
  8546. .fontColor(Color.White)
  8547. .visibility(Visibility.Hidden)
  8548. }
  8549. .backgroundColor(Color.Black)
  8550. .borderRadius(20)
  8551. .padding({
  8552. top: 10,
  8553. right: 20,
  8554. left: 15,
  8555. bottom: 20
  8556. })
  8557. .opacity(0.6)
  8558. Text('已切换至' + this.longPressSpeed + '倍速播放')
  8559. .fontColor(Color.White)
  8560. }
  8561. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  8562. .zIndex(5)
  8563. .margin({ top: 80 })
  8564. }
  8565. @Builder
  8566. IjkMusicPlayerView() {
  8567. Stack() {
  8568. if(canIUse("SystemCapability.UIDesign.HDSComponent.Core")
  8569. &&deviceInfo.sdkApiVersion>=20&&this.sceneBgController){
  8570. HdsVisualComponent()
  8571. .scene(HdsSceneType.DUAL_EDGE_FLOW_LIGHT_WITH_BACKGROUND_MASK, this.sceneBgController, () => {
  8572. console.info('Succeeded in finishing');
  8573. })
  8574. .width('100%')
  8575. .height('100%')
  8576. .visibility(this.isShowBgLiuGUANG?Visibility.Visible:Visibility.None)
  8577. }
  8578. Column() {
  8579. Column() {
  8580. //播放标题
  8581. Column() {
  8582. this.PlayTitle()
  8583. }
  8584. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  8585. .width('100%')
  8586. .margin({ top: 0 })
  8587. .height(PlayConstants.HEIGHT)
  8588. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  8589. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  8590. if (this.showSpeedDialog) {
  8591. this.SpeedDialog()
  8592. }
  8593. Stack() {
  8594. //手势拖动快进
  8595. Column()
  8596. .width(CommonConstants.FULL_PERCENT)
  8597. .height('100%')
  8598. .gesture(
  8599. GestureGroup(GestureMode.Parallel,
  8600. // 长按屏幕倍数播放
  8601. LongPressGesture({ repeat: true })
  8602. .onAction(() => {
  8603. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8604. this.showSpeedDialog = true;
  8605. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  8606. }
  8607. })
  8608. .onActionEnd(() => {
  8609. this.showSpeedDialog = false;
  8610. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  8611. }),
  8612. //双击屏幕暂停或者播放
  8613. TapGesture({ count: 2 })
  8614. .onAction((event: GestureEvent) => {
  8615. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8616. ToastUtil.showToast('已暂停')
  8617. }
  8618. console.info('onecold playOrPause 6693')
  8619. this.playOrPause()
  8620. })
  8621. )
  8622. )
  8623. }
  8624. .height('65%')
  8625. Swiper() {
  8626. this.CoverInfo()
  8627. this.PlayerLyrics()
  8628. }
  8629. .onChange((index: number) => {
  8630. this.currentSwiperIndex = index
  8631. })
  8632. .indicator(false)
  8633. .displayCount(new BreakpointType({
  8634. sm: 1,
  8635. md: 2,
  8636. lg: 2,
  8637. xl: 2,
  8638. xxl: 2
  8639. }).getValue(this.currentBreakpoint))
  8640. .clip(false)
  8641. .loop(false)
  8642. .autoPlay(false)
  8643. // .interval(8000)
  8644. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  8645. .height('100%')
  8646. .hitTestBehavior(HitTestMode.Transparent)
  8647. Image($r('app.media.icon_replay'))
  8648. .objectFit(ImageFit.Auto)
  8649. .width('120px')
  8650. .height('120px')
  8651. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  8652. .border({ width: 0 })
  8653. .visibility(Visibility.None)
  8654. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  8655. .onClick(() => {
  8656. console.info('onecold startPlayOrResumePlay 6744')
  8657. this.startPlayOrResumePlay();
  8658. })
  8659. }
  8660. .width(CommonConstants.FULL_PERCENT)
  8661. .height(CommonConstants.FULL_PERCENT)
  8662. .justifyContent(FlexAlign.End)
  8663. }
  8664. .justifyContent(FlexAlign.End)
  8665. .margin({ bottom: 8 })
  8666. }
  8667. .backgroundImage(!this.isMusicBGCover||StrUtil.isEmpty(this.cover)?null: this.cover)
  8668. .backgroundImageSize(this.isPuraWP()||!this.isMusicBGCover ? { width: '100%' } : { height: '150%', width: '100%' })
  8669. .animation({
  8670. duration: 666,
  8671. curve: 'ease-in-out' // 可选动画曲线
  8672. })
  8673. .backgroundBlurStyle((this.isPuraWP() && this.currentSwiperIndex === 0) ||!this.isMusicBGCover
  8674. ? BlurStyle.NONE :
  8675. BlurStyle.BACKGROUND_ULTRA_THICK)
  8676. .hitTestBehavior(HitTestMode.Transparent)
  8677. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  8678. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  8679. .onClick(() => {
  8680. if(this.isHiCar())
  8681. return
  8682. if(this.is_auto_hide_progress){
  8683. this.is_auto_hide_progress = false
  8684. }
  8685. this.startAutoHide()
  8686. })
  8687. }
  8688. @Consume progressValue: number ;
  8689. @State currentTime: string = "00:00";
  8690. @State totalTime: string = "00:00";
  8691. @State loadingVisible: Visibility = Visibility.None;
  8692. @State replayVisible: Visibility = Visibility.None;
  8693. @State slideEnable: boolean = false;
  8694. @State aspRatio: number = 0.5;
  8695. @State mContext: object | undefined = undefined;
  8696. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  8697. @State mFirst: boolean = true;
  8698. @State mDestroyPage: boolean = false;
  8699. @State playSpeed: number = 1;
  8700. @State oldSeconds: number = 0;
  8701. @State isSeekTo: boolean = false;
  8702. @State isCurrentTime: boolean = false;
  8703. @State videoWidth: string = '100%';
  8704. @State videoHeight: string = '100%';
  8705. @State initAspectRatio: number = 1;
  8706. @State videoAspectRatio: number = this.initAspectRatio;
  8707. @State videoUrl: string = '';
  8708. private last: number = 0;
  8709. @State videoParentAspectRatio: number = this.initAspectRatio;
  8710. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  8711. @Consume CONTROL_PlayStatus: number ;
  8712. @State PROGRESS_MAX_VALUE: number = 100;
  8713. @State updateProgressTimer: number = 0;
  8714. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  8715. @State name: string = '';
  8716. // @State loop: boolean = false;
  8717. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  8718. @State multiple: string = '1.0X';
  8719. xcomponentController: XComponentController = new XComponentController()
  8720. private panOptionBright: PanGestureOptions =
  8721. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  8722. private panOptionVolume: PanGestureOptions =
  8723. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  8724. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  8725. //手势的音量控制和亮度控制
  8726. private positionX: number = PlayConstants.POSITION_X;
  8727. private positionY: number = PlayConstants.POSITION_Y;
  8728. private windowClass: window.Window = globalThis.windowClass
  8729. @State volume: number = 0.5;
  8730. @State volumeSmall: boolean = false
  8731. @State autoParseMusicName: boolean = true
  8732. @State isShowFileName: boolean = false
  8733. @State isLongNameRoLL: boolean = true//长歌名滚动
  8734. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  8735. @State bright: number = PlayConstants.BRIGHT;
  8736. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  8737. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  8738. @State screenWidth: number = 0
  8739. @State screenHeight: number = 0
  8740. @State statusBarHeight: number = 0
  8741. @State isYesFull: boolean = false
  8742. private seekValue: number = 0
  8743. @State isVideoLock: boolean = false; // Whether the video playback is locked
  8744. eventHub = getContext().eventHub;
  8745. //投播组件
  8746. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  8747. private castController: avSession.AVCastController | undefined = undefined;
  8748. @State isCastPlaying: boolean = false;
  8749. @State currentTime2: number = 0;
  8750. @State currentStringTime: string = '00:00';
  8751. @State duration: number = 0;
  8752. @State isReady: boolean = false;
  8753. @State durationTime: number = 0;
  8754. @State durationStringTime: string = '00:00';
  8755. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  8756. // @State isPlaying: boolean = false;
  8757. private castSeek: boolean = false;
  8758. private castItem: avSession.AVQueueItem | undefined = undefined;
  8759. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  8760. @State rotateAngle2: number = -9
  8761. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  8762. @Consume cover: string | undefined ;
  8763. @State artist: string | undefined = ''
  8764. // 1.初始化controller
  8765. private lyricController: LyricController = new LyricController()
  8766. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  8767. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  8768. private parser = new LyricParser()
  8769. @State randomColor: string = 'rgb(0,0,0)'
  8770. @State randomShakenX: number = 0
  8771. @State randomShakenY: number = 0
  8772. @State lyricTextSize: number = 24
  8773. @State lyricContent: string = ''
  8774. @State isDebug: boolean = false
  8775. @State isHightLightCenter: boolean = true
  8776. /**
  8777. * 初始化歌词加载与展示逻辑
  8778. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  8779. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  8780. * @param isApi2 是否使用API2获取歌词(可选)
  8781. *
  8782. * 主要流程:
  8783. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  8784. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  8785. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  8786. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  8787. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  8788. * 6. 解析失败或读取失败时,清空歌词显示。
  8789. *
  8790. * 注意事项:
  8791. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  8792. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  8793. * - 歌词内容解析后通过lyricController驱动UI渲染。
  8794. */
  8795. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  8796. if (StrUtil.isEmpty(lyricPath)) {
  8797. return
  8798. }
  8799. this.initPipLyricSetting()
  8800. this.lyricControllerSingle
  8801. .setTextSize(15)
  8802. .setCacheSize(4)
  8803. .setTextColor("#FFFFFF")
  8804. .setHighlightColor("#FFFFFF")
  8805. .setHighlightScale(1.2)
  8806. .setEmptyHint("")
  8807. .setAlignMode('center')
  8808. .setAnimationDuration(500)
  8809. .setSingleLine(true)
  8810. this.lyricContent = ''
  8811. this.lyricController
  8812. .setTextSize(this.currentLyricSize)
  8813. .setCacheSize(4)
  8814. .setTextColor("#DDDDDD")
  8815. .setHighlightColor("#FFFFFF")
  8816. .setEmptyHint("")
  8817. .setAnimationDuration(1000)
  8818. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  8819. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  8820. this.setBlurDegree(this.blurDegree, false)
  8821. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  8822. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  8823. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  8824. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  8825. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  8826. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  8827. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  8828. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  8829. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  8830. this.lyricController.setTextWeight(this.lyricTextWeight)
  8831. this.showSingleLyric = false
  8832. this.timeOffset = 0
  8833. this.lyricController.setLyric(null)
  8834. this.lyricControllerSingle.setLyric(null)
  8835. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  8836. console.log("onecold lyricPath =" + lyricPath)
  8837. let neiqianLrc = ''
  8838. let lyContent = this.currentSong?.lyricContent
  8839. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  8840. neiqianLrc = lyContent
  8841. }
  8842. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast&&!isLocal&&!isLocal) {
  8843. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  8844. //赋值给this.lyricContent,播控中心才可以显示歌词
  8845. this.lyricContent = neiqianLrc
  8846. // 将文件内容按行分割成字符串数组
  8847. let lines = neiqianLrc.split('\n').map(line => line.trim());
  8848. // 3.解析歌词
  8849. let lyric = this.parser.parse(lines);
  8850. // 4.设置歌词
  8851. this.lyricController.setLyric(lyric);
  8852. this.lyricControllerXF.setLyric(lyric)
  8853. this.lyricControllerSingle.setLyric(lyric)
  8854. return
  8855. }
  8856. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  8857. && !Utility.isVideoByExtension(this.videoUrl))) {
  8858. if (this.currentSong !== undefined) {
  8859. // ToastUtil.showShort('正在为你搜索在线歌词!')
  8860. //判断是不是赞助会员,是会员的话才开启歌词功能
  8861. // if (!this.isDebug) {
  8862. // if (!Utility.isNoble()) {
  8863. // LogUtil.debug("onecold 不是赞助会员")
  8864. // return
  8865. // }
  8866. // if(!Utility.isPassInstallTime(33)){
  8867. // LogUtil.debug("onecold not pass time")
  8868. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  8869. // return
  8870. // }
  8871. // }
  8872. let artist = this.currentSong?.artist
  8873. if (artist === undefined) {
  8874. artist = ''
  8875. }
  8876. if (isApi2 === undefined) {
  8877. isApi2 = false
  8878. }
  8879. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  8880. // LogUtil.debug("onecold res =" + res)
  8881. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  8882. if (StrUtil.isNotEmpty(res)) {
  8883. this.lyricContent = res
  8884. let lines = res.split('\n').map(line => line.trim());
  8885. // 3.解析歌词
  8886. let lyric = this.parser.parse(lines);
  8887. // 4.设置歌词
  8888. this.lyricController.setLyric(lyric);
  8889. this.lyricControllerXF.setLyric(lyric)
  8890. this.lyricControllerSingle.setLyric(lyric)
  8891. this.showSingleLyric = true
  8892. // 4.保存歌词文件lyric到本地
  8893. //2025年8月28日歌词不再加密下载
  8894. this.saveDataToFile(res, lyricPath, false)
  8895. } else {
  8896. this.lyricController.setLyric(null)
  8897. this.lyricControllerXF.setLyric(null)
  8898. this.lyricControllerSingle.setLyric(null)
  8899. if (isOnLineAndToast) {
  8900. ToastUtil.showShort('未获取到歌词!')
  8901. }
  8902. }
  8903. } else {
  8904. this.lyricController.setLyric(null)
  8905. this.lyricControllerXF.setLyric(null)
  8906. this.lyricControllerSingle.setLyric(null)
  8907. if (isOnLineAndToast) {
  8908. ToastUtil.showShort('未获取到歌词!')
  8909. }
  8910. }
  8911. })
  8912. } else {
  8913. this.lyricController.setLyric(null)
  8914. this.lyricControllerXF.setLyric(null)
  8915. this.lyricControllerSingle.setLyric(null)
  8916. if (isOnLineAndToast) {
  8917. ToastUtil.showShort('未获取到歌词!')
  8918. }
  8919. }
  8920. return
  8921. }
  8922. try {
  8923. let isJiaMi = false;
  8924. let realLyricPath = lyricPath
  8925. if (FileUtil.accessSync(jiaMilyricPath)) {
  8926. isJiaMi = true
  8927. realLyricPath = jiaMilyricPath
  8928. console.info("onecold 找到加密本地歌词 ");
  8929. } else {
  8930. isJiaMi = false
  8931. realLyricPath = lyricPath
  8932. console.info("onecold 找到本地歌词 ");
  8933. }
  8934. // 3.读取文件内容并指定编码为 UTF-8
  8935. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  8936. const stat = await fileIo.stat(file.fd);
  8937. const arrayBuffer = new ArrayBuffer(stat.size);
  8938. fs.read(file.fd, arrayBuffer)
  8939. .then((readLen: number) => {
  8940. console.info("read file data succeed");
  8941. // let buf = buffer.from(arrayBuffer, 0, readLen);
  8942. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  8943. // 检查 buf 是否为空
  8944. if (buf.length === 0) {
  8945. throw new Error("Buffer is empty after reading the file");
  8946. }
  8947. try {
  8948. // 检测文件编码
  8949. // let detectedEncoding = chardet.detect(buf);
  8950. // console.info("onecoldT Detected encoding: " + detectedEncoding);
  8951. let detectedEncoding = this.detect(arrayBuffer)
  8952. console.info("onecoldT Detected encoding: " + detectedEncoding);
  8953. // 使用检测到的编码解码,解决中文乱码问题
  8954. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  8955. console.info("onecoldT Detected textDecoder: " + textDecoder);
  8956. let fileContent = textDecoder.decode(buf);
  8957. console.info(`onecoldT The content of file1: ${fileContent}`);
  8958. //解密
  8959. if (isJiaMi) {
  8960. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  8961. }
  8962. console.info(`onecold The content of file2: ${fileContent}`);
  8963. this.lyricContent = fileContent
  8964. if(isLocal){//编辑标签选择本地歌词需要赋值给this.lyricConStr
  8965. this.lyricConStr = fileContent
  8966. }
  8967. // 将文件内容按行分割成字符串数组
  8968. let lines = fileContent.split('\n').map(line => line.trim());
  8969. console.info(`onecold The content of file: ${fileContent}`);
  8970. // 3.解析歌词
  8971. let lyric = this.parser.parse(lines);
  8972. // 4.设置歌词
  8973. this.lyricController.setLyric(lyric);
  8974. this.lyricControllerXF.setLyric(lyric)
  8975. this.lyricControllerSingle.setLyric(lyric)
  8976. this.showSingleLyric = true
  8977. console.info(`The content of file: ${fileContent}`);
  8978. } catch (chardetError) {
  8979. console.error("chardet.detect failed with error: " + chardetError.message);
  8980. this.lyricController.setLyric(null);
  8981. this.lyricControllerXF.setLyric(null)
  8982. this.lyricControllerSingle.setLyric(null)
  8983. }
  8984. })
  8985. .catch((err: BusinessError) => {
  8986. this.lyricController.setLyric(null)
  8987. this.lyricControllerXF.setLyric(null)
  8988. this.lyricControllerSingle.setLyric(null)
  8989. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  8990. })
  8991. .catch((err: Error) => {
  8992. this.lyricController.setLyric(null)
  8993. this.lyricControllerXF.setLyric(null)
  8994. this.lyricControllerSingle.setLyric(null)
  8995. console.error("read file 2 data failed with error message: " + err.message);
  8996. })
  8997. .finally(() => {
  8998. fs.closeSync(file);
  8999. });
  9000. } catch (error) {
  9001. this.lyricController.setLyric(null)
  9002. this.lyricControllerSingle.setLyric(null)
  9003. this.lyricControllerXF.setLyric(null)
  9004. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  9005. }
  9006. }
  9007. detect(data: ArrayBuffer): string {
  9008. //创建检测对象
  9009. let detector: UniversalDetector = new UniversalDetector();
  9010. // 传入检测数据并实时判断编码格式
  9011. detector.handleData(data, 0, data.byteLength);
  9012. // 标记检测数据 读取结束
  9013. detector.dataEnd();
  9014. // 获取检测结果
  9015. let detected: string = detector.getDetectedCharset();
  9016. // 释放资源
  9017. detector.reset();
  9018. return detected;
  9019. }
  9020. //初始化悬浮歌词的自定义设置
  9021. initPipLyricSetting() {
  9022. this.lyricControllerXF
  9023. .setTextSize(this.currentLyricSize)
  9024. .setCacheSize(4)
  9025. .setTextColor("#DDDDDD")
  9026. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  9027. .setEmptyHint("")
  9028. .setAnimationDuration(1000)
  9029. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  9030. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  9031. this.setBlurDegree(this.blurDegreePip, true)
  9032. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  9033. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  9034. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  9035. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  9036. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  9037. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  9038. this.lyricControllerXF.setHightLightCenter(true)
  9039. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  9040. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  9041. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  9042. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  9043. if (this.pipBgIndex === 0) {
  9044. if (this.cover) {
  9045. this.pipBg = this.cover
  9046. } else {
  9047. this.pipBg = this.imageColor
  9048. }
  9049. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  9050. }
  9051. }
  9052. //根据item返回歌词内容
  9053. async getLyricContent(item: VideoItem): Promise<string> {
  9054. let neiqianLrc = ''
  9055. let lyContent = item?.lyricContent
  9056. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  9057. neiqianLrc = lyContent
  9058. return neiqianLrc
  9059. }
  9060. try {
  9061. //取数据库里面的歌词lyContent
  9062. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  9063. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  9064. console.log("onecold Lyrics:", lyricContent);
  9065. neiqianLrc = lyricContent
  9066. return neiqianLrc
  9067. }
  9068. } catch (error) {
  9069. console.error("Error fetching lyrics:", error);
  9070. }
  9071. try {
  9072. let filePath = item.filePath;
  9073. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  9074. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  9075. let isJiaMi = false;
  9076. let realLyricPath = lyricPath;
  9077. if (FileUtil.accessSync(jiaMilyricPath)) {
  9078. isJiaMi = true;
  9079. realLyricPath = jiaMilyricPath;
  9080. console.info("onecold 找到加密本地歌词");
  9081. } else {
  9082. console.info("onecold 找到本地歌词");
  9083. }
  9084. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  9085. const stat = await fileIo.stat(file.fd);
  9086. const arrayBuffer = new ArrayBuffer(stat.size);
  9087. const readLen = await fs.read(file.fd, arrayBuffer);
  9088. console.info("read file data succeed");
  9089. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  9090. if (buf.length === 0) {
  9091. throw new Error("Buffer is empty after reading the file");
  9092. }
  9093. // let detectedEncoding = chardet.detect(buf);
  9094. let detectedEncoding = this.detect(arrayBuffer)
  9095. console.info("Detected encoding: " + detectedEncoding);
  9096. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  9097. let fileContent = textDecoder.decode(buf);
  9098. console.info(`onecold The content of file1: ${fileContent}`);
  9099. if (isJiaMi) {
  9100. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  9101. }
  9102. console.info(`onecold The content of file2: ${fileContent}`);
  9103. fs.closeSync(file);
  9104. return fileContent;
  9105. } catch (error) {
  9106. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  9107. return '';
  9108. }
  9109. }
  9110. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  9111. if (StrUtil.isEmpty(filePath)) {
  9112. return
  9113. }
  9114. try {
  9115. //将content进行加密
  9116. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  9117. let lyricContent = ''
  9118. if (isJiaMi) {
  9119. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  9120. } else {
  9121. lyricContent = content
  9122. }
  9123. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  9124. // 清空文件内容
  9125. await fileIo.truncate(file.fd, 0);
  9126. await fileIo.write(file.fd, lyricContent);
  9127. await fileIo.close(file);
  9128. console.log('onecold lyric file Data saved successfully.');
  9129. } catch (error) {
  9130. console.error('onecold lyric file Failed to save data:', error);
  9131. }
  9132. }
  9133. // 定义开始旋转的方法
  9134. // 定时器用于一百毫秒执行一次旋转角度
  9135. @State timer: number = 0
  9136. @State rotateAngle: number = 0
  9137. //封面旋转动画
  9138. animationRoFun() {
  9139. if (this.isPlaying && !this.isCoverRectangle) {
  9140. this.timer = setInterval(() => {
  9141. this.rotateAngle += 1
  9142. }, 100)
  9143. this.startRotation()
  9144. } else {
  9145. clearInterval(this.timer)
  9146. this.stopRotation()
  9147. }
  9148. }
  9149. // 定义开始旋转的方法
  9150. startRotation() {
  9151. if (this.isPlaying) {
  9152. animateTo({
  9153. duration: 777,
  9154. iterations: 1,
  9155. curve: Curve.Linear
  9156. }, () => {
  9157. this.rotateAngle2 = -9
  9158. })
  9159. }
  9160. }
  9161. // 回调,暂停和播放按钮回调,下一首和上一首
  9162. playChange() {
  9163. // if(this.isCoverRectangle){
  9164. // return
  9165. // }
  9166. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  9167. this.setIsPlaying(true)
  9168. this.animationState = AnimationStatus.Running
  9169. } else {
  9170. this.setIsPlaying(false)
  9171. this.animationState = AnimationStatus.Paused
  9172. }
  9173. AppStorage.setOrCreate('animationState', this.animationState);
  9174. }
  9175. // 定义停止旋转的方法
  9176. stopRotation() {
  9177. if (this.isCoverRectangle) {
  9178. this.rotateAngle = 0
  9179. } else {
  9180. //唱针以左上角为点选择逆时针40度
  9181. animateTo({
  9182. duration: 1000,
  9183. curve: Curve.Linear,
  9184. iterations: 1,
  9185. }, () => {
  9186. this.rotateAngle2 = -45;
  9187. });
  9188. }
  9189. }
  9190. @Builder
  9191. private LyricsTopItem() {
  9192. Row() {
  9193. Stack() {
  9194. Image(this.cover)
  9195. .height(58)
  9196. .width(58)
  9197. .alt($r('app.media.alt'))
  9198. .borderRadius(8)
  9199. .clickEffect({ level: ClickEffectLevel.HEAVY })
  9200. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  9201. .shadow({
  9202. radius: 22,
  9203. type: ShadowType.BLUR,
  9204. color: 'on_primary'
  9205. })
  9206. }
  9207. .width('18%')
  9208. Column() {
  9209. Column() {
  9210. Text(this.name)
  9211. .fontSize(16)
  9212. .maxLines(1)
  9213. .fontWeight(FontWeight.Bolder)
  9214. .fontColor(this.currentLyricColor)
  9215. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  9216. Row() {
  9217. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  9218. .fontSize(13)
  9219. .fontWeight(FontWeight.Bold)
  9220. .padding({ top: 8 })
  9221. .fontColor(this.currentLyricColor)
  9222. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  9223. Blank()
  9224. }
  9225. }
  9226. .height('100%')
  9227. .width('100%')
  9228. .justifyContent(FlexAlign.Center)
  9229. .alignItems(HorizontalAlign.Start)
  9230. }
  9231. .height('100%')
  9232. .width('65%')
  9233. Column() {
  9234. Image($r('app.media.lyric'))
  9235. .width(28)
  9236. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9237. .margin({ right: 30 })
  9238. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9239. .onClick(() => {
  9240. this.isLyricSetting = !this.isLyricSetting;
  9241. })
  9242. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  9243. height: '95%',
  9244. dragBar: true,
  9245. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9246. showClose: true,
  9247. blurStyle: BlurStyle.Thin,
  9248. backgroundColor: Color.Transparent,
  9249. // title: { title: $r('app.string.lyric_setting') }
  9250. })
  9251. }
  9252. .width('18%')
  9253. }
  9254. .width('82%')
  9255. .height(58)
  9256. .justifyContent(FlexAlign.SpaceBetween)
  9257. }
  9258. //歌词显示
  9259. @Builder
  9260. PlayerLyrics() {
  9261. Column() {
  9262. Column() {
  9263. this.LyricsTopItem()
  9264. }
  9265. .height(this.isPuraWP() ? 15 : 58)
  9266. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  9267. Visibility.None : Visibility.Visible)
  9268. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  9269. .width("100%")
  9270. Column() {
  9271. LyricView2({
  9272. controller: this.lyricController,
  9273. enableSeek: true,
  9274. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  9275. seekLineColor: "#80ffffff", // 滑动定位线颜色
  9276. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  9277. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  9278. if (!this.isPlaying) {
  9279. console.info('onecold startPlayOrResumePlay 7527')
  9280. this.startPlayOrResumePlay()
  9281. }
  9282. else {
  9283. this.isSeekTo = true;
  9284. this.mDestroyPage = false;
  9285. this.showLoadIng();
  9286. this.seekTo(position + "");
  9287. this.isSeekTo = false;
  9288. }
  9289. return true
  9290. }
  9291. })
  9292. .width("100%")
  9293. .layoutWeight(1)
  9294. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  9295. if (this.isPhoneLan()) {
  9296. Column() {
  9297. this.playProgressView()
  9298. // this.playCenterView()
  9299. }
  9300. .margin({ bottom: 30, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  9301. }
  9302. }
  9303. .position({
  9304. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  9305. (this.isPuraWP() ? 58 : 99)
  9306. })
  9307. .justifyContent(FlexAlign.Center)
  9308. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  9309. }
  9310. }
  9311. @Builder
  9312. SingleLyricView() {
  9313. Column() {
  9314. Column() {
  9315. LyricView2({
  9316. controller: this.lyricControllerSingle,
  9317. enableSeek: false,
  9318. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  9319. seekLineColor: "#80ffffff", // 滑动定位线颜色
  9320. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  9321. })
  9322. }
  9323. .height(66)
  9324. .margin({ bottom: 20 })
  9325. }
  9326. }
  9327. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  9328. @Builder
  9329. BottomControl() {
  9330. Column() {
  9331. this.TopPlayProgressView()
  9332. //播放 暂停,下一首,上一首
  9333. this.playCenterView()
  9334. //播放进度条
  9335. this.BottomView()
  9336. }
  9337. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  9338. }
  9339. //播放控制上一首 下一首 暂停和播放
  9340. @Builder
  9341. playCenterView(){
  9342. Row() {
  9343. Button({type:ButtonType.Circle,stateEffect:true}){
  9344. //更多功能
  9345. Image($r('app.media.menu'))
  9346. .width(24)
  9347. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9348. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  9349. height: '99%',
  9350. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  9351. dragBar: true,
  9352. showClose: true,
  9353. blurStyle: BlurStyle.Thin,
  9354. backgroundColor: Color.Transparent,
  9355. })
  9356. }
  9357. .height(45)
  9358. .width(45)
  9359. .margin({ left: 5 })
  9360. .backgroundColor(Color.Transparent)
  9361. .onClick(() => {
  9362. this.isShowMoreView = !this.isShowMoreView;
  9363. })
  9364. Button({type:ButtonType.Circle,stateEffect:true}){
  9365. Image($r('app.media.ic_previous'))
  9366. .width(33)
  9367. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9368. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9369. }
  9370. .height(45)
  9371. .width(45)
  9372. .onClick(async () => {
  9373. await this.playPrevious()
  9374. })
  9375. .backgroundColor(Color.Transparent)
  9376. Button({type:ButtonType.Circle,stateEffect:true}){
  9377. Column() {
  9378. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  9379. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  9380. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  9381. .width(this.isPhoneLan()?45:55)
  9382. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9383. .fillColor(Color.White)
  9384. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9385. }
  9386. }
  9387. .onClick(async () => {
  9388. this.playOrPause()
  9389. })
  9390. .backgroundColor(Color.Transparent)
  9391. .layoutWeight(1)
  9392. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9393. Image($r('app.media.ic_next'))
  9394. .width(33)
  9395. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9396. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9397. }
  9398. .height(45)
  9399. .width(45)
  9400. .backgroundColor(Color.Transparent)
  9401. .onClick(async () => {
  9402. await this.playNext();
  9403. })
  9404. this.fullButton()
  9405. }
  9406. .width('95%')
  9407. .margin({ bottom:this.isCoverOpacity()?0:15 })
  9408. .justifyContent(FlexAlign.SpaceEvenly)
  9409. }
  9410. @Builder
  9411. TopPlayProgressView(){
  9412. Column() {
  9413. Row(){
  9414. Stack(){
  9415. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  9416. .fontColor([Color.White])
  9417. .fontSize(21)
  9418. .effectStrategy(1)
  9419. Text(this.fastForwardSeconds)
  9420. .fontColor(Color.White)
  9421. .fontSize(10)
  9422. .fontWeight(FontWeight.Bold)
  9423. }
  9424. .padding({left:12,bottom:6})
  9425. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  9426. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9427. .onClick(()=>{
  9428. this.backForward()
  9429. })
  9430. Slider({
  9431. value: this.progressValue,
  9432. min: 0,
  9433. max: this.PROGRESS_MAX_VALUE,
  9434. step: 1,
  9435. style: SliderStyle.InSet
  9436. })
  9437. .height(20)
  9438. .blockColor('rgba(255,255,255,1)')
  9439. .trackColor('rgba(255,255,255,0.3)')
  9440. .selectedColor(Color.White)
  9441. .trackThickness(4)
  9442. .showSteps(false)
  9443. .showTips(true)
  9444. .layoutWeight(1)
  9445. .enabled(this.slideEnable)
  9446. .onChange((value: number, mode: SliderChangeMode) => {
  9447. // if (mode == 2) {
  9448. this.isSeekTo = true;
  9449. this.mDestroyPage = false;
  9450. this.showLoadIng();
  9451. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  9452. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  9453. this.seekTo(seekValue + "");
  9454. // this.setProgress()
  9455. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  9456. this.isSeekTo = false;
  9457. // }
  9458. })
  9459. Stack(){
  9460. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  9461. .fontColor([Color.White])
  9462. .fontSize(21)
  9463. .effectStrategy(1)
  9464. Text(this.fastForwardSeconds)
  9465. .fontColor(Color.White)
  9466. .fontSize(10)
  9467. .fontWeight(FontWeight.Bold)
  9468. }
  9469. .padding({right:10,bottom:6})
  9470. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  9471. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9472. .onClick(()=>{
  9473. this.fastForward()
  9474. })
  9475. }
  9476. .justifyContent(FlexAlign.Center)
  9477. .padding({left:20,right:20})
  9478. .width(this.isLandscape?'88%':'95%')
  9479. Row() {
  9480. Text(this.currentTime)
  9481. .fontSize(10)
  9482. .fontColor(Color.White)
  9483. .margin({left:25})
  9484. Blank()
  9485. Text(this.totalTime)
  9486. .fontSize(10)
  9487. .fontColor(Color.White)
  9488. .margin({right:25})
  9489. }
  9490. .width(this.isLandscape?'85%':'90%')
  9491. .height(10)
  9492. }
  9493. .width('100%')
  9494. .alignItems(HorizontalAlign.Center)
  9495. }
  9496. //播放进度条
  9497. @Builder
  9498. BottomView(){
  9499. Row() {
  9500. Button({type:ButtonType.Circle,stateEffect:true}){
  9501. Column() {
  9502. if (this.playType === 0) {
  9503. Image($r('app.media.loop'))
  9504. .width(27)
  9505. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9506. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9507. } else if (this.playType === 1) {
  9508. Image($r('app.media.single'))
  9509. .width(27)
  9510. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9511. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9512. } else if (this.playType === 2) {
  9513. Image($r('app.media.normal_play'))
  9514. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9515. .width(27)
  9516. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9517. } else if (this.playType === 3) {
  9518. Image($r('app.media.random'))
  9519. .width(27)
  9520. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9521. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9522. }
  9523. }
  9524. }
  9525. .layoutWeight(1)
  9526. .margin({ left: 5 })
  9527. .height(45)
  9528. .width(45)
  9529. .backgroundColor(Color.Transparent)
  9530. .onClick(async () => {
  9531. this.setLoopMode()
  9532. })
  9533. if(this.currentSong){
  9534. Button({type:ButtonType.Circle,stateEffect:true}){
  9535. Column() {
  9536. Image($r('app.media.rename2'))
  9537. .width(21)
  9538. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9539. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9540. }
  9541. }
  9542. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  9543. height: '99%',
  9544. dragBar: true,
  9545. showClose: true,
  9546. preferType: SheetType.BOTTOM,
  9547. title: { title: '编辑标签' }
  9548. })
  9549. .height(45)
  9550. .width(45)
  9551. .layoutWeight(1)
  9552. .backgroundColor(Color.Transparent)
  9553. .onClick(async () => {
  9554. this.initEditFields(this.currentSong)
  9555. this.tempLyricContent = this.lyricContent
  9556. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  9557. this.lyricConStr = this.tempLyricContent
  9558. }
  9559. this.isShowEdit = !this.isShowEdit;
  9560. })
  9561. }
  9562. Button({type:ButtonType.Circle,stateEffect:true}){
  9563. Column() {
  9564. Image($r('app.media.lyric'))
  9565. .width(26)
  9566. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9567. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9568. }
  9569. }
  9570. .height(45)
  9571. .width(45)
  9572. .layoutWeight(1)
  9573. .backgroundColor(Color.Transparent)
  9574. .onClick(async () => {
  9575. this.isLyricSetting = !this.isLyricSetting;
  9576. })
  9577. //播放列表
  9578. Button({type:ButtonType.Circle,stateEffect:true}){
  9579. Image($r('app.media.hm_playlist'))
  9580. .width(24)
  9581. .fillColor(Color.White)
  9582. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9583. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9584. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  9585. height: '95%',
  9586. dragBar: true,
  9587. showClose: true,
  9588. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9589. blurStyle: BlurStyle.Thin,
  9590. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  9591. title: {
  9592. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  9593. + `(${this.songList.length}首)`
  9594. }
  9595. })
  9596. }
  9597. .layoutWeight(1)
  9598. .height(45)
  9599. .width(45)
  9600. .backgroundColor(Color.Transparent)
  9601. .onClick(() => {
  9602. this.isShowSheetView = !this.isShowSheetView;
  9603. if(this.isPlayListBgGrass){
  9604. this.isFrontWhite = true
  9605. }else{
  9606. this.isFrontWhite = false
  9607. }
  9608. this.scrollIndex()
  9609. })
  9610. }
  9611. .width(this.isLandscape?'88%':'95%')
  9612. .justifyContent(FlexAlign.SpaceAround)
  9613. .height(30)
  9614. .animation({
  9615. duration: 666,
  9616. curve: 'ease-in-out' // 可选动画曲线
  9617. })
  9618. }
  9619. @Builder
  9620. fullButton(){
  9621. Button({type:ButtonType.Circle,stateEffect:true}){
  9622. Column() {
  9623. Image($r('app.media.full_4'))
  9624. .width(25)
  9625. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9626. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9627. }
  9628. }
  9629. .layoutWeight(1)
  9630. .backgroundColor(Color.Transparent)
  9631. .height(45)
  9632. .width(45)
  9633. .onClick(async () => {
  9634. if (this.isLandscape) {
  9635. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  9636. } else {
  9637. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  9638. }
  9639. })
  9640. }
  9641. //旧版本播放进度条
  9642. @Builder
  9643. playProgressView() {
  9644. Row() {
  9645. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9646. Column() {
  9647. if (this.playType === 0) {
  9648. Image($r('app.media.loop'))
  9649. .width($r('app.float.control_image_width'))
  9650. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9651. } else if (this.playType === 1) {
  9652. Image($r('app.media.single'))
  9653. .width($r('app.float.control_image_width'))
  9654. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9655. } else if (this.playType === 2) {
  9656. Image($r('app.media.normal_play'))
  9657. .width($r('app.float.control_image_width'))
  9658. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9659. } else if (this.playType === 3) {
  9660. Image($r('app.media.random'))
  9661. .width($r('app.float.control_image_width'))
  9662. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9663. }
  9664. }
  9665. }
  9666. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  9667. .animation({
  9668. duration: 666,
  9669. curve: 'ease-in-out' // 可选动画曲线
  9670. })
  9671. .backgroundColor(Color.Transparent)
  9672. .margin({ right: 10 })
  9673. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9674. .onClick(async () => {
  9675. this.setLoopMode()
  9676. })
  9677. Text(this.currentTime)
  9678. .fontSize($r('app.float.slider_font_size'))
  9679. .fontColor(Color.White)
  9680. .margin(3)
  9681. Slider({
  9682. value: this.progressValue,
  9683. min: 0,
  9684. max: this.PROGRESS_MAX_VALUE,
  9685. step: 1,
  9686. style: SliderStyle.OutSet
  9687. })
  9688. .width('600px')
  9689. .blockColor('rgba(255,255,255,1)')
  9690. .trackColor('rgba(255,255,255,0.3)')
  9691. .selectedColor(Color.White)
  9692. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  9693. .layoutWeight(1)
  9694. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  9695. .showSteps(false)
  9696. .showTips(true)
  9697. .enabled(this.slideEnable)
  9698. .onChange((value: number, mode: SliderChangeMode) => {
  9699. // if (mode == 2) {
  9700. this.isSeekTo = true;
  9701. this.mDestroyPage = false;
  9702. this.showLoadIng();
  9703. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  9704. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  9705. this.seekTo(seekValue + "");
  9706. // this.setProgress()
  9707. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  9708. this.isSeekTo = false;
  9709. // }
  9710. })
  9711. Text(this.totalTime)
  9712. .fontSize($r('app.float.slider_font_size'))
  9713. .fontColor(Color.White)
  9714. .margin(3)
  9715. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  9716. //播放列表
  9717. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9718. Image($r('app.media.hm_playlist'))
  9719. .width($r('app.float.control_image_width'))
  9720. .fillColor(Color.White)
  9721. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9722. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  9723. height: '95%',
  9724. dragBar: true,
  9725. showClose: true,
  9726. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9727. blurStyle: BlurStyle.Thin,
  9728. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  9729. title: {
  9730. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  9731. + `(${this.songList.length}首)`
  9732. }
  9733. })
  9734. }
  9735. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  9736. .animation({
  9737. duration: 666,
  9738. curve: 'ease-in-out' // 可选动画曲线
  9739. })
  9740. .backgroundColor(Color.Transparent)
  9741. .margin({ right: 20, left: 10 })
  9742. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9743. .onClick(() => {
  9744. this.isShowSheetView = !this.isShowSheetView;
  9745. if (this.isPlayListBgGrass) {
  9746. this.isFrontWhite = true
  9747. } else {
  9748. this.isFrontWhite = false
  9749. }
  9750. this.scrollIndex()
  9751. })
  9752. }
  9753. //x5的竖屏模式需要99%
  9754. .width(this.isPhonePortrait() ? '93.4%'
  9755. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  9756. .height(this.isPhoneLan() ? 25 : 33)
  9757. .animation({
  9758. duration: 666,
  9759. curve: 'ease-in-out' // 可选动画曲线
  9760. })
  9761. }
  9762. isBigScreen() {
  9763. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  9764. return true
  9765. }
  9766. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  9767. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  9768. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  9769. return false
  9770. } else {
  9771. return true
  9772. }
  9773. return false
  9774. }
  9775. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  9776. @State isCoverRectangle: boolean = false
  9777. @State isCoverTop: boolean = true
  9778. // 添加控制缩放的状态变量
  9779. @State scaleValueImage: number = 1
  9780. @State scaleValueText: number = 1
  9781. @Builder
  9782. CoverInfo() {
  9783. Column() {
  9784. //如果是方形,判断是不是封面在顶部,如果不是顶部,显示musicNameInfo, 如果是圆形显示musicNameInfo
  9785. if (this.isCoverRectangle) {
  9786. if (!this.isCoverTop) {
  9787. this.musicNameInfo(false)
  9788. }
  9789. } else {
  9790. this.musicNameInfo(false)
  9791. }
  9792. Stack() {
  9793. // 唱片旋转效果
  9794. Image($r('app.media.ic_music_disc'))
  9795. .width(245)
  9796. .height(245)
  9797. .margin({ right: 20, left: 20 ,top:this.isCoverRectangle||this.isLandscape?0:43})
  9798. .aspectRatio(1)
  9799. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  9800. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  9801. .borderRadius('100%')
  9802. .align(Alignment.Center)
  9803. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  9804. .rotate({
  9805. angle: this.rotateAngle,
  9806. centerX: "50%",
  9807. centerY: "50%",
  9808. })
  9809. .animation({
  9810. duration: 100,
  9811. curve: Curve.Linear
  9812. })
  9813. .shadow({
  9814. radius: 22,
  9815. type: ShadowType.BLUR,
  9816. color: 'on_primary'
  9817. })
  9818. Column() {
  9819. if (this.isCoverTop && this.isCoverRectangle) {
  9820. Image(this.cover)
  9821. .height(this.isHiCar()?(px2vp(this.windowHeight)*0.46):
  9822. this.isCoverOpacity()?(px2vp(this.windowHeight)*0.6):'auto')
  9823. .width(this.isHiCar()||this.isCoverOpacity()?'auto':this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '88%')
  9824. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  9825. .alt($r('app.media.alt'))
  9826. .margin({ right: 8, left: 8, top: 8 })
  9827. .aspectRatio(1)
  9828. .geometryTransition('cover') // 绑定标识符
  9829. .opacity(this.opacityValueImage)
  9830. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  9831. // 设置左下角为缩放中心点
  9832. centerX: '0%',
  9833. centerY: '100%' })
  9834. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  9835. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  9836. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  9837. .clip(true)
  9838. .rotate({
  9839. x: 0,
  9840. y: 0,
  9841. z: 1,
  9842. angle: this.rotateAngle
  9843. })
  9844. .shadow({
  9845. radius: 22,
  9846. type: ShadowType.BLUR,
  9847. color: 'on_primary'
  9848. })
  9849. .onClick(() => {
  9850. })
  9851. // .visualEffect(new hdsEffect.HdsEffectBuilder()
  9852. // .shaderEffect({
  9853. // effectType: hdsEffect.EffectType.DUAL_EDGE_FLOW_LIGHT,
  9854. // animation: {
  9855. // duration: 4000,
  9856. // iterations: -1,
  9857. // autoPlay: true,
  9858. // onFinish: () => {
  9859. // console.info('Succeeded in finishing');
  9860. // }
  9861. // },
  9862. // controller: this.controller,
  9863. // params: {
  9864. // firstEdgeFlowLight: {
  9865. // startPos: 0,
  9866. // endPos: 1.0,
  9867. // color: '#1AD0F1',
  9868. // },
  9869. // secondEdgeFlowLight: {
  9870. // startPos: 0.5,
  9871. // endPos: 1.5,
  9872. // color: '#FFA4E5',
  9873. // }
  9874. // }
  9875. // })
  9876. // .buildEffect())
  9877. this.musicNameInfo(false)
  9878. } else {
  9879. Image(this.cover)
  9880. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  9881. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 162))
  9882. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  9883. .alt($r('app.media.alt'))
  9884. .geometryTransition('cover') // 绑定标识符
  9885. .margin({ right: 20, left: 20,top:this.isCoverRectangle||this.isLandscape?0:43 })
  9886. .aspectRatio(1)
  9887. .opacity(this.opacityValueImage)
  9888. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  9889. // 设置左下角为缩放中心点
  9890. centerX: '0%',
  9891. centerY: '100%' })
  9892. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  9893. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  9894. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  9895. .align(Alignment.Center)//
  9896. .clip(true)
  9897. .shadow({
  9898. radius: 22,
  9899. type: ShadowType.BLUR,
  9900. color: 'on_primary'
  9901. })
  9902. .rotate({
  9903. x: 0,
  9904. y: 0,
  9905. z: 1,
  9906. angle: this.rotateAngle
  9907. })
  9908. .onClick(() => {
  9909. })
  9910. }
  9911. if (this.isPhoneLan()) {
  9912. Text(this.name)
  9913. .fontSize(18)
  9914. .fontWeight(FontWeight.Bold)
  9915. .margin({ top: 13 })
  9916. .textOverflow({ overflow: TextOverflow.Ellipsis })
  9917. .maxLines(1)
  9918. .width('99%')
  9919. .textAlign(TextAlign.Center)
  9920. .fontColor(Color.White)
  9921. }
  9922. }
  9923. .width('100%')
  9924. // 唱针以左上角为点选择逆时针40度
  9925. Image($r('app.media.ic_music_cover_hand'))
  9926. .height(130)
  9927. .margin({ bottom: 220, top: 0 })
  9928. .align(Alignment.Top)
  9929. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  9930. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  9931. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  9932. Column({ space: 8 }) {
  9933. Text(this.name)
  9934. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  9935. .fontWeight(FontWeight.Bold)
  9936. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9937. .maxLines(1)
  9938. .width('85%')
  9939. .textAlign(TextAlign.Center)
  9940. .fontColor(Color.White)
  9941. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  9942. Text(this.artist)
  9943. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  9944. .fontColor(Color.White)
  9945. .fontWeight(FontWeight.Bold)
  9946. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  9947. }
  9948. .justifyContent(FlexAlign.Start)
  9949. .zIndex(1)
  9950. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  9951. }
  9952. .margin({
  9953. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  9954. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  9955. top: this.isCoverOpacity() ? 0 : 20
  9956. })
  9957. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  9958. this.SingleLyricView()
  9959. }
  9960. if (this.isPhoneLan()) {
  9961. Column() {
  9962. this.playCenterView()
  9963. // this.playProgressView()
  9964. }
  9965. .position({ left: 28, bottom: 38 })
  9966. } else {
  9967. this.BottomControl()
  9968. }
  9969. }
  9970. .width(CommonConstants.FULL_PERCENT)
  9971. .clip(true)
  9972. }
  9973. @Builder
  9974. private musicNameInfo(isHidden: boolean) {
  9975. Row(){
  9976. Column({ space: 8 }) {
  9977. Text(this.name)
  9978. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 20)
  9979. .fontWeight(FontWeight.Bold)
  9980. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9981. .maxLines(1)
  9982. .width('99%')
  9983. .textAlign(TextAlign.Start)
  9984. .fontColor(Color.White)
  9985. Text(this.artist + ' ' + this.currentSong?.album)
  9986. .fontSize(this.isCoverOpacity() ? 12 : 15)
  9987. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9988. .fontColor(Color.White)
  9989. .textAlign(TextAlign.Start)
  9990. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  9991. .width('99%')
  9992. .maxLines(1)
  9993. }
  9994. .zIndex(1)
  9995. .layoutWeight(1)
  9996. .margin({ left: 15 })
  9997. Blank()
  9998. Row(){
  9999. Button({type:ButtonType.Circle,stateEffect:true}){
  10000. //添加或取消收藏
  10001. SymbolGlyph(Utility.getIsFav(this.favList,this.currentSong)?
  10002. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'))
  10003. .fontSize(22)
  10004. .fontColor([Color.White])
  10005. .alignSelf(ItemAlign.Center)
  10006. // .width(24)
  10007. .clickEffect({level:ClickEffectLevel.MIDDLE})
  10008. .aspectRatio(CommonConstants.ASPECT_RATIO)
  10009. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  10010. .onClick(async () => {
  10011. if(this.currentSong){
  10012. this.doFav(this.currentSong)
  10013. }
  10014. })
  10015. }
  10016. .margin({ left: 8,right:8 })
  10017. .backgroundColor(Color.Transparent)
  10018. .width(45)
  10019. .height(45)
  10020. }
  10021. }
  10022. .width(this.isLandscape?'83%':'90%')
  10023. .scale({ x: this.scaleValueText, y: this.scaleValueText }) // 添加缩放效果
  10024. .margin({ top: this.isCoverOpacity() ? 10 : isHidden ? 20 : 10 })
  10025. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  10026. }
  10027. @Builder
  10028. private PlayTitle() {
  10029. Row() {
  10030. Row() {
  10031. Image($r('app.media.ic_back_down'))
  10032. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  10033. .hitTestBehavior(HitTestMode.Transparent)
  10034. Text(this.name + ' ' + this.artist)
  10035. .fontColor(Color.White)
  10036. .fontSize($r('app.float.title_font_size'))
  10037. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  10038. .maxLines(1)
  10039. .visibility(Visibility.None)
  10040. .margin({ left: 2, right: 30 })
  10041. }
  10042. .layoutWeight(1)
  10043. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10044. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  10045. .onClick(() => {
  10046. this.setShowPlayFalse()
  10047. })
  10048. Column() {
  10049. AVCastPicker({
  10050. normalColor: Color.White,
  10051. onStateChange: this.onStateVastChange
  10052. })
  10053. .width(24)
  10054. .height(24)
  10055. }
  10056. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  10057. }
  10058. .width(PlayConstants.ROW_WIDTH)
  10059. }
  10060. @Builder
  10061. lyricSettingSheet(isPip: boolean) {
  10062. Scroll() {
  10063. this.lyricSetting(isPip)
  10064. }
  10065. .width('100%')
  10066. .height('100%')
  10067. }
  10068. @Builder
  10069. lyricSetting(isPip: boolean) {
  10070. Column() {
  10071. // 时间调节模块
  10072. if (!isPip) {
  10073. this.BuildTimeControls()
  10074. }
  10075. // 字号控制模块
  10076. this.BuildFontControls(isPip)
  10077. }
  10078. }
  10079. // 歌词时间偏移状态
  10080. @State timeOffset: number = 0.0
  10081. @State currentLyricColor: string = '#FFFFFF'
  10082. @State currentLyricColorPip: string = '#FFFFFF'
  10083. @State currentHighLightLyricColor: string = '#FF4081'
  10084. @State currentHighLightLyricColorPip: string = '#FF4081'
  10085. // 歌词字号状态
  10086. @State currentLyricSize: number = 20
  10087. @State currentLyricSizePip: number = 20
  10088. // 高亮歌词放大倍数
  10089. @State currentHightLyricSize: number = 1.2
  10090. @State currentHightLyricSizePip: number = 1.2
  10091. @State currentLyricLineSpace: number = 10
  10092. @State currentLyricLineSpacePip: number = 10
  10093. @State currentLyricAlignMode: number = 1
  10094. @State currentLyricAlignModePip: number = 1
  10095. @State blurDegree: number = 2
  10096. @State blurDegreePip: number = 2
  10097. @State isShowSelectColor: boolean = false
  10098. @State isShowHLSelectColor: boolean = false
  10099. @State isShowPipBgSelectColor: boolean = false
  10100. @State pipLyWidth: number = 330
  10101. @State pipLyHeight: number = 120
  10102. // 构建颜色选择器
  10103. @Builder
  10104. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  10105. Row({ space: 10 }) {
  10106. HSBColorPicker({
  10107. color: '#FFFFFF',
  10108. radius: 8,
  10109. layout: HSBColorPickerLayout.COLUMN,
  10110. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  10111. '#fa7105'],
  10112. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  10113. this.changeLyricColor(value, isPip, isBGPip)
  10114. })
  10115. .height(250)
  10116. .layoutWeight(1)
  10117. .padding(25)
  10118. }
  10119. .width('66%')
  10120. }
  10121. @State isOpenPip: boolean = false
  10122. @State pipBgIndex: number = 0
  10123. // 构建字号控制器
  10124. @Builder
  10125. BuildFontControls(isPip: boolean) {
  10126. Column() {
  10127. if (isPip) {
  10128. Column() {
  10129. Row() {
  10130. Text('悬浮歌词')
  10131. .margin({ left: 18 })
  10132. .fontSize(15)
  10133. .fontColor(Color.White)
  10134. .fontWeight(480)
  10135. .layoutWeight(1)
  10136. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  10137. .selectedColor(this.themeColor)
  10138. .switchPointColor(Color.White)
  10139. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10140. .margin({ right: 18 })
  10141. .onChange((checked: boolean) => {
  10142. this.isOpenPip = checked;
  10143. if (this.isOpenPip) {
  10144. this.startPip()
  10145. } else {
  10146. this.stopPip()
  10147. }
  10148. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  10149. })
  10150. .width(50)
  10151. .height(30);
  10152. }
  10153. .height(55)
  10154. }
  10155. .backgroundColor(Color.Transparent)
  10156. .borderRadius(15)
  10157. .margin({
  10158. left: 30,
  10159. right: 30,
  10160. top: 0,
  10161. bottom: 20
  10162. })
  10163. .padding(0)
  10164. .border({
  10165. color: Color.White,
  10166. width: 1.8
  10167. })
  10168. }else{
  10169. Column() {
  10170. Row() {
  10171. Text('单行歌词')
  10172. .margin({ left: 18 })
  10173. .fontSize(15)
  10174. .fontColor(Color.White)
  10175. .fontWeight(480)
  10176. .layoutWeight(1)
  10177. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  10178. .selectedColor(this.themeColor)
  10179. .switchPointColor(Color.White)
  10180. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10181. .margin({ right: 18 })
  10182. .onChange((checked: boolean) => {
  10183. this.isShowSingleLineLyric = checked;
  10184. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  10185. })
  10186. .width(50)
  10187. .height(30);
  10188. }
  10189. .height(55)
  10190. }
  10191. .backgroundColor(Color.Transparent)
  10192. .borderRadius(15)
  10193. .margin({
  10194. left: 30,
  10195. right: 30,
  10196. top: 10,
  10197. bottom: 10
  10198. })
  10199. .padding(0)
  10200. .border({
  10201. color: Color.White,
  10202. width: 1.8
  10203. })
  10204. }
  10205. Row() {
  10206. Text(`歌词居中:`)
  10207. .fontSize(14)
  10208. .fontColor(Color.White)
  10209. .margin({ left: 2 })
  10210. Row() {
  10211. ForEach(['居中', '居左'], (size: string, index: number) => {
  10212. Button(size)
  10213. .width(60)
  10214. .height(28)
  10215. .fontSize(12)
  10216. .fontColor('#FFFFFF')
  10217. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  10218. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  10219. .border({
  10220. color: (!isPip && this.currentLyricAlignMode === index) ||
  10221. (isPip && this.currentLyricAlignModePip === index) ?
  10222. '#007DFF' : '#DDDDDD',
  10223. width: 1.8
  10224. })
  10225. .onClick(() => {
  10226. this.setLyricAlignMode(index, isPip)
  10227. })
  10228. .margin({ left: 10, right: 8 })
  10229. })
  10230. }
  10231. .width('76%')
  10232. Blank()
  10233. }
  10234. .margin({
  10235. top: 10,
  10236. bottom: 10,
  10237. right: 20,
  10238. left: 20
  10239. })
  10240. if (isPip) {
  10241. Row() {
  10242. Text(`悬浮背景:`)
  10243. .fontSize(14)
  10244. .fontColor(Color.White)
  10245. Select([
  10246. { value: CommonConstants.PIP_LYRIC_BG[0] },
  10247. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  10248. .font({ size: 13, weight: FontWeight.Medium })
  10249. .fontColor(Color.White)
  10250. .margin({ left: 10 })
  10251. .selected(this.pipBgIndex)
  10252. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  10253. .onSelect(async (_index: number, text?: string | undefined) => {
  10254. this.pipBgIndex = _index
  10255. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  10256. if (this.pipBgIndex === 0) {
  10257. if (this.cover) {
  10258. this.pipBg = this.cover
  10259. } else {
  10260. this.pipBg = this.imageColor
  10261. }
  10262. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  10263. } else {
  10264. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  10265. }
  10266. })
  10267. Column() {
  10268. }
  10269. .backgroundColor(this.pipBg)
  10270. .margin({ left: 10, right: 10 })
  10271. .borderRadius(20)
  10272. .height(28)
  10273. .width(28)
  10274. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10275. Row() {
  10276. SymbolGlyph($r('sys.symbol.paintbrush'))
  10277. .fontColor([Color.White])
  10278. .effectStrategy(1)
  10279. Text(`选择颜色`)
  10280. .fontSize(13)
  10281. .margin({ left: 10 })
  10282. .fontColor(Color.White)
  10283. }
  10284. }
  10285. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  10286. .backgroundColor(Color.Transparent)
  10287. .border({
  10288. color: '#FFFFFF',
  10289. radius: 20,
  10290. width: 1.8
  10291. })
  10292. .height(36)
  10293. .width(110)
  10294. .onClick(() => {
  10295. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  10296. })
  10297. .bindPopup(this.isShowPipBgSelectColor, {
  10298. builder: this.SelectColor(false, isPip, true),
  10299. placement: Placement.Top,
  10300. mask: { color: '#33000000' },
  10301. enableArrow: false, //是否显示箭头
  10302. showInSubWindow: false,
  10303. onStateChange: (e) => {
  10304. if (!e.isVisible) {
  10305. this.isShowPipBgSelectColor = false
  10306. }
  10307. }
  10308. })
  10309. }
  10310. .width('76%')
  10311. .margin({ bottom: 5, right: 45, left: 20 })
  10312. }
  10313. if (!isPip) {
  10314. Row() {
  10315. Text(`高亮居中:`)
  10316. .fontSize(14)
  10317. .fontColor(Color.White)
  10318. Column() {
  10319. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  10320. .selectedColor(this.themeColor)
  10321. .switchPointColor(Color.White)
  10322. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10323. .onChange((checked: boolean) => {
  10324. this.isHightLightCenter = checked;
  10325. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  10326. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  10327. })
  10328. .width(50)
  10329. .height(30)
  10330. .alignSelf(ItemAlign.Start)
  10331. .margin({ left: 12 })
  10332. Blank()
  10333. }
  10334. .width('76%')
  10335. }
  10336. .margin({
  10337. left: 20,
  10338. right: 15,
  10339. top: 10,
  10340. bottom: 10
  10341. })
  10342. }
  10343. Row() {
  10344. Text(`歌词颜色:`)
  10345. .fontSize(14)
  10346. .fontColor(Color.White)
  10347. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  10348. .fontSize(15)
  10349. .fontColor(Color.White)
  10350. .margin({ left: 12, right: 12 })
  10351. Column() {
  10352. }
  10353. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  10354. .margin({ right: 12 })
  10355. .borderRadius(20)
  10356. .height(28)
  10357. .width(28)
  10358. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10359. Row() {
  10360. SymbolGlyph($r('sys.symbol.paintbrush'))
  10361. .fontColor([Color.White])
  10362. .effectStrategy(1)
  10363. Text(`选择颜色`)
  10364. .fontSize(13)
  10365. .margin({ left: 10 })
  10366. .fontColor(Color.White)
  10367. }
  10368. }
  10369. .backgroundColor(Color.Transparent)
  10370. .border({
  10371. color: '#FFFFFF',
  10372. radius: 20,
  10373. width: 1.8
  10374. })
  10375. .height(36)
  10376. .width(110)
  10377. .onClick(() => {
  10378. this.isShowSelectColor = !this.isShowSelectColor
  10379. })
  10380. .bindPopup(this.isShowSelectColor, {
  10381. builder: this.SelectColor(false, isPip),
  10382. placement: Placement.Top,
  10383. mask: { color: '#33000000' },
  10384. enableArrow: false, //是否显示箭头
  10385. showInSubWindow: false,
  10386. onStateChange: (e) => {
  10387. if (!e.isVisible) {
  10388. this.isShowSelectColor = false
  10389. }
  10390. }
  10391. })
  10392. }
  10393. .width('76%')
  10394. .margin({
  10395. top: 10,
  10396. bottom: 10,
  10397. right: 45,
  10398. left: 20
  10399. })
  10400. Row() {
  10401. Text(`高亮颜色:`)
  10402. .fontSize(14)
  10403. .fontColor(Color.White)
  10404. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  10405. .fontSize(15)
  10406. .fontColor(Color.White)
  10407. .margin({ left: 12, right: 12 })
  10408. Column() {
  10409. }
  10410. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  10411. .margin({ right: 12 })
  10412. .borderRadius(20)
  10413. .height(28)
  10414. .width(28)
  10415. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10416. Row() {
  10417. SymbolGlyph($r('sys.symbol.paintbrush'))
  10418. .fontColor([Color.White])
  10419. .effectStrategy(1)
  10420. Text(`选择颜色`)
  10421. .fontSize(13)
  10422. .margin({ left: 10 })
  10423. .fontColor(Color.White)
  10424. }
  10425. }
  10426. .backgroundColor(Color.Transparent)
  10427. .border({
  10428. color: '#FFFFFF',
  10429. radius: 20,
  10430. width: 1.8
  10431. })
  10432. .height(36)
  10433. .width(110)
  10434. .onClick(() => {
  10435. this.isShowHLSelectColor = !this.isShowHLSelectColor
  10436. })
  10437. .bindPopup(this.isShowHLSelectColor, {
  10438. builder: this.SelectColor(true, isPip),
  10439. placement: Placement.Top,
  10440. mask: { color: '#33000000' },
  10441. enableArrow: false, //是否显示箭头
  10442. showInSubWindow: false,
  10443. onStateChange: (e) => {
  10444. if (!e.isVisible) {
  10445. this.isShowHLSelectColor = false
  10446. }
  10447. }
  10448. })
  10449. }
  10450. .width('76%')
  10451. .margin({
  10452. top: 10,
  10453. bottom: 10,
  10454. right: 45,
  10455. left: 20
  10456. })
  10457. if (isPip) {
  10458. Row() {
  10459. Text(`显示宽度:`)
  10460. .fontSize(14)
  10461. .fontColor(Color.White)
  10462. Slider({
  10463. value: this.pipLyWidth,
  10464. min: 10,
  10465. max: 800,
  10466. step: 1,
  10467. style: SliderStyle.OutSet
  10468. })
  10469. .blockColor(this.themeColor)
  10470. .trackColor($r('app.color.speed_text_color'))
  10471. .selectedColor(Color.White)
  10472. .trackThickness(6)
  10473. .onChange((value: number) => {
  10474. this.pipLyWidth = value
  10475. if (this.pipController) {
  10476. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10477. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  10478. }
  10479. })
  10480. .width('76%')
  10481. }
  10482. .margin({
  10483. left: 20,
  10484. right: 15,
  10485. top: 5,
  10486. bottom: 5
  10487. })
  10488. Row() {
  10489. Text(`显示高度:`)
  10490. .fontSize(14)
  10491. .fontColor(Color.White)
  10492. Slider({
  10493. value: this.pipLyHeight,
  10494. min: 10,
  10495. max: 1000,
  10496. step: 1,
  10497. style: SliderStyle.OutSet
  10498. })
  10499. .blockColor(this.themeColor)
  10500. .trackColor($r('app.color.speed_text_color'))
  10501. .selectedColor(Color.White)
  10502. .trackThickness(6)
  10503. .onChange((value: number) => {
  10504. this.pipLyHeight = value
  10505. if (this.pipController) {
  10506. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10507. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  10508. }
  10509. })
  10510. .width('76%')
  10511. }
  10512. .margin({
  10513. left: 20,
  10514. right: 15,
  10515. top: 5,
  10516. bottom: 5
  10517. })
  10518. }
  10519. Row() {
  10520. Text(`歌词字号:`)
  10521. .fontSize(14)
  10522. .fontColor(Color.White)
  10523. Slider({
  10524. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  10525. min: 12,
  10526. max: 30,
  10527. step: 0.1,
  10528. style: SliderStyle.OutSet
  10529. })
  10530. .blockColor(this.themeColor)
  10531. .trackColor($r('app.color.speed_text_color'))
  10532. .selectedColor(Color.White)
  10533. .trackThickness(6)
  10534. .onChange((value: number) => {
  10535. this.setLyricTextSize(value, isPip)
  10536. })
  10537. .width('76%')
  10538. }
  10539. .margin({
  10540. left: 20,
  10541. right: 15,
  10542. top: 5,
  10543. bottom: 5
  10544. })
  10545. Row() {
  10546. Text(`高亮倍数:`)
  10547. .fontSize(14)
  10548. .fontColor(Color.White)
  10549. Slider({
  10550. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  10551. min: 1,
  10552. max: 2,
  10553. step: 0.1,
  10554. style: SliderStyle.OutSet
  10555. })
  10556. .blockColor(this.themeColor)
  10557. .trackColor($r('app.color.speed_text_color'))
  10558. .selectedColor(Color.White)
  10559. .trackThickness(6)
  10560. .onChange((value: number) => {
  10561. this.setHighLyricTextSize(value, isPip)
  10562. })
  10563. .width('76%')
  10564. }
  10565. .margin({
  10566. left: 20,
  10567. right: 15,
  10568. top: 5,
  10569. bottom: 5
  10570. })
  10571. Row() {
  10572. Text(`歌词间隙:`)
  10573. .fontSize(14)
  10574. .fontColor(Color.White)
  10575. Slider({
  10576. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  10577. min: 0,
  10578. max: 100,
  10579. step: 1,
  10580. style: SliderStyle.OutSet
  10581. })
  10582. .blockColor(this.themeColor)
  10583. .trackColor($r('app.color.speed_text_color'))
  10584. .selectedColor(Color.White)
  10585. .trackThickness(6)
  10586. .onChange((value: number) => {
  10587. this.setLyricLineSpace(value, isPip)
  10588. })
  10589. .width('76%')
  10590. }
  10591. .margin({
  10592. left: 20,
  10593. right: 15,
  10594. top: 5,
  10595. bottom: 5
  10596. })
  10597. //取值间隔为100,默认为400,取值越大,字体越粗
  10598. Row() {
  10599. Text(`歌词字重:`)
  10600. .fontSize(14)
  10601. .fontColor(Color.White)
  10602. Slider({
  10603. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  10604. min: 100,
  10605. max: 900,
  10606. step: 100,
  10607. style: SliderStyle.OutSet
  10608. })
  10609. .blockColor(this.themeColor)
  10610. .trackColor($r('app.color.speed_text_color'))
  10611. .selectedColor(Color.White)
  10612. .trackThickness(6)
  10613. .onChange((value: number) => {
  10614. if (isPip) {
  10615. this.lyricTextWeightPip = value
  10616. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  10617. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  10618. } else {
  10619. this.lyricTextWeight = value
  10620. this.lyricController.setTextWeight(this.lyricTextWeight)
  10621. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  10622. }
  10623. })
  10624. .width('76%')
  10625. }
  10626. .margin({
  10627. left: 20,
  10628. right: 15,
  10629. top: 5,
  10630. bottom: 5
  10631. })
  10632. if (!isPip) {
  10633. Row() {
  10634. Text(`歌词模糊:`)
  10635. .fontSize(14)
  10636. .fontColor(Color.White)
  10637. Slider({
  10638. value: isPip ? this.blurDegreePip : this.blurDegree,
  10639. min: 0,
  10640. max: 5,
  10641. step: 0.1,
  10642. style: SliderStyle.OutSet
  10643. })
  10644. .blockColor(this.themeColor)
  10645. .trackColor($r('app.color.speed_text_color'))
  10646. .selectedColor(Color.White)
  10647. .trackThickness(6)
  10648. .onChange((value: number) => {
  10649. this.setBlurDegree(value, isPip)
  10650. })
  10651. .width('76%')
  10652. }
  10653. .margin({
  10654. left: 20,
  10655. right: 15,
  10656. top: 5,
  10657. bottom: 15
  10658. })
  10659. }
  10660. Row() {
  10661. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  10662. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  10663. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  10664. }
  10665. .justifyContent(FlexAlign.Center)
  10666. .margin({ top: 3, bottom: 10 })
  10667. }
  10668. }
  10669. private setBlurDegree(index: number, isPip: boolean) {
  10670. if (isPip) {
  10671. this.blurDegreePip = index
  10672. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  10673. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  10674. } else {
  10675. this.blurDegree = index
  10676. this.lyricController.setBlurDegree(this.blurDegree)
  10677. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  10678. }
  10679. }
  10680. private setLyricAlignMode(index: number, isPip: boolean) {
  10681. if (isPip) {
  10682. this.currentLyricAlignModePip = index
  10683. if (this.currentLyricAlignModePip === 1) {
  10684. this.lyricControllerXF.setAlignMode("left")
  10685. } else {
  10686. this.lyricControllerXF.setAlignMode("center")
  10687. }
  10688. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  10689. } else {
  10690. this.currentLyricAlignMode = index
  10691. if (this.currentLyricAlignMode === 1) {
  10692. this.lyricController.setAlignMode("left")
  10693. } else {
  10694. this.lyricController.setAlignMode("center")
  10695. }
  10696. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  10697. }
  10698. }
  10699. private setLyricTextSize(index: number, isPip: boolean) {
  10700. if (isPip) {
  10701. this.currentLyricSizePip = index
  10702. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  10703. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  10704. } else {
  10705. this.currentLyricSize = index
  10706. this.lyricController.setTextSize(this.currentLyricSize)
  10707. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  10708. }
  10709. }
  10710. private setHighLyricTextSize(scale: number, isPip: boolean) {
  10711. if (isPip) {
  10712. this.currentHightLyricSizePip = scale
  10713. this.lyricControllerXF
  10714. .setHighlightScale(this.currentHightLyricSizePip)
  10715. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  10716. } else {
  10717. this.currentHightLyricSize = scale
  10718. this.lyricController
  10719. .setHighlightScale(this.currentHightLyricSize)
  10720. PreferencesUtil.putSync('HighLyricTextSize', scale)
  10721. }
  10722. }
  10723. private setLyricLineSpace(index: number, isPip: boolean) {
  10724. if (isPip) {
  10725. this.currentLyricLineSpacePip = index
  10726. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  10727. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  10728. } else {
  10729. this.currentLyricLineSpace = index
  10730. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  10731. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  10732. }
  10733. }
  10734. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  10735. LogUtil.info('onecold isBG = ' + isBG)
  10736. if (isBG) { //如果是设置悬浮背景
  10737. this.pipBg = color
  10738. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  10739. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  10740. return
  10741. }
  10742. if (isPip) {
  10743. this.currentLyricColorPip = color
  10744. this.lyricControllerXF
  10745. .setTextColor(this.currentLyricColorPip)
  10746. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  10747. } else {
  10748. this.currentLyricColor = color
  10749. this.lyricController
  10750. .setTextColor(this.currentLyricColor)
  10751. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  10752. }
  10753. }
  10754. private changeLyricHightLightColor(color: string, isPip: boolean) {
  10755. if (isPip) {
  10756. this.currentHighLightLyricColorPip = color
  10757. this.lyricControllerXF
  10758. .setHighlightColor(this.currentHighLightLyricColorPip)
  10759. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  10760. } else {
  10761. this.currentHighLightLyricColor = color
  10762. this.lyricController
  10763. .setHighlightColor(this.currentHighLightLyricColor)
  10764. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  10765. }
  10766. }
  10767. // 构建时间控制器
  10768. @Builder
  10769. BuildTimeControls() {
  10770. Column() {
  10771. // 时间显示
  10772. Text(this.getTimeText())
  10773. .fontSize(18)
  10774. .fontColor(Color.White)
  10775. .margin({ bottom: 10 })
  10776. Row() {
  10777. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  10778. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  10779. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  10780. }
  10781. .justifyContent(FlexAlign.Center)
  10782. }
  10783. .margin({ top: 12, bottom: 8 })
  10784. }
  10785. // 精度按钮组件
  10786. @Builder
  10787. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  10788. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10789. Column() {
  10790. Image(icon)
  10791. .width(28)
  10792. .margin({ bottom: 5 })
  10793. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  10794. Text(label)
  10795. .fontSize(12)
  10796. .fontColor('#FFFFFF')
  10797. }
  10798. }
  10799. .backgroundColor(Color.Transparent)
  10800. .enabled(!this.isButtonDisabled(step))
  10801. .onClick(() => this.handlePrecisionAdjust(step))
  10802. .padding(5)
  10803. .width(66)
  10804. .height(66)
  10805. .margin({ left: 18, right: 18 })
  10806. .border({
  10807. color: '#FFFFFF',
  10808. width: 1.8
  10809. })
  10810. }
  10811. private handlePrecisionAdjust(step: number) {
  10812. if (step === 0) {
  10813. this.timeOffset = 0
  10814. return
  10815. }
  10816. // 精度处理:保留1位小数
  10817. const newOffset = Number((this.timeOffset + step).toFixed(5))
  10818. // 边界保护(±15.0秒)
  10819. if (newOffset < -30.0 || newOffset > 30.0) {
  10820. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  10821. return
  10822. }
  10823. // 状态更新
  10824. this.timeOffset = newOffset
  10825. }
  10826. // 按钮禁用逻辑
  10827. private isButtonDisabled(step: number): boolean {
  10828. const futureOffset = this.timeOffset + step
  10829. return (futureOffset < -30.0) || (futureOffset > 30.0)
  10830. }
  10831. // 时间显示文本升级
  10832. private getTimeText(): string {
  10833. const absValue = Math.abs(this.timeOffset)
  10834. return this.timeOffset === 0
  10835. ? '歌词时间已重置'
  10836. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  10837. }
  10838. // 导入 本地歌词 搜索歌词
  10839. @Builder
  10840. pushLyricButton(icon: Resource, step: number, label: string) {
  10841. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10842. Row() {
  10843. Image(icon)
  10844. .width(14)
  10845. .margin({ left: 13 })
  10846. Text(label)
  10847. .fontSize(12)
  10848. .margin({ left: 6 })
  10849. .fontColor('#FFFFFF')
  10850. }
  10851. }
  10852. .onClick(() => {
  10853. switch (step) {
  10854. case 0:
  10855. this.callFilePickerSelectFileForLyric()
  10856. break;
  10857. case 1:
  10858. //判断有没有设置api
  10859. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  10860. this.isLyricSetting = false
  10861. this.showTipsDialog()
  10862. return
  10863. }
  10864. if (StrUtil.isNotEmpty(this.videoUrl)) {
  10865. ToastUtil.showToast('正在获取')
  10866. this.isLyricSetting = false
  10867. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  10868. this.initLyric(lyricPath, true);
  10869. }
  10870. break;
  10871. }
  10872. })
  10873. .padding(5)
  10874. .width(110)
  10875. .backgroundColor(Color.Transparent)
  10876. .height(40)
  10877. .margin({ left: 6, right: 6 })
  10878. .border({
  10879. color: '#FFFFFF',
  10880. radius: 20,
  10881. width: 1.8
  10882. })
  10883. }
  10884. showVipDialog() {
  10885. DialogHelper.showCustomContentDialog({
  10886. dialogId: 'vip',
  10887. title: "友情提示",
  10888. autoCancel: false, //点击遮障层时,不关闭弹窗
  10889. backCancel: true, //点击返回键,不关闭弹窗
  10890. contentBuilder: () => {
  10891. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  10892. },
  10893. buttons: [],
  10894. })
  10895. }
  10896. //去赞助的自定义内容
  10897. @Builder
  10898. customVipBuilder(content: string) {
  10899. Column() {
  10900. Text(content)
  10901. .fontColor(Color.Gray)
  10902. .fontSize(16)
  10903. .alignSelf(ItemAlign.Start)
  10904. .margin({ bottom: 15 })
  10905. .fontSize(16)
  10906. Row() {
  10907. Button('取消')
  10908. .fontColor(Color.White)
  10909. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  10910. .height(50)
  10911. .layoutWeight(1)
  10912. .stateEffect(true)
  10913. .margin({ right: 6 })
  10914. .onClick(() => {
  10915. DialogHelper.closeDialog('vip'); //关闭弹框
  10916. })
  10917. Button('开通')
  10918. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  10919. .layoutWeight(1)
  10920. .height(50)
  10921. .backgroundColor(this.themeColor)
  10922. .stateEffect(true)
  10923. .margin({ left: 6 })
  10924. .onClick(() => {
  10925. DialogHelper.closeDialog('vip'); //关闭弹框
  10926. this.isShowPlay = false
  10927. this.mType = 1 //跳转到用户中心
  10928. // router.pushUrl({
  10929. // url: 'pages/VipPage'
  10930. // }, router.RouterMode.Single);
  10931. })
  10932. }
  10933. }
  10934. .width("100%")
  10935. .padding(10)
  10936. }
  10937. showTipsDialog() {
  10938. DialogHelper.showCustomContentDialog({
  10939. dialogId: 'tips',
  10940. title: "友情提示",
  10941. autoCancel: false, //点击遮障层时,不关闭弹窗
  10942. backCancel: true, //点击返回键,不关闭弹窗
  10943. contentBuilder: () => {
  10944. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  10945. },
  10946. buttons: [],
  10947. })
  10948. }
  10949. @Builder
  10950. customTipsBuilder(content: string) {
  10951. Column() {
  10952. Text(content)
  10953. .fontColor(Color.Gray)
  10954. .fontSize(16)
  10955. .alignSelf(ItemAlign.Start)
  10956. .margin({ bottom: 15 })
  10957. .fontSize(16)
  10958. Row() {
  10959. Button('取消')
  10960. .fontColor(Color.White)
  10961. .backgroundColor(this.themeColor)
  10962. .height(50)
  10963. .layoutWeight(1)
  10964. .stateEffect(true)
  10965. .margin({ right: 6 })
  10966. .onClick(() => {
  10967. DialogHelper.closeDialog('tips'); //关闭弹框
  10968. })
  10969. Button('跳转')
  10970. .fontColor(Color.White)//
  10971. .layoutWeight(1)
  10972. .height(50)
  10973. .backgroundColor(this.themeColor)
  10974. .stateEffect(true)
  10975. .margin({ left: 6 })
  10976. .onClick(() => {
  10977. DialogHelper.closeDialog('tips'); //关闭弹框
  10978. this.isShowEdit = false
  10979. this.longItemFilePath = ''
  10980. // if(this.isGridMusic&&!this.isShowPlay){
  10981. // this.longItemFilePath== ''
  10982. // }else{
  10983. // this.isShowEdit = false
  10984. // }
  10985. this.isShowMoreView = false;
  10986. this.isShowPlay = false
  10987. this.mType = 4
  10988. // router.pushUrl({
  10989. // url: 'pages/SettingPage'
  10990. // }, router.RouterMode.Single);
  10991. })
  10992. }
  10993. }
  10994. .width("100%")
  10995. .padding(10)
  10996. }
  10997. @Builder
  10998. PlayMoreSheet() {
  10999. Column() {
  11000. this.MoreList()
  11001. }
  11002. .width('100%')
  11003. .height('100%')
  11004. }
  11005. @Builder
  11006. MoreList() {
  11007. Scroll() {
  11008. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  11009. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  11010. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  11011. Row() {
  11012. if (more.id === 3&&this.currentSong) {
  11013. Image(more.image)
  11014. .width(24)
  11015. .height(24)
  11016. .margin({ left: 10, right: 10 })
  11017. Text(more.title)
  11018. .fontSize(16)
  11019. .fontColor(Color.White)
  11020. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  11021. height: this.isCoverOpacity() ? '95%' : '95%',
  11022. dragBar: true,
  11023. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11024. showClose: true,
  11025. blurStyle: BlurStyle.Thin,
  11026. backgroundColor: Color.Transparent,
  11027. title: { title: '歌曲信息' }
  11028. })
  11029. } else if (more.id === 15 && this.currentSong) { //编辑标签
  11030. Image(more.image)
  11031. .width(24)
  11032. .height(24)
  11033. .margin({ left: 10, right: 10 })
  11034. Text(more.title)
  11035. .fontSize(16)
  11036. .fontColor(Color.White)
  11037. } else if (more.id === 5) { //定时关闭
  11038. Image(more.image)
  11039. .width(24)
  11040. .height(24)
  11041. .margin({ left: 10, right: 10 })
  11042. Text(more.title)
  11043. .fontSize(16)
  11044. .fontColor(Color.White)
  11045. .onClick(() => {
  11046. this.doMore(more.id)
  11047. })
  11048. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  11049. height: this.isCoverOpacity() ? '95%' : '95%',
  11050. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11051. dragBar: true,
  11052. showClose: true,
  11053. title: { title: $r('app.string.time_close') }
  11054. })
  11055. } else if (more.id === 2) { //歌词设置
  11056. Image(more.image)
  11057. .width(24)
  11058. .height(24)
  11059. .margin({ left: 10, right: 10 })
  11060. Text(more.title)
  11061. .fontSize(16)
  11062. .fontColor(Color.White)
  11063. } else if (more.id === 16) { //悬浮歌词设置
  11064. Image(more.image)
  11065. .width(24)
  11066. .height(24)
  11067. .margin({ left: 10, right: 10 })
  11068. Text(more.title)
  11069. .fontSize(16)
  11070. .fontColor(Color.White)
  11071. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  11072. height: this.isCoverOpacity() ? '95%' : '95%',
  11073. dragBar: true,
  11074. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11075. showClose: true,
  11076. blurStyle: BlurStyle.Thin,
  11077. backgroundColor: Color.Transparent,
  11078. title: { title: '悬浮歌词' }
  11079. })
  11080. } else if (more.id === 11) {
  11081. Image(more.image)
  11082. .width(24)
  11083. .height(24)
  11084. .margin({ left: 10, right: 10 })
  11085. Text(more.title)
  11086. .fontSize(16)
  11087. .fontColor(Color.White)
  11088. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  11089. height: this.isCoverOpacity() ? '95%' : '60%',
  11090. dragBar: true,
  11091. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11092. showClose: true,
  11093. blurStyle: BlurStyle.Thin,
  11094. backgroundColor: Color.Transparent,
  11095. title: { title: '跳过头尾' }
  11096. })
  11097. } else if (more.id === 12) { //投播
  11098. AVCastPicker({
  11099. customPicker: (): void => this.TPImageBuilder(more),
  11100. onStateChange: (state) => {
  11101. if (state == AVCastPickerState.STATE_APPEARING) {
  11102. console.log(' The picker starts showing.');
  11103. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  11104. console.log(' The picker finishes presenting.');
  11105. }
  11106. },
  11107. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  11108. sessionType: 'video'
  11109. })
  11110. .id('AVCastPicker')
  11111. } else {
  11112. Image(more.image)
  11113. .width(24)
  11114. .height(24)
  11115. .fillColor(Color.White)
  11116. .margin({ left: 10, right: 10 })
  11117. .onClick(() => {
  11118. this.doMore(more.id)
  11119. })
  11120. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  11121. .fontSize(16)
  11122. .fontColor(Color.White)
  11123. .onClick(() => {
  11124. this.doMore(more.id)
  11125. })
  11126. Select([//倍速
  11127. { value: '0.25x' },
  11128. { value: '0.5x' },
  11129. { value: '0.75x' },
  11130. { value: '1x' },
  11131. { value: '1.25x' },
  11132. { value: '1.5x' },
  11133. { value: '1.75x' },
  11134. { value: '2x' },
  11135. { value: '3x' }])
  11136. .font({ size: 16, weight: FontWeight.Medium })
  11137. .fontColor($r('sys.color.white'))
  11138. .margin({ left: 25 })
  11139. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  11140. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  11141. .value(Utility.optimizedFormat(this.playSpeed))
  11142. .onSelect(async (_index: number, text?: string | undefined) => {
  11143. let speed = parseFloat(text?.replace('x', '') || '1');
  11144. if (!CommonConstants.video_speed_list.includes(speed)) {
  11145. speed = 1;
  11146. }
  11147. this.playSpeed = speed
  11148. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  11149. })
  11150. Slider({
  11151. value: this.volume,
  11152. min: 0,
  11153. max: 1,
  11154. step: 0.1,
  11155. style: SliderStyle.OutSet
  11156. })
  11157. .margin({ left: 18, right: 8 })
  11158. .blockColor(this.themeColor)
  11159. .trackColor($r('app.color.speed_text_color'))
  11160. .selectedColor(Color.White)
  11161. .trackThickness(9)
  11162. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  11163. .onChange((value: number) => {
  11164. this.volume = value;
  11165. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  11166. PreferencesUtil.putSync('DefalutVolume',this.volume)
  11167. })
  11168. .layoutWeight(1)
  11169. Blank()
  11170. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  11171. .selectedColor(this.themeColor)
  11172. .switchPointColor(Color.White)
  11173. .margin({ right: 15 })
  11174. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11175. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  11176. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11177. if (more.id == 6) {
  11178. this.isMusicMemoryPlay = checked;
  11179. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  11180. if (this.isMusicMemoryPlay) {
  11181. ToastUtil.showToast('记忆播放已开启')
  11182. } else {
  11183. ToastUtil.showToast('记忆播放已关闭')
  11184. }
  11185. }
  11186. })
  11187. .width(48)
  11188. .height(24);
  11189. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  11190. .selectedColor(this.themeColor)
  11191. .switchPointColor(Color.White)
  11192. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11193. .margin({ right: 15 })
  11194. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  11195. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11196. if (more.id == 7) {
  11197. this.isMusicBGCover = checked;
  11198. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  11199. if (this.isMusicBGCover) {
  11200. ToastUtil.showToast('播放背景随音乐封面已开启')
  11201. } else {
  11202. ToastUtil.showToast('播放背景随音乐封面已关闭')
  11203. }
  11204. }
  11205. })
  11206. .width(48)
  11207. .height(24);
  11208. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  11209. .selectedColor(this.themeColor)
  11210. .switchPointColor(Color.White)
  11211. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11212. .margin({ right: 15 })
  11213. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  11214. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11215. if (more.id == 8) {
  11216. this.isSavePlayMode = checked;
  11217. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  11218. if (this.isSavePlayMode) {
  11219. ToastUtil.showToast('保存播放模式已开启')
  11220. } else {
  11221. ToastUtil.showToast('保存播放模式已关闭')
  11222. }
  11223. }
  11224. })
  11225. .width(48)
  11226. .height(24);
  11227. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  11228. .selectedColor(this.themeColor)
  11229. .switchPointColor(Color.White)
  11230. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11231. .margin({ right: 15 })
  11232. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  11233. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11234. if (more.id == 13) {
  11235. this.isCoverRectangle = checked;
  11236. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  11237. if (this.isCoverRectangle) {
  11238. ToastUtil.showToast('封面方形已开启')
  11239. this.animationRoFun()
  11240. } else {
  11241. ToastUtil.showToast('封面圆形已开启')
  11242. this.animationRoFun()
  11243. }
  11244. }
  11245. })
  11246. .width(48)
  11247. .height(24);
  11248. Toggle({ type: ToggleType.Switch, isOn: this.isShowBgLiuGUANG })
  11249. .selectedColor(this.themeColor)
  11250. .switchPointColor(Color.White)
  11251. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11252. .margin({ right: 15 })
  11253. .visibility(more.id == 21 ? Visibility.Visible : Visibility.None)
  11254. .onChange((checked: boolean) => { // 是否开启背景流光效果
  11255. if (more.id == 21) {
  11256. this.isShowBgLiuGUANG = checked;
  11257. PreferencesUtil.putSync('isShowBgLiuGUANG',this.isShowBgLiuGUANG)
  11258. }
  11259. })
  11260. .width(48)
  11261. .height(24);
  11262. }
  11263. }
  11264. .width('100%')
  11265. .height(45)
  11266. .padding(15)
  11267. .backgroundColor(Color.Transparent)
  11268. .borderRadius(12)
  11269. .margin({ bottom: 6 })
  11270. }
  11271. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  11272. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  11273. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  11274. .backgroundColor(Color.Transparent)
  11275. .onClick(() => {
  11276. this.doMore(more.id)
  11277. })
  11278. });
  11279. }
  11280. .width('100%')
  11281. .padding(16)
  11282. }.margin({ bottom: 18 })
  11283. }
  11284. @Builder
  11285. TPImageBuilder(more: MoreItem): void {
  11286. Row() {
  11287. Image($r('app.media.tuoping'))
  11288. .width(22)
  11289. .height(22)
  11290. .margin({ left: 10, right: 10 })
  11291. Text(more.title)
  11292. .fontSize(16)
  11293. .fontColor(Color.White)
  11294. }
  11295. .width('100%')
  11296. .layoutWeight(1)
  11297. .alignItems(VerticalAlign.Center)
  11298. .justifyContent(FlexAlign.Start)
  11299. }
  11300. private moreItems: MoreItem[] = [
  11301. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  11302. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  11303. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  11304. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  11305. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  11306. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  11307. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  11308. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  11309. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  11310. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  11311. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  11312. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  11313. { id: 4, image: $r('app.media.share2'), title: '分享' },
  11314. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  11315. // { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  11316. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  11317. { id : 21, image: $r('app.media.music_red'), title: '开启背景流光' },
  11318. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  11319. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  11320. ];
  11321. @State isShowBgLiuGUANG: boolean = true;
  11322. @State isShowMoreView: boolean = false;
  11323. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  11324. @State isShowTimeCloseMore: boolean = false
  11325. @State isShowDetailMore: boolean = false
  11326. @State isMusicBGCover: boolean = true
  11327. @State isSavePlayMode: boolean = true
  11328. @State isLyricSetting: boolean = false
  11329. @State isJumpSetting: boolean = false
  11330. @State isShowEdit: boolean = false
  11331. @State showPipLyric: boolean = false
  11332. async setRingTone() {
  11333. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  11334. return
  11335. }
  11336. // 确定后的逻辑
  11337. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  11338. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  11339. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  11340. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  11341. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  11342. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  11343. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  11344. , this.videoUrl, this.name).then(res => {
  11345. LogUtil.info('onecold setFlag :' + res);
  11346. });
  11347. }
  11348. doMore(moreId: number) {
  11349. switch (moreId) {
  11350. case 2: //歌词
  11351. this.isLyricSetting = !this.isLyricSetting;
  11352. this.isShowMoreView = false
  11353. break;
  11354. case 3: //详情
  11355. this.isShowDetailMore = !this.isShowDetailMore;
  11356. break;
  11357. case 4: //分享
  11358. if (this.currentSong !== undefined) {
  11359. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  11360. }
  11361. this.isShowMoreView = false
  11362. break;
  11363. case 5: //定时关闭
  11364. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  11365. break;
  11366. case 10: //设为铃声
  11367. this.setRingTone()
  11368. this.isShowMoreView = false
  11369. break;
  11370. case 11: //跳过头尾
  11371. this.isJumpSetting = !this.isJumpSetting;
  11372. break;
  11373. case 13: //倍速
  11374. break;
  11375. case 14: //搜索封面
  11376. if (this.currentSong !== undefined) {
  11377. this.doSearchCover(this.currentSong)
  11378. }
  11379. this.isShowMoreView = false
  11380. break;
  11381. case 15: //编辑标签
  11382. this.initEditFields(this.currentSong)
  11383. this.tempLyricContent = this.lyricContent
  11384. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  11385. this.lyricConStr = this.tempLyricContent
  11386. }
  11387. this.isShowEdit = !this.isShowEdit;
  11388. break;
  11389. case 16: //悬浮歌词
  11390. this.showPipLyric = !this.showPipLyric;
  11391. break;
  11392. case 17: //横屏模式
  11393. if (this.isLandscape) {
  11394. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  11395. } else {
  11396. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  11397. }
  11398. this.isShowMoreView = false
  11399. break;
  11400. case 20://AB循环
  11401. this.isABSheet = !this.isABSheet
  11402. break;
  11403. }
  11404. }
  11405. //AB循环
  11406. @State isOpenAB:boolean = false
  11407. @State jumpATime:number = 0
  11408. @State jumpBTime:number = 0
  11409. @State isABSheet:boolean = false
  11410. @Builder
  11411. ABLoopSheet() {
  11412. ABLoopComptent({
  11413. jumpATime:this.jumpATime,
  11414. jumpBTime:this.jumpBTime,
  11415. onClickAItem: async ()=>{
  11416. if(this.mIjkMediaPlayer){
  11417. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  11418. }
  11419. },
  11420. onClickBItem: async ()=>{
  11421. if(this.mIjkMediaPlayer){
  11422. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  11423. if(this.jumpBTime<=this.jumpATime){
  11424. ToastUtil.showToast('设置B点时间不能小于A点时间')
  11425. this.jumpBTime = 0
  11426. }
  11427. }
  11428. },
  11429. onCancleButtonClick: async ()=>{
  11430. this.isOpenAB = false
  11431. this.isABSheet = false
  11432. },
  11433. onStartButtonClick: async ()=>{
  11434. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  11435. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  11436. return
  11437. }
  11438. this.isABSheet = false
  11439. this.startABLoop()
  11440. },
  11441. })
  11442. }
  11443. //开始AB循环
  11444. startABLoop(){
  11445. if(this.mIjkMediaPlayer){
  11446. this.seekTo(this.jumpATime+'')
  11447. this.isOpenAB = true
  11448. }
  11449. }
  11450. /**
  11451. * 切换横竖屏
  11452. *
  11453. */
  11454. setOrientation(orientation: number) {
  11455. this.windowClass.setPreferredOrientation(orientation).then(() => {
  11456. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  11457. }).catch((err: BusinessError) => {
  11458. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  11459. });
  11460. }
  11461. /**
  11462. * 画中画功能(悬浮歌词功能)
  11463. *
  11464. */
  11465. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  11466. pipController?: PiPWindow.PiPController;
  11467. navigationId: string = '';
  11468. @State curState: string = '';
  11469. @State curError: ResourceStr = '';
  11470. @State pipBg: string = '#E8E8E8'
  11471. @State buttonAction: string = '';
  11472. //开启画中画功能
  11473. async startPip() {
  11474. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  11475. if (!this.pipController) {
  11476. await this.createPipController();
  11477. }
  11478. if (!this.pipController) {
  11479. Logger.info(`[${TAG}] pipController create error`);
  11480. return;
  11481. }
  11482. await this.pipController.startPiP();
  11483. }
  11484. async stopPip() {
  11485. if (!this.pipController) {
  11486. Logger.info(`[${TAG}] pipController is not exist`);
  11487. return;
  11488. }
  11489. this.isOpenPip = false
  11490. await this.pipController.stopPiP();
  11491. }
  11492. async createPipController() {
  11493. this.pipController = await PiPWindow.create({
  11494. context: getContext(this),
  11495. componentController: this.xcomponentController,
  11496. navigationId: this.navigationId,
  11497. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  11498. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  11499. customUIController: this.nodeController,
  11500. });
  11501. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  11502. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  11503. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  11504. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  11505. this.onStateChange(state, reason);
  11506. });
  11507. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  11508. this.onActionEvent(event, status);
  11509. });
  11510. }
  11511. destroyPipController() {
  11512. if (!this.pipController) {
  11513. return;
  11514. }
  11515. this.pipController.off('stateChange');
  11516. this.pipController.off('controlPanelActionEvent');
  11517. this.pipController = undefined;
  11518. }
  11519. onStateChange(state: PiPWindow.PiPState, reason: string) {
  11520. switch (state) {
  11521. case PiPWindow.PiPState.ABOUT_TO_START:
  11522. this.curState = 'ABOUT_TO_START';
  11523. this.curError = $r('app.string.current_error_hint');
  11524. break;
  11525. case PiPWindow.PiPState.STARTED:
  11526. this.curState = 'STARTED';
  11527. this.curError = $r('app.string.current_error_hint');
  11528. break;
  11529. case PiPWindow.PiPState.ABOUT_TO_STOP:
  11530. this.curState = 'ABOUT_TO_STOP';
  11531. this.curError = $r('app.string.current_error_hint');
  11532. break;
  11533. case PiPWindow.PiPState.STOPPED:
  11534. this.curState = 'STOPPED';
  11535. this.curError = $r('app.string.current_error_hint');
  11536. this.stopPip()
  11537. this.destroyPipController()
  11538. break;
  11539. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  11540. this.curState = 'ABOUT_TO_RESTORE';
  11541. this.curError = $r('app.string.current_error_hint');
  11542. break;
  11543. case PiPWindow.PiPState.ERROR:
  11544. this.curState = 'ERROR';
  11545. this.curError = reason;
  11546. break;
  11547. default:
  11548. break;
  11549. }
  11550. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  11551. }
  11552. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  11553. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  11554. switch (event) {
  11555. case 'playbackStateChanged':
  11556. if (status === 0) {
  11557. this.pause();
  11558. } else {
  11559. console.info('onecold startPlayOrResumePlay 9869')
  11560. this.startPlayOrResumePlay();
  11561. }
  11562. break;
  11563. case 'nextVideo':
  11564. // 切换到下一个视频
  11565. this.playNext().catch(() => {
  11566. Logger.error('heanup onActionEvent playNext', `播放下一首失败`);
  11567. });
  11568. break;
  11569. case 'previousVideo':
  11570. // 切换到上一个视频
  11571. this.playPrevious().catch(() => {
  11572. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败`);
  11573. });
  11574. break;
  11575. case 'previousVideo':
  11576. // 切换到上一个视频
  11577. this.playPrevious().catch(() => {
  11578. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败:`);
  11579. });
  11580. break;
  11581. default:
  11582. }
  11583. this.buttonAction = event + `-status:${status}`;
  11584. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  11585. }
  11586. /**
  11587. * 画中画功能(悬浮歌词功能)结束
  11588. *
  11589. */
  11590. async doSearchCover(item: VideoItem,title?:string,artist?:string): Promise<string> {
  11591. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  11592. this.isShowMoreView = false;
  11593. this.showTipsDialog();
  11594. return ''; // Return empty string when no API is configured
  11595. }
  11596. if (!item) {
  11597. return ''; // Return empty string if item is undefined
  11598. }
  11599. const titleS = title||item?.name || '';
  11600. const artistS = artist||item?.artist || ''; // Use empty string if artist is missing
  11601. return this.searchCover(item, titleS, artistS); // Await is not needed here as we return the promise directly
  11602. }
  11603. /**
  11604. *api搜索封面
  11605. *item,根据title和artist
  11606. */
  11607. searchCover(item: VideoItem, title: string, artist: string): Promise<string> {
  11608. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  11609. LogUtil.debug("onecold res =" + res);
  11610. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  11611. if (item.filePath == this.currentSong?.filePath) {
  11612. this.cover = res;
  11613. if (this.currentSong) {
  11614. this.currentSong.pixelMapPath = res;
  11615. }
  11616. }
  11617. // Update pixel map path but always return res regardless of success
  11618. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  11619. if (success) {
  11620. this.doUpdateData();
  11621. console.log("onecold 更新音乐封面成功,数据库已同步");
  11622. } else {
  11623. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  11624. }
  11625. // Note: We don't resolve/reject here because we already returned res
  11626. });
  11627. LogUtil.debug("onecold this.cover =" + this.cover);
  11628. }
  11629. return res; // Always return res regardless of updatePixelMapPath result
  11630. });
  11631. }
  11632. @State jumpTopTime: number = 0
  11633. @State jumpEndTime: number = 0
  11634. @State isOpenJump: boolean = false
  11635. @Builder
  11636. JumpTopEndSheet() {
  11637. Scroll() {
  11638. Column() {
  11639. Column() {
  11640. Text('仅对本播放列表有效')
  11641. .fontSize(16)
  11642. .fontColor($r('app.color.text_color'))
  11643. // 跳过头尾
  11644. Column() {
  11645. Row() {
  11646. Text('跳过片头:')
  11647. .fontSize(16)
  11648. .fontColor($r('app.color.text_color'))
  11649. Text(this.jumpTopTime + 's')
  11650. .fontSize(16)
  11651. .fontColor($r('app.color.text_color'))
  11652. }
  11653. .margin({ bottom: 5 })
  11654. Row() {
  11655. Slider({
  11656. value: this.jumpTopTime,
  11657. min: 0,
  11658. max: 120,
  11659. step: 1,
  11660. style: SliderStyle.OutSet
  11661. })
  11662. .blockColor(this.themeColor)
  11663. .trackColor($r('app.color.speed_text_color'))
  11664. .selectedColor(Color.White)
  11665. .trackThickness(8)
  11666. .onChange((value: number) => {
  11667. this.jumpTopTime = value;
  11668. })
  11669. .width('85%')
  11670. }
  11671. .alignItems(VerticalAlign.Top)
  11672. }
  11673. .margin({ top: 10, bottom: 10 })
  11674. // 跳过头尾
  11675. Column() {
  11676. Row() {
  11677. Text('跳过片尾:')
  11678. .fontSize(16)
  11679. .fontColor($r('app.color.text_color'))
  11680. Text(this.jumpEndTime + 's')
  11681. .fontSize(16)
  11682. .fontColor($r('app.color.text_color'))
  11683. }
  11684. .margin({ bottom: 5 })
  11685. Row() {
  11686. Slider({
  11687. value: this.jumpEndTime,
  11688. min: 0,
  11689. max: 120,
  11690. step: 1,
  11691. style: SliderStyle.OutSet
  11692. })
  11693. .blockColor(this.themeColor)
  11694. .trackColor($r('app.color.speed_text_color'))
  11695. .selectedColor(Color.White)
  11696. .trackThickness(8)
  11697. .onChange((value: number) => {
  11698. this.jumpEndTime = value;
  11699. })
  11700. .width('85%')
  11701. }
  11702. .alignItems(VerticalAlign.Top)
  11703. }
  11704. .margin({ top: 10, bottom: 10 })
  11705. Row() {
  11706. Button('保存设置')
  11707. .fontColor(Color.White)
  11708. .layoutWeight(1)
  11709. .height(40)
  11710. .width(80)
  11711. .backgroundColor(this.themeColor)
  11712. .stateEffect(true)
  11713. .margin({ left: 0, bottom: 20 })
  11714. .onClick(async () => {
  11715. if (!Utility.isNoble()) {
  11716. this.isJumpSetting = false
  11717. this.isShowMoreView = false
  11718. this.showVipDialog()
  11719. return
  11720. }
  11721. if (this.currentSong === undefined) {
  11722. return
  11723. }
  11724. if (this.modeType === 0) {
  11725. let parentPath = FileUtil.getParentPath(this.videoUrl)
  11726. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  11727. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  11728. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  11729. } else if (this.modeType === 1) { //媒体库
  11730. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  11731. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  11732. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  11733. } else if (this.modeType === 2) { //艺术家
  11734. if (this.currentSong?.artist) {
  11735. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  11736. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  11737. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  11738. }
  11739. } else if (this.modeType === 3) { //专辑
  11740. if (this.currentSong?.album) {
  11741. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  11742. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  11743. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  11744. }
  11745. }
  11746. ToastUtil.showShort("保存成功")
  11747. this.isJumpSetting = false
  11748. })
  11749. }
  11750. .margin({
  11751. left: 38,
  11752. right: 38,
  11753. top: 10,
  11754. bottom: 10
  11755. })
  11756. .width(120)
  11757. .height(50)
  11758. }
  11759. }
  11760. }
  11761. .width('100%')
  11762. .height('100%')
  11763. }
  11764. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  11765. private onStateVastChange(state: AVCastPickerState) {
  11766. if (state == AVCastPickerState.STATE_APPEARING) {
  11767. console.log('The picker starts showing.');
  11768. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  11769. console.log('The picker finishes presenting.');
  11770. }
  11771. }
  11772. private showSelectLyric() {
  11773. DialogHelper.showActionSheetDialog({
  11774. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  11775. // sheets: ["本地歌词", "搜索歌词"],
  11776. sheets: [
  11777. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  11778. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  11779. ],
  11780. maskColor: Color.Transparent,
  11781. backgroundColor: $r('app.color.bg_card'),
  11782. transition: AnimationHelper.transitionInDown(666),
  11783. onAction: (index) => {
  11784. switch (index) {
  11785. case 0:
  11786. this.callFilePickerSelectFileForLyric()
  11787. break;
  11788. case 1:
  11789. if (StrUtil.isNotEmpty(this.videoUrl)) {
  11790. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  11791. this.initLyric(lyricPath);
  11792. }
  11793. break;
  11794. }
  11795. }
  11796. })
  11797. }
  11798. // 拉起picker选择文件管理器
  11799. async callFilePickerSelectFileForLyric(): Promise<void> {
  11800. try {
  11801. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  11802. DocumentSelectOptions.maxSelectNumber = 1
  11803. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  11804. let documentPicker = new picker.DocumentViewPicker();
  11805. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  11806. Logger.info(TAG,
  11807. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  11808. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  11809. this.saveVideoDatasLyric(DocumentSelectResult)
  11810. }
  11811. }).catch((err: BusinessError) => {
  11812. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  11813. });
  11814. } catch (err) {
  11815. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  11816. }
  11817. }
  11818. async saveVideoDatasLyric(uris: string[]) {
  11819. if (ArrayUtil.isEmpty(uris)) {
  11820. return
  11821. }
  11822. let newUris: string[] = [];
  11823. for (let i = 0; i < uris.length; i++) {
  11824. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  11825. Logger.info(TAG, 'filePath uri: ' + filePath);
  11826. newUris.push(filePath)
  11827. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  11828. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  11829. fileIo.copyFileSync(file.fd, file2.fd)
  11830. fileIo.closeSync(file);
  11831. fileIo.closeSync(file2);
  11832. this.initLyric(filePath,false,false,true)
  11833. }
  11834. }
  11835. private initDelayPlay(context: object) {
  11836. this.mContext = context;
  11837. }
  11838. startPipLyric() {
  11839. if (this.pipController) {
  11840. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  11841. PiPWindow.PiPControlStatus.PLAY);
  11842. }
  11843. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  11844. if (this.isOpenPip) {
  11845. this.startPip()
  11846. } else {
  11847. this.stopPip()
  11848. }
  11849. }
  11850. //startOffset 从cue分轨时间开始播
  11851. private startPlayOrResumePlay(startOffset?:number) {
  11852. //针对dsf文件高采样率,统一转wav播放
  11853. const sampleRate = this.currentSong?.sampleRate||0
  11854. if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  11855. console.info('onecold 采样率 ='+sampleRate)
  11856. let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  11857. console.info('onecold newDsfPath ='+newDsfPath)
  11858. if(!FileUtil.accessSync(newDsfPath)){
  11859. const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  11860. taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  11861. this.videoUrl = newDsfPath
  11862. this.startPlay(startOffset)
  11863. }).catch((e:object)=>{
  11864. console.info("task1 catch e: " + e);
  11865. })
  11866. }else{
  11867. this.videoUrl = newDsfPath
  11868. this.startPlay(startOffset)
  11869. }
  11870. }else{
  11871. this.startPlay(startOffset)
  11872. }
  11873. }
  11874. startPlay(startOffset?:number) {
  11875. this.startPipLyric()
  11876. this.mDestroyPage = false;
  11877. this.animationState = AnimationStatus.Running
  11878. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  11879. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  11880. this.stopProgressTask();
  11881. this.startProgressTask();
  11882. this.play(this.videoUrl.toString(),startOffset);
  11883. }
  11884. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  11885. this.mIjkMediaPlayer.start();
  11886. this.setProgress()
  11887. this.CONTROL_PlayStatus = PlayStatus.PLAY
  11888. }
  11889. this.setIsPlaying(true)
  11890. this.updateSessionPlayState(true)
  11891. this.watchStatus();
  11892. this.updateLastPlayTimeStr(this.videoUrl)
  11893. }
  11894. updateLastPlayTimeStr(filePath: string) {
  11895. // 检查是否为网络音频(WebDAV),如果是则不更新本地数据库
  11896. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  11897. Logger.info(`heanup 检测到网络音频播放,跳过数据库更新: ${filePath}`)
  11898. return;
  11899. }
  11900. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  11901. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  11902. if (success) {
  11903. this.getHistoryList(false)
  11904. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  11905. } else {
  11906. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  11907. }
  11908. });
  11909. }
  11910. private completionNum(num: number): string | number {
  11911. if (num < 10) {
  11912. return '0' + num;
  11913. } else {
  11914. return num;
  11915. }
  11916. }
  11917. private stringForTime(timeMs: number): string {
  11918. let totalSeconds: number | string = (timeMs / 1000);
  11919. let newSeconds: number | string = totalSeconds % 60;
  11920. let minutes: number | string = (totalSeconds / 60) % 60;
  11921. let hours: number | string = totalSeconds / 3600;
  11922. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  11923. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  11924. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  11925. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  11926. if (this.isCurrentTime) {
  11927. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  11928. this.oldSeconds = newSeconds
  11929. } else {
  11930. newSeconds = this.oldSeconds
  11931. }
  11932. }
  11933. newSeconds = this.completionNum(newSeconds);
  11934. if (hours > 0) {
  11935. return hours + ":" + minutes + ":" + newSeconds;
  11936. } else {
  11937. return minutes + ":" + newSeconds;
  11938. }
  11939. }
  11940. private setProgress() {
  11941. let position = this.mIjkMediaPlayer.getCurrentPosition();
  11942. let duration = this.mIjkMediaPlayer.getDuration();
  11943. let pos = 0;
  11944. if (duration > 0) {
  11945. this.slideEnable = true;
  11946. let curPercent = position / duration;
  11947. pos = curPercent * 100;
  11948. if (pos > this.PROGRESS_MAX_VALUE) {
  11949. this.progressValue = this.PROGRESS_MAX_VALUE
  11950. } else {
  11951. this.progressValue = pos;
  11952. }
  11953. }
  11954. // LogUtils.getInstance()
  11955. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  11956. this.totalTime = this.stringForTime(duration);
  11957. if (position > duration) {
  11958. position = duration;
  11959. }
  11960. this.isCurrentTime = true;
  11961. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  11962. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  11963. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  11964. this.currentTime = this.stringForTime(position);
  11965. this.isCurrentTime = false
  11966. if (this.mIjkMediaPlayer.isPlaying()) {
  11967. this.randomColor =
  11968. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  11969. //如果是开启AB循环
  11970. if(this.isOpenAB){
  11971. if(position >=this.jumpBTime){
  11972. this.seekTo(this.jumpATime+'')
  11973. return
  11974. }
  11975. }
  11976. // 判断是否播放到结束时间
  11977. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  11978. if (position >= duration - this.jumpEndTime * 1000) {
  11979. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  11980. this.CONTROL_PlayStatus = PlayStatus.INIT
  11981. this.startPlayOrResumePlay();
  11982. }else if (this.playType == 2) { //2:正常播放,单曲播完
  11983. this.showRePlay();
  11984. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  11985. this.progressValue = this.PROGRESS_MAX_VALUE;
  11986. this.slideEnable = false;
  11987. this.stop();
  11988. // ToastUtil.showToast('开始重新播放')
  11989. }else{
  11990. this.playNext().catch(() => {
  11991. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  11992. });
  11993. }
  11994. }
  11995. }
  11996. } else {
  11997. this.randomColor = 'rbg(0,0,0)'
  11998. }
  11999. }
  12000. private startProgressTask() {
  12001. let that = this;
  12002. this.updateProgressTimer = setInterval(() => {
  12003. //LogUtils.getInstance().LOGI("startProgressTask");
  12004. if (!that.mDestroyPage) {
  12005. that.setProgress();
  12006. }
  12007. }, 300);
  12008. }
  12009. private stopProgressTask() {
  12010. LogUtils.getInstance().LOGI("stopProgressTask");
  12011. clearInterval(this.updateProgressTimer);
  12012. }
  12013. private showLoadIng() {
  12014. this.loadingVisible = Visibility.Visible;
  12015. this.replayVisible = Visibility.None;
  12016. }
  12017. private hideLoadIng() {
  12018. this.loadingVisible = Visibility.None;
  12019. this.replayVisible = Visibility.None;
  12020. }
  12021. private showRePlay() {
  12022. this.loadingVisible = Visibility.None;
  12023. this.replayVisible = Visibility.Visible;
  12024. }
  12025. private async play(url: string,startOffset?:number) {
  12026. this.isShowBgLiuGUANG = PreferencesUtil.getBooleanSync('isShowBgLiuGUANG', true)
  12027. console.info('onecold this.url 1= '+url)
  12028. if(!url.toLowerCase().startsWith('http')){
  12029. let hasPermission = await PermissionUtil.activatePermission(url)
  12030. console.info('onecold this.hasPermission 1= '+hasPermission)
  12031. if(!url.includes(this.packName)){
  12032. const file = fs.openSync(url)
  12033. this.videoUrl = file.path
  12034. url= this.videoUrl
  12035. }
  12036. console.info('onecold this.hasPermission 1= '+hasPermission)
  12037. console.info('onecold this.videoUrl 1= '+this.videoUrl)
  12038. }
  12039. let that = this;
  12040. that.showLoadIng();
  12041. this.isOpenAB = false
  12042. //设置XComponent回调的context
  12043. if (!!this.mContext) {
  12044. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  12045. }
  12046. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  12047. this.mIjkMediaPlayer.reset();
  12048. }
  12049. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  12050. //设置debug模式
  12051. this.mIjkMediaPlayer.setDebug(false);
  12052. //初始化配置
  12053. this.mIjkMediaPlayer.native_setup();
  12054. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  12055. if(this.volumeSmall){
  12056. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  12057. this.mIjkMediaPlayer.setVolume('1', '1');
  12058. }else{
  12059. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  12060. }
  12061. }else{
  12062. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  12063. }
  12064. //设置视频源
  12065. this.mIjkMediaPlayer.setDataSource(url);
  12066. // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
  12067. const headers = new Map<string, string>();
  12068. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  12069. headers.set("Accept", "*/*");
  12070. if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
  12071. &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
  12072. //如果封面为空,则搜索封面
  12073. this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
  12074. }
  12075. // 如果是WebDAV网络音频,使用webdav_account_id获取认证信息(等待完成后再设置一次性头部)
  12076. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  12077. Logger.info(`heanup WebDAV歌曲认证 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
  12078. if (this.currentSong.webdav_account_id) {
  12079. try {
  12080. const webdavManager = RemoteDriveManager.getInstance();
  12081. const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  12082. if (webDavHeaders && webDavHeaders.size > 0) {
  12083. webDavHeaders.forEach((value, key) => headers.set(key, value));
  12084. Logger.info(`heanup 成功通过webdav_account_id获取并合并WebDAV认证头`);
  12085. } else {
  12086. Logger.warn(`heanup 通过webdav_account_id获取认证头失败,播放可能无法继续`);
  12087. }
  12088. } catch (error) {
  12089. const err = error as Error;
  12090. Logger.error(`heanup 获取WebDAV认证头时出错: ${err.message}`);
  12091. }
  12092. } else {
  12093. Logger.error(`heanup WebDAV歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法进行认证`);
  12094. }
  12095. }
  12096. // 统一设置带认证的请求头
  12097. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  12098. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  12099. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  12100. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  12101. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  12102. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  12103. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  12104. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  12105. // 缓冲和播放优化设置
  12106. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  12107. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  12108. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1"); // 预加载启动
  12109. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  12110. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  12111. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  12112. // 网络相关设置
  12113. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  12114. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  12115. // 重连设置
  12116. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  12117. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  12118. }
  12119. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  12120. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  12121. // }
  12122. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  12123. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  12124. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  12125. const fileSize = await this.getFileSize(this.videoUrl);
  12126. let bufferSize = 1 * 1024 ; // 默认缓冲区大小为1MB
  12127. if (fileSize > 3 * 1024 * 1024 * 1024) { // 文件大于3GB
  12128. bufferSize = 25 * 1024 * 1024; // 设置缓冲区大小为25MB
  12129. }
  12130. // 使用软件解码(通常比硬件解码更节省内存)
  12131. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", '0');
  12132. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", '0');
  12133. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", '1024');
  12134. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzeduration", '500000');
  12135. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  12136. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  12137. //停止预读的最小帧数
  12138. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  12139. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  12140. // 设置其他缓冲相关选项
  12141. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  12142. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  12143. //启动预加载
  12144. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  12145. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  12146. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  12147. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  12148. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  12149. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  12150. // 因此需要播放器丢包,才不会累积延时
  12151. // 这个和第三个参数packet-buffering无关。
  12152. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  12153. // 无限制收流
  12154. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  12155. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  12156. // 屏幕常亮
  12157. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  12158. // 设置超时
  12159. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  12160. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  12161. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  12162. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  12163. // 变速播放
  12164. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  12165. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  12166. let Speed = this.mIjkMediaPlayer.getSpeed()
  12167. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  12168. //是否开启循环播放
  12169. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  12170. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  12171. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  12172. if (height === 0) {
  12173. return;
  12174. }
  12175. const va = width / height;
  12176. const vpa = that.videoParentAspectRatio;
  12177. if (vpa > va) {
  12178. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  12179. } else {
  12180. that.videoWidth = '100%';
  12181. }
  12182. if (width && height) {
  12183. that.videoAspectRatio = width / height;
  12184. }
  12185. LogUtils.getInstance()
  12186. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  12187. that.hideLoadIng();
  12188. }
  12189. }
  12190. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  12191. let mOnPreparedListener: OnPreparedListener = {
  12192. onPrepared: async () => {
  12193. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  12194. try {
  12195. //保存碰一碰分享的当前的歌曲
  12196. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  12197. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  12198. await this.initLyric(lyricPath);
  12199. setTimeout(() => {
  12200. this.avSessionController.initAvSession(false);
  12201. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  12202. this.setAvSessionListener();
  12203. this.updateSessionPlayState(true)
  12204. this.setCurrentPlayMode()
  12205. }, 500)
  12206. if(startOffset&&startOffset>0){//cue分轨播放
  12207. this.seekTo(startOffset + "");
  12208. this.saveLastPlayList()
  12209. return
  12210. }
  12211. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12212. let timeoutPlay = 0
  12213. if (StrUtil.isNotEmpty(this.videoUrl) &&
  12214. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  12215. timeoutPlay = 1000
  12216. }
  12217. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  12218. if (this.modeType === 0) { //文件夹
  12219. let parentPath = FileUtil.getParentPath(this.videoUrl)
  12220. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  12221. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  12222. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  12223. } else if (this.modeType === 1) { //媒体库
  12224. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  12225. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  12226. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  12227. } else if (this.modeType === 2) { //艺术家
  12228. if (this.currentSong?.artist) {
  12229. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  12230. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  12231. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  12232. }
  12233. } else if (this.modeType === 3) { //专辑
  12234. if (this.currentSong?.album) {
  12235. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  12236. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  12237. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  12238. }
  12239. }
  12240. this.duration = this.mIjkMediaPlayer.getDuration()
  12241. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  12242. if (this.mIjkMediaPlayer != null) {
  12243. let jumpTopTimeMs = this.jumpTopTime*1000;
  12244. if (jumpTopTimeMs <= this.duration) {
  12245. // 调用 seekTo 方法,跳到指定时间
  12246. if(PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY,true)){
  12247. console.log('onecold jumpTopTime = '+jumpTopTimeMs);
  12248. const position:number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  12249. console.log('onecold position = '+position);
  12250. if (position > jumpTopTimeMs) {
  12251. jumpTopTimeMs = position
  12252. }
  12253. }
  12254. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12255. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  12256. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  12257. }
  12258. }, timeoutPlay)
  12259. } else {
  12260. // 提示用户无法跳过
  12261. ToastUtil.showToast('跳过时间超过视频时长');
  12262. }
  12263. }
  12264. } else {
  12265. this.jumpTopTime = 0
  12266. this.jumpEndTime = 0
  12267. // console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  12268. // console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  12269. // console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  12270. // PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  12271. //记忆播放(每一首都会记忆播放)
  12272. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  12273. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12274. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  12275. this.restorePlaybackPosition() //读取播放记忆功能
  12276. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  12277. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  12278. this.restorePlaybackPosition() //读取播放记忆功能
  12279. }
  12280. this.isFirstStartPlay = false
  12281. }, timeoutPlay)
  12282. } else {
  12283. this.isFirstStartPlay = false
  12284. }
  12285. }
  12286. this.saveLastPlayList()
  12287. } catch (error) {
  12288. let err: BusinessError = error as BusinessError;
  12289. console.error('onecold failed with err: ' + JSON.stringify(err));
  12290. }
  12291. }
  12292. }
  12293. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  12294. let mOnTimedTextListener: OnTimedTextListener = {
  12295. onTimedText: () => {
  12296. }
  12297. }
  12298. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  12299. let mOnCompletionListener: OnCompletionListener = {
  12300. onCompletion: () => {
  12301. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  12302. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  12303. // 异步调用playNext
  12304. this.playNext().catch(() => {
  12305. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  12306. });
  12307. } else if (this.playType == 1) { //1:单片重复播放
  12308. this.CONTROL_PlayStatus = PlayStatus.INIT
  12309. that.startPlayOrResumePlay();
  12310. } else if (this.playType == 2) { //2:正常播放,单曲播完
  12311. that.showRePlay();
  12312. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  12313. that.progressValue = this.PROGRESS_MAX_VALUE;
  12314. that.slideEnable = false;
  12315. that.stop();
  12316. // ToastUtil.showToast('开始重新播放')
  12317. } else if (this.playType == 3) { //3:随机播放
  12318. // 异步调用randomPlay
  12319. this.randomPlay().catch(() => {
  12320. Logger.error('heanup OnCompletionListener randomPlay', `随机播放失败`);
  12321. });
  12322. }
  12323. }
  12324. }
  12325. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  12326. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  12327. onBufferingUpdate: (percent: number) => {
  12328. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  12329. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  12330. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  12331. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  12332. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  12333. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  12334. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  12335. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  12336. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  12337. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  12338. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  12339. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  12340. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  12341. let Looping = this.mIjkMediaPlayer.isLooping()
  12342. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  12343. }
  12344. }
  12345. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  12346. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  12347. onSeekComplete: () => {
  12348. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  12349. console.info('onecold startPlayOrResumePlay 10643')
  12350. that.startPlayOrResumePlay();
  12351. }
  12352. }
  12353. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  12354. let mOnInfoListener: OnInfoListener = {
  12355. onInfo: (what: number, extra: number) => {
  12356. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  12357. that.hideLoadIng();
  12358. }
  12359. }
  12360. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  12361. let mOnErrorListener: OnErrorListener = {
  12362. onError: (what: number, extra: number) => {
  12363. this.stopProgressTask();
  12364. LogUtils.getInstance().LOGI("heanup OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  12365. LogUtils.getInstance().LOGI('heanup 播放错误,歌曲详情:' + JSON.stringify(this.currentSong))
  12366. // 检查是否为WebDAV播放错误
  12367. let isWebDavError = false;
  12368. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.currentSong.filePath) {
  12369. try {
  12370. const globalContext = GlobalContext.getContext();
  12371. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  12372. if (webDavAuthInfo) {
  12373. isWebDavError = true;
  12374. }
  12375. } catch (error) {
  12376. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  12377. }
  12378. }
  12379. if (isWebDavError) {
  12380. Logger.error(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  12381. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  12382. // this.currentWebDavAuthInfo = null;
  12383. Logger.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  12384. // 根据错误代码提供更具体的错误信息
  12385. let errorMessage = "WebDAV播放失败";
  12386. if (what === -1) { // 网络错误
  12387. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  12388. } else if (what === -1004) { // HTTP 404
  12389. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  12390. } else if (what === -1001) { // 超时
  12391. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  12392. } else if (what === -1003) { // 无法解析主机
  12393. errorMessage = "无法连接到WebDAV服务器";
  12394. }
  12395. ToastUtil.showToast(errorMessage);
  12396. } else {
  12397. if (StrUtil.isNotEmpty(this.videoUrl) &&
  12398. !this.videoUrl.startsWith('http://') &&
  12399. !this.videoUrl.startsWith('https://') &&
  12400. !FileUtil.accessSync(this.videoUrl)) {
  12401. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  12402. }
  12403. }
  12404. that.hideLoadIng();
  12405. }
  12406. }
  12407. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  12408. this.mIjkMediaPlayer.setMessageListener();
  12409. this.mIjkMediaPlayer.prepareAsync();
  12410. this.mIjkMediaPlayer.start();
  12411. }
  12412. //保存最后播放的那首歌和已经对应的播放列表
  12413. saveLastPlayList() {
  12414. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  12415. PreferencesUtil.putSync('LastMusicList', this.songList)
  12416. }
  12417. // 清空播放记录
  12418. clearVideoHistory() {
  12419. this.table.clearPlayHistory((success: boolean, error?: string) => {
  12420. if (success) {
  12421. this.historyList = [];
  12422. this.updateListData(this.historyList)
  12423. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  12424. ToastUtil.showToast('清空播放记录成功')
  12425. } else {
  12426. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  12427. }
  12428. });
  12429. }
  12430. public async setAvSessionListener() {
  12431. if (!this.avSessionController) {
  12432. return;
  12433. }
  12434. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  12435. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  12436. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  12437. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  12438. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  12439. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  12440. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  12441. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  12442. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  12443. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  12444. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  12445. }
  12446. setLoopMode() {
  12447. let itype = this.playType + 1
  12448. if (itype >= 4) {
  12449. this.playType = 0
  12450. ToastUtil.showToast('连续播放')
  12451. } else if (itype === 1) {
  12452. this.playType = 1
  12453. ToastUtil.showToast('单曲循环')
  12454. } else if (itype === 2) {
  12455. this.playType = 2
  12456. ToastUtil.showToast('单曲播完')
  12457. } else if (itype === 3) {
  12458. this.playType = 3
  12459. ToastUtil.showToast('随机播放')
  12460. } else if (itype === 0) {
  12461. this.playType = 0
  12462. ToastUtil.showToast('连续播放')
  12463. }
  12464. PreferencesUtil.putSync('musicPlayType', this.playType)
  12465. this.setCurrentPlayMode()
  12466. }
  12467. private sessionSetLoopModeCallback = (mode: number) => {
  12468. if (this.mIjkMediaPlayer != null) {
  12469. ToastUtil.showToast('当前播放模式:' + mode)
  12470. Logger.info('onecold 当前播放模式= ' + mode)
  12471. let hmPlayMode = mode + 1
  12472. if (hmPlayMode >= 4) {
  12473. hmPlayMode = 0
  12474. }
  12475. if (hmPlayMode === 1) {
  12476. this.playType = 1
  12477. ToastUtil.showToast('单曲循环')
  12478. } else if (hmPlayMode === 0) {
  12479. this.playType = 2
  12480. ToastUtil.showToast('单曲播完')
  12481. } else if (hmPlayMode === 3) {
  12482. this.playType = 3
  12483. ToastUtil.showToast('随机播放')
  12484. } else if (hmPlayMode === 2) {
  12485. this.playType = 0
  12486. ToastUtil.showToast('连续播放')
  12487. }
  12488. PreferencesUtil.putSync('musicPlayType', this.playType)
  12489. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  12490. let playBackState: avSession.AVPlaybackState = {
  12491. loopMode: hmPlayMode,
  12492. };
  12493. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  12494. console.info(`set setLoopMode AVPlaybackState successfully`);
  12495. }).catch((err: BusinessError) => {
  12496. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  12497. });
  12498. }
  12499. }
  12500. setCurrentPlayMode() {
  12501. if (!this.avSessionController) {
  12502. return;
  12503. }
  12504. let mLoopMode = 0
  12505. switch (this.playType) {
  12506. case 0:
  12507. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  12508. break;
  12509. case 1:
  12510. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  12511. break;
  12512. case 2:
  12513. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  12514. break;
  12515. case 3:
  12516. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  12517. break;
  12518. }
  12519. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  12520. let playBState: avSession.AVPlaybackState = {
  12521. loopMode: mLoopMode,
  12522. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  12523. };
  12524. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  12525. console.info(`set setLoopMode AVPlaybackState successfully`);
  12526. }).catch((err: BusinessError) => {
  12527. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  12528. });
  12529. }
  12530. private sessionToggleFavoriteCallback = (assetId: string) => {
  12531. if (this.mIjkMediaPlayer != null && this.currentSong) {
  12532. console.info(`on toggleFavorite `);
  12533. // 应用收到收藏命令,进行收藏处理。
  12534. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  12535. this.doFav(this.currentSong)
  12536. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  12537. let playbackState: avSession.AVPlaybackState = {
  12538. isFavorite: !this.isFac,
  12539. };
  12540. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  12541. console.info(`SetAVPlaybackState successfully`);
  12542. }).catch((err: BusinessError) => {
  12543. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  12544. });
  12545. }
  12546. }
  12547. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  12548. device: avSession.OutputDeviceInfo) => {
  12549. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  12550. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  12551. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  12552. await this.startCasting();
  12553. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  12554. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  12555. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  12556. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  12557. if (device) {
  12558. this.endCasting();
  12559. }
  12560. }
  12561. };
  12562. private async startCasting() {
  12563. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  12564. this.setPlaybackStateChangeListener();
  12565. this.pause();
  12566. this.initQueueItem();
  12567. this.prepare();
  12568. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  12569. refToIsCasting?.set(true);
  12570. this.castSeek = true;
  12571. this.isCastPlaying = true;
  12572. }
  12573. async changeCasting() {
  12574. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  12575. this.initQueueItem();
  12576. this.prepare();
  12577. this.setPlaybackStateChangeListener();
  12578. this.isCastPlaying = true;
  12579. this.castSeek = true;
  12580. }
  12581. public endCasting() {
  12582. this.avSessionController.getAvSession()?.stopCasting();
  12583. this.stopCast();
  12584. this.isCastPlaying = false;
  12585. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  12586. refToIsCasting?.set(false);
  12587. this.pause();
  12588. this.setIsPlaying(false);
  12589. // if (this.curIndex === this.curSource.index) {
  12590. // this.play
  12591. // this.seek(this.currentTime * 1000);
  12592. // this.setIsPlaying(true);
  12593. // } else {
  12594. // this.pauseVideo();
  12595. // this.setIsPlaying(false);
  12596. // }
  12597. }
  12598. public setIsPlaying(isPlayer: boolean) {
  12599. this.isPlaying = isPlayer;
  12600. // 发送播放状态变化事件给歌单详情页面
  12601. try {
  12602. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  12603. const currentFilePath = this.currentSong?.filePath || ''
  12604. const eventData: emitter.EventData = {
  12605. data: {
  12606. isPlaying: this.isPlaying,
  12607. curIndex: this.curIndex,
  12608. currentFilePath: currentFilePath
  12609. }
  12610. };
  12611. emitter.emit(eventPlaybackStatus, eventData)
  12612. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  12613. } catch (error) {
  12614. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  12615. }
  12616. }
  12617. private setPlaybackStateChangeListener(): void {
  12618. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  12619. this.castController?.on('endOfStream', this.reloadCasting);
  12620. this.castController?.on('playNext', this.playNextCallback);
  12621. this.castController?.on('playPrevious', this.playPreviousCallback);
  12622. }
  12623. private updateSessionPlayState(isPlay: boolean): void {
  12624. // if(!this.isBgPlayOpen)
  12625. // return
  12626. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  12627. this.setAVSessionPlayState({
  12628. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  12629. position: {
  12630. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  12631. updateTime: new Date().getTime()
  12632. }
  12633. });
  12634. }
  12635. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  12636. this.avSessionController.setAvSessionPlayState(playbackState)
  12637. }
  12638. private positionChange(position: number) {
  12639. this.currentTime2 = position / 1000;
  12640. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  12641. }
  12642. private playDurationChange(duration: number) {
  12643. this.duration = duration;
  12644. this.durationTime = Math.floor(this.duration / 1000);
  12645. this.durationStringTime = secondToTime((this.durationTime));
  12646. }
  12647. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  12648. const duration = playbackState?.extras?.duration;
  12649. if (typeof duration === 'number') {
  12650. this.playDurationChange(duration as number);
  12651. }
  12652. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  12653. this.positionChange(playbackState?.position?.elapsedTime);
  12654. }
  12655. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  12656. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  12657. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  12658. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  12659. this.isCastPlaying = false;
  12660. }
  12661. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  12662. this.isCastPlaying = true;
  12663. }
  12664. };
  12665. private reloadCasting = async () => {
  12666. let item = this.songList[this.curIndex];
  12667. let uri = fileUri.getUriFromPath(item.filePath);
  12668. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  12669. // description.startPosition = 0;
  12670. this.castItem = {
  12671. itemId: this.curIndex,
  12672. description: {
  12673. assetId: item.filePath,
  12674. title: item.name,
  12675. artist: '',
  12676. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  12677. // mediaUri: item.filePath,
  12678. fdSrc: {
  12679. fd: file.fd
  12680. },
  12681. // 该字段大写,音频'AUDIO',视频'VIDEO'
  12682. mediaType: 'VIDEO',
  12683. mediaSize: item.videoSize,
  12684. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  12685. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  12686. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  12687. duration: this.duration,
  12688. // albumCoverUri: 'https://www.example.jpeg',
  12689. // albumTitle: '《ExampleAlbum》',
  12690. appName: this.appName,
  12691. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  12692. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  12693. }
  12694. };
  12695. this.prepare();
  12696. this.isCastPlaying = true;
  12697. };
  12698. public playNextCallback = (): void => {
  12699. this.playNext().catch(() => {
  12700. Logger.error('heanup playNextCallback', `播放下一首失败`);
  12701. });
  12702. };
  12703. public playPreviousCallback = (): void => {
  12704. this.playPrevious().catch(() => {
  12705. Logger.error('heanup playNextCallback', `播放上一首失败`);
  12706. });
  12707. };
  12708. async prepare() {
  12709. await this.castController?.prepare(this.castItem);
  12710. await this.castController?.start(this.castItem);
  12711. }
  12712. public initQueueItem() {
  12713. let item = this.songList[this.curIndex];
  12714. let time = this.currentTime;
  12715. let uri = fileUri.getUriFromPath(item.filePath);
  12716. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  12717. this.castItem = {
  12718. itemId: this.curIndex,
  12719. description: {
  12720. assetId: item.filePath,
  12721. title: item.name,
  12722. artist: '',
  12723. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  12724. fdSrc: {
  12725. fd: file.fd
  12726. },
  12727. // 该字段大写,音频'AUDIO',视频'VIDEO'
  12728. mediaType: 'AUDIO',
  12729. mediaSize: item.videoSize,
  12730. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  12731. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  12732. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  12733. duration: this.duration,
  12734. // albumCoverUri: 'https://www.example.jpeg',
  12735. // albumTitle: '《ExampleAlbum》',
  12736. appName: this.appName,
  12737. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  12738. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  12739. }
  12740. };
  12741. }
  12742. async stopCast() {
  12743. try {
  12744. this.castController?.off('playbackStateChange');
  12745. this.castController?.off('endOfStream');
  12746. this.castController?.off('playNext');
  12747. this.castController?.off('playPrevious');
  12748. this.castController?.off('error');
  12749. } catch (error) {
  12750. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  12751. }
  12752. }
  12753. private sessionPlayCallback = (): void => {
  12754. this.playOrPause()
  12755. };
  12756. private sessionPauseCallback = (): void => {
  12757. this.pause()
  12758. };
  12759. private playOrPause() {
  12760. if (!this.debounce()) {
  12761. return;
  12762. }
  12763. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  12764. this.pause();
  12765. } else {
  12766. console.info('onecold startPlayOrResumePlay 11064')
  12767. this.startPlayOrResumePlay();
  12768. this.playChange()
  12769. }
  12770. }
  12771. private sessionPlayNextCallback = (): void => {
  12772. this.playNext().catch(() => {
  12773. Logger.error('heanup sessionPlayPreviousCallback', `播放下 一首失败`);
  12774. });
  12775. };
  12776. private sessionPlayPreviousCallback = (): void => {
  12777. this.playPrevious().catch(() => {
  12778. Logger.error('heanup sessionPlayPreviousCallback', `播放上一首失败`);
  12779. });
  12780. };
  12781. private sessionStopCallback = (): void => {
  12782. this.stop()
  12783. };
  12784. private sessionFastForwardCallback = (time?: number) => {
  12785. if (!time) {
  12786. return;
  12787. }
  12788. if (this.mIjkMediaPlayer != null) {
  12789. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12790. let seeTime = curPosition + time * 1000;
  12791. // 限制 seekValue 在合法范围内
  12792. if (seeTime < 0) {
  12793. seeTime = 0;
  12794. } else if (seeTime > this.duration) {
  12795. seeTime = this.duration;
  12796. }
  12797. Logger.info('onecold seeTime= ' + seeTime)
  12798. this.setSeekToActionProgress(seeTime)
  12799. this.seekTo(seeTime + "")
  12800. }
  12801. };
  12802. /**
  12803. * Gesture method onActionUpdate.
  12804. *
  12805. * @param event Gesture event.手势拖动设置快进和后退
  12806. */
  12807. private setSeekToActionProgress(position: number) {
  12808. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  12809. let duration = this.mIjkMediaPlayer.getDuration();
  12810. let pos = 0;
  12811. if (duration > 0) {
  12812. this.slideEnable = true;
  12813. let curPercent = position / duration;
  12814. pos = curPercent * 100;
  12815. if (pos > this.PROGRESS_MAX_VALUE) {
  12816. this.progressValue = this.PROGRESS_MAX_VALUE
  12817. } else {
  12818. this.progressValue = pos;
  12819. }
  12820. }
  12821. // LogUtils.getInstance()
  12822. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  12823. this.totalTime = this.stringForTime(duration);
  12824. if (position > duration) {
  12825. position = duration;
  12826. }
  12827. this.isCurrentTime = true;
  12828. this.currentTime = this.stringForTime(position);
  12829. this.isCurrentTime = false
  12830. }
  12831. private sessionRewindCallback = (time?: number) => {
  12832. if (!time) {
  12833. return;
  12834. }
  12835. if (this.mIjkMediaPlayer != null) {
  12836. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12837. let seeTime = curPosition - time * 1000;
  12838. // 限制 seekValue 在合法范围内
  12839. if (seeTime < 0) {
  12840. seeTime = 0;
  12841. } else if (seeTime > this.duration) {
  12842. seeTime = this.duration;
  12843. }
  12844. Logger.info('onecold seeTime= ' + seeTime)
  12845. this.setSeekToActionProgress(seeTime)
  12846. this.seekTo(seeTime + "")
  12847. }
  12848. };
  12849. private sessionSeekCallback = (seekTime: number) => {
  12850. if (this.mIjkMediaPlayer != null) {
  12851. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12852. this.seekTo(seekTime + "")
  12853. }
  12854. };
  12855. private async getFileSize(filePath: string): Promise<number> {
  12856. try {
  12857. const stat = await fs.stat(filePath);
  12858. return stat.size;
  12859. } catch (err) {
  12860. console.error('Failed to get file size: ' + err.message);
  12861. return 0;
  12862. }
  12863. }
  12864. private pause() {
  12865. if (this.mIjkMediaPlayer.isPlaying()) {
  12866. this.savePlaybackPosition();
  12867. this.mIjkMediaPlayer.pause();
  12868. this.setProgress();
  12869. this.mDestroyPage = true;
  12870. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  12871. this.updateSessionPlayState(false)
  12872. this.playChange()
  12873. if (this.pipController) {
  12874. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  12875. PiPWindow.PiPControlStatus.PAUSE);
  12876. }
  12877. }
  12878. }
  12879. private stop() {
  12880. this.savePlaybackPosition();
  12881. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12882. this.mIjkMediaPlayer.stop();
  12883. this.mIjkMediaPlayer.release();
  12884. this.stopProgressTask();
  12885. this.updateSessionPlayState(false)
  12886. this.playChange()
  12887. this.watchStatus();
  12888. }
  12889. //保持记忆播放功能
  12890. private savePlaybackPosition() {
  12891. if (this.mIjkMediaPlayer != null) {
  12892. const position = this.mIjkMediaPlayer.getCurrentPosition();
  12893. // ToastUtil.showToast('保存记忆播放 = ' + position)
  12894. const duration = this.mIjkMediaPlayer.getDuration();
  12895. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  12896. // 如果播放位置接近视频末尾,则保存 position 为 0
  12897. const playbackPosition = (duration - position < threshold) ? 0 : position;
  12898. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  12899. }
  12900. }
  12901. //获取记忆播放功能
  12902. private restorePlaybackPosition() {
  12903. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  12904. // ToastUtil.showToast('position = ' + position)
  12905. if (this.mIjkMediaPlayer != null && position > 0) {
  12906. // ToastUtil.showToast('seekTo = ' + position)
  12907. this.seekTo(position + "");
  12908. }
  12909. }
  12910. private seekTo(value: string) {
  12911. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  12912. ToastUtil.showToast('wma格式不支持拖动快进。')
  12913. return
  12914. }
  12915. this.isSeekTo = true
  12916. this.mIjkMediaPlayer.seekTo(value);
  12917. console.info('onecold startPlayOrResumePlay 11227')
  12918. // this.startPlayOrResumePlay()
  12919. // 在这里恢复计时器状态
  12920. this.setProgress()
  12921. this.isSeekTo = false
  12922. }
  12923. // 添加到下一首播放
  12924. private addToNextPlay(song: VideoItem) {
  12925. if (!this.debounce()) {
  12926. return;
  12927. }
  12928. if (this.currentSong) {
  12929. if (this.currentSong === song) {
  12930. ToastUtil.showToast('当前已经在播放这首歌了!')
  12931. return
  12932. }
  12933. }
  12934. // 如果未开始播放或队列为空
  12935. if (this.curIndex === -1 || this.songList.length === 0) {
  12936. this.songList = [song];
  12937. this.curIndex = 0;
  12938. this.doPlay(song)
  12939. return;
  12940. }
  12941. // 插入到当前索引+1的位置
  12942. const insertPos = this.curIndex + 1;
  12943. this.songList.splice(insertPos, 0, song);
  12944. this.songList = [...this.songList]; // 触发状态更新
  12945. this.sonDataSource.pushArrayData(this.songList)
  12946. ToastUtil.showToast('已添加至下一首播放')
  12947. }
  12948. //后退10s,可再设置设置默认几秒
  12949. backForward() {
  12950. if(this.mIjkMediaPlayer){
  12951. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  12952. let value = pos - Number(this.fastForwardSeconds) * 1000;
  12953. this.seekTo(value+"");
  12954. }
  12955. }
  12956. //快进10s,可再设置设置默认几秒
  12957. fastForward() {
  12958. if(this.mIjkMediaPlayer){
  12959. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  12960. let value = pos + Number(this.fastForwardSeconds) * 1000;
  12961. this.seekTo(value+"");
  12962. }
  12963. }
  12964. //下一个
  12965. private async playNext() {
  12966. if (!this.debounce()) {
  12967. return;
  12968. }
  12969. if (this.playType == 3) { //3:随机播放
  12970. await this.randomPlay()
  12971. return;
  12972. }
  12973. if (ArrayUtil.isNotEmpty(this.songList)) {
  12974. if (this.curIndex == this.songList.length - 1) {
  12975. this.curIndex = 0;
  12976. } else {
  12977. this.curIndex++;
  12978. }
  12979. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12980. this.stop();
  12981. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  12982. this.currentSong = this.songList[this.curIndex];
  12983. Logger.info('heanup playNext', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  12984. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12985. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  12986. context: this.context,
  12987. autoParseMusicName: this.autoParseMusicName
  12988. });
  12989. this.artist = this.songList[this.curIndex].artist
  12990. this.name = this.songList[this.curIndex].name
  12991. //this.cover = this.songList[this.curIndex].pixelMapPath
  12992. this.changeImageAnimation()
  12993. }
  12994. }
  12995. changeImageAnimation() {
  12996. if(this.openSkipSongAnimate){
  12997. // 第一步:淡出动画
  12998. this.getUIContext()?.animateTo({
  12999. duration: 500,
  13000. curve: Curve.EaseOut,
  13001. }, () => {
  13002. this.opacityValueImage = 0.1;
  13003. if(this.isCoverRectangle){
  13004. this.scaleValueImage = 0.88
  13005. }
  13006. });
  13007. // 第二步:切换图片后淡入
  13008. setTimeout(() => {
  13009. this.cover = this.songList[this.curIndex].pixelMapPath
  13010. this.getUIContext()?.animateTo({
  13011. duration: 500,
  13012. curve: Curve.EaseIn,
  13013. }, () => {
  13014. this.opacityValueImage = 1;
  13015. this.scaleValueImage = 1 // 图标恢复到原始大小
  13016. this.startPlayOrResumePlay()
  13017. });
  13018. }, 500);
  13019. }else{
  13020. this.cover = this.songList[this.curIndex].pixelMapPath
  13021. this.startPlayOrResumePlay()
  13022. }
  13023. }
  13024. // 存储已播放的歌曲索引
  13025. private playedIndices: Set<number> = new Set();
  13026. //随机播放
  13027. private async randomPlay() {
  13028. // if (!this.debounce()) {
  13029. // return;
  13030. // }
  13031. if (ArrayUtil.isNotEmpty(this.songList)) {
  13032. if (this.songList.length > 3) {
  13033. // 如果所有歌曲都播放过一次,清空已播放索引集合
  13034. if (this.playedIndices.size === this.songList.length) {
  13035. this.playedIndices.clear();
  13036. }
  13037. // 随机选择一个未播放的歌曲索引
  13038. let newIndex: number;
  13039. // 添加超时机制防止无限循环
  13040. let attempt = 0;
  13041. const maxAttempts = 100; // 根据需求调整
  13042. do {
  13043. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  13044. attempt++;
  13045. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  13046. if (attempt >= maxAttempts) {
  13047. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  13048. newIndex = Math.floor(Math.random() * this.songList.length);
  13049. }
  13050. this.curIndex = newIndex;
  13051. this.playedIndices.add(newIndex);
  13052. } else {
  13053. // 当歌曲数量小于或等于3时,直接播放下一首
  13054. if (this.curIndex == this.songList.length - 1) {
  13055. this.curIndex = 0;
  13056. } else {
  13057. this.curIndex++;
  13058. }
  13059. }
  13060. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13061. this.stop();
  13062. this.currentSong = this.songList[this.curIndex];
  13063. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13064. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13065. context: this.context,
  13066. autoParseMusicName: this.autoParseMusicName
  13067. });
  13068. this.name = this.songList[this.curIndex].name;
  13069. this.artist = this.songList[this.curIndex].artist
  13070. // this.cover = this.songList[this.curIndex].pixelMapPath
  13071. this.changeImageAnimation()
  13072. }
  13073. }
  13074. private async playIndex(index: number) {
  13075. if (!this.debounce()) {
  13076. return;
  13077. }
  13078. if (ArrayUtil.isNotEmpty(this.songList)) {
  13079. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13080. this.stop();
  13081. this.curIndex = index;
  13082. this.currentSong = this.songList[index];
  13083. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13084. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13085. context: this.context,
  13086. autoParseMusicName: this.autoParseMusicName
  13087. });
  13088. this.name = this.currentSong.name
  13089. this.artist = this.currentSong.artist
  13090. this.changeImageAnimation()
  13091. }
  13092. }
  13093. //上一个
  13094. private async playPrevious() {
  13095. if (!this.debounce()) {
  13096. return;
  13097. }
  13098. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  13099. this.randomModePlayFromHistory()
  13100. return;
  13101. }
  13102. if (this.curIndex == 0) {
  13103. this.curIndex = this.songList.length - 1;
  13104. } else {
  13105. this.curIndex--;
  13106. }
  13107. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13108. this.stop();
  13109. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  13110. this.currentSong = this.songList[this.curIndex];
  13111. Logger.info('heanup playPrevious', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  13112. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13113. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13114. context: this.context,
  13115. autoParseMusicName: this.autoParseMusicName
  13116. });
  13117. this.name = this.songList[this.curIndex].name
  13118. this.artist = this.songList[this.curIndex].artist
  13119. this.changeImageAnimation()
  13120. }
  13121. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  13122. private async randomModePlayFromHistory() {
  13123. if (this.historyList.length >= 2) {
  13124. // 播放历史记录的第二首
  13125. const prevSong = this.historyList[1];
  13126. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  13127. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13128. this.stop();
  13129. // 直接使用历史记录中的歌曲信息,历史记录中的数据应该是完整的
  13130. this.currentSong = prevSong;
  13131. Logger.info('heanup randomModePlayFromHistory', `直接使用历史歌曲信息: ${prevSong.name}, type: ${prevSong.type}`);
  13132. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13133. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13134. context: this.context,
  13135. autoParseMusicName: this.autoParseMusicName
  13136. });
  13137. this.cover = prevSong.pixelMapPath
  13138. this.artist = prevSong.artist
  13139. this.name = prevSong.name;
  13140. console.info('onecold startPlayOrResumePlay 11434')
  13141. this.startPlayOrResumePlay();
  13142. } else {
  13143. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  13144. if (this.curIndex === 0) {
  13145. this.curIndex = this.songList.length - 1;
  13146. } else {
  13147. this.curIndex--;
  13148. }
  13149. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13150. this.stop();
  13151. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  13152. this.currentSong = this.songList[this.curIndex];
  13153. Logger.info('heanup randomModePlayFromHistory', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  13154. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13155. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13156. context: this.context,
  13157. autoParseMusicName: this.autoParseMusicName
  13158. });
  13159. this.artist = this.songList[this.curIndex].artist
  13160. this.name = this.songList[this.curIndex].name;
  13161. this.changeImageAnimation()
  13162. }
  13163. }
  13164. debounce() {
  13165. const delay = 600;
  13166. let cur = new Date().getTime();
  13167. if (cur - this.last > delay) {
  13168. this.last = cur;
  13169. return true;
  13170. }
  13171. return false;
  13172. }
  13173. /**
  13174. * Sets whether the screen is a constant based on the playback status.
  13175. */
  13176. watchStatus() {
  13177. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  13178. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  13179. this.windowClass.setWindowKeepScreenOn(true);
  13180. } else {
  13181. this.windowClass.setWindowKeepScreenOn(false);
  13182. }
  13183. }
  13184. /**
  13185. * Volume gesture method onActionStart.
  13186. *
  13187. * @param event Gesture event.
  13188. */
  13189. private customDialogComponentIdMM: number = 0
  13190. @Builder
  13191. customDialogComponentMM() {
  13192. Column() {
  13193. Row() {
  13194. Blank()
  13195. Text('验证密码')
  13196. .fontSize(22)
  13197. .fontColor($r('app.color.pri_bg'))
  13198. .margin({ top: 18 })
  13199. Blank()
  13200. Image($r('app.media.close'))
  13201. .fillColor(Color.White)
  13202. .margin({ top: 18, right: 18 })
  13203. .width(20)
  13204. .onClick(() => {
  13205. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  13206. })
  13207. }
  13208. .width('100%') // 使Row占据整个宽度
  13209. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  13210. Verify({
  13211. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  13212. });
  13213. }.height('60%')
  13214. .backgroundColor($r('app.color.index_background'))
  13215. .justifyContent(FlexAlign.SpaceBetween)
  13216. }
  13217. private handleVerifyCompleted(isSuccess: boolean) {
  13218. if (isSuccess) {
  13219. console.log('验证成功');
  13220. // 在这里处理验证成功后的逻辑
  13221. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  13222. this.currentPath = this.lockPath
  13223. this.getSortedFiles(this.currentPath)
  13224. } else {
  13225. // console.log('验证失败');
  13226. ToastUtil.showToast('验证失败')
  13227. }
  13228. }
  13229. private showVerifyDialog() {
  13230. promptAction.openCustomDialog({
  13231. transition: TransitionEffect.asymmetric(
  13232. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  13233. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  13234. ,
  13235. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  13236. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  13237. ),
  13238. builder: () => {
  13239. this.customDialogComponentMM()
  13240. },
  13241. isModal: true,
  13242. autoCancel: true,
  13243. maskColor: Color.Transparent,
  13244. alignment: DialogAlignment.Bottom,
  13245. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  13246. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  13247. console.log("dialog onWillDismiss")
  13248. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  13249. dismissDialogAction.dismiss()
  13250. }
  13251. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  13252. dismissDialogAction.dismiss()
  13253. }
  13254. }
  13255. }).then((dialogId: number) => {
  13256. this.customDialogComponentIdMM = dialogId
  13257. })
  13258. }
  13259. //左滑操作 移动文件 重命名 删除等操作
  13260. @Builder
  13261. DeleteButton(item: VideoItem, index: number, filePath: string) {
  13262. Row() {
  13263. //加入收藏
  13264. Button() {
  13265. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  13266. .fillColor(Color.White)
  13267. .width(20)
  13268. }
  13269. .width(40)
  13270. .height(40)
  13271. .type(ButtonType.Circle)
  13272. .backgroundColor(this.themeColor)
  13273. .margin(5)
  13274. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13275. .onClick(() => {
  13276. if (item) {
  13277. this.doFav(item)
  13278. }
  13279. })
  13280. //加入下一首播放
  13281. Button() {
  13282. Image($r('app.media.next_to_play'))
  13283. .fillColor(Color.White)
  13284. .width(20)
  13285. }
  13286. .width(40)
  13287. .height(40)
  13288. .type(ButtonType.Circle)
  13289. .backgroundColor(this.themeColor)
  13290. .margin(5)
  13291. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13292. .onClick(() => {
  13293. this.addToNextPlay(item);
  13294. })
  13295. //复制文件
  13296. Button() {
  13297. Image($r('app.media.copy'))
  13298. .fillColor(Color.White)
  13299. .width(20)
  13300. }
  13301. .width(40)
  13302. .height(40)
  13303. .type(ButtonType.Circle)
  13304. .backgroundColor(this.themeColor)
  13305. .margin(5)
  13306. .id(filePath + 'copy')
  13307. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13308. .onClick(() => {
  13309. this.showCopyDialog(false, item, index, filePath + 'copy');
  13310. })
  13311. //移动文件
  13312. Button() {
  13313. Image($r('app.media.cut'))
  13314. .fillColor(Color.White)
  13315. .width(20)
  13316. }
  13317. .width(40)
  13318. .height(40)
  13319. .type(ButtonType.Circle)
  13320. .backgroundColor(this.themeColor)
  13321. .margin(5)
  13322. .id(filePath)
  13323. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13324. .onClick(() => {
  13325. this.showCutDialog(false, item, index, filePath);
  13326. })
  13327. Button() {
  13328. Image($r('app.media.cut_current'))
  13329. .fillColor(Color.White)
  13330. .width(20)
  13331. }
  13332. .width(40)
  13333. .height(40)
  13334. .type(ButtonType.Circle)
  13335. .backgroundColor(this.themeColor)
  13336. .margin(5)
  13337. .id(filePath + 'current')
  13338. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  13339. (this.isHasDir ? Visibility.Visible : Visibility.None))
  13340. .onClick(() => {
  13341. this.showCutDialog(true, item, index, filePath + 'current');
  13342. })
  13343. //重命名
  13344. Button() {
  13345. Image($r('app.media.rename2'))
  13346. .fillColor(Color.White)
  13347. .width(20)
  13348. }
  13349. .width(40)
  13350. .height(40)
  13351. .type(ButtonType.Circle)
  13352. .backgroundColor(this.themeColor)
  13353. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  13354. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  13355. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  13356. .margin(5)
  13357. .onClick(() => {
  13358. this.showReNameDialog(item, index + '', filePath)
  13359. })
  13360. Button() {
  13361. Image($r('app.media.delete2'))
  13362. .fillColor(Color.White)
  13363. .width(20)
  13364. }
  13365. .width(40)
  13366. .height(40)
  13367. .type(ButtonType.Circle)
  13368. .backgroundColor(this.themeColor)
  13369. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  13370. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  13371. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  13372. .margin(5)
  13373. .onClick(() => {
  13374. this.selectedFiles.push(item)
  13375. this.showWarnIsDelete()
  13376. // this.showWarnIsDeleteFile(item, index + '', filePath)
  13377. })
  13378. Button() {
  13379. Image($r('app.media.share2'))
  13380. .fillColor(Color.White)
  13381. .width(20)
  13382. }
  13383. .width(40)
  13384. .height(40)
  13385. .type(ButtonType.Circle)
  13386. .backgroundColor(this.themeColor)
  13387. .margin(5)
  13388. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13389. .onClick(() => {
  13390. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  13391. })
  13392. }
  13393. }
  13394. /**
  13395. * 穿山甲banner广告
  13396. */
  13397. // private declare bannerAd: CSJNativeExpressAd;
  13398. // @State private status: string = "未加载"
  13399. // @State private isShowAd: boolean = false
  13400. // private declare mAdSlot: AdSlot;
  13401. // private mBiddingAdm = '' //服务端bidding才需要设置
  13402. // private expressLoadAdListener: NativeExpressAdListener = {
  13403. // /**
  13404. // * 加载失败的回调
  13405. // *
  13406. // * @param code
  13407. // * @param message
  13408. // */
  13409. // onError: (code: number, message: string) => {
  13410. // console.error("加载广告失败,code=" + code + ",message=" + message);
  13411. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  13412. // },
  13413. //
  13414. // /**
  13415. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  13416. // *
  13417. // * @param ads 返回的广告列表
  13418. // */
  13419. //
  13420. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  13421. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  13422. // if (ads && ads.length > 0) {
  13423. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  13424. // ad.setExpressInteractionListener({
  13425. // /**
  13426. // *广告的点击回调
  13427. // * @param type 广告的交互类型
  13428. // */
  13429. // onAdClicked: (type: number) => {
  13430. // console.log("BannerExpressAdPage==onAdClicked......");
  13431. // },
  13432. //
  13433. // /**
  13434. // * 广告的展示回调 每个广告仅回调一次
  13435. // * @param type 广告的交互类型
  13436. // */
  13437. // onAdShow: (type: number) => {
  13438. // console.log("BannerExpressAdPage==onAdShow......");
  13439. // },
  13440. //
  13441. // /**
  13442. // * 模板渲染失败
  13443. // */
  13444. // onRenderFail: (code: number, msg: string) => {
  13445. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  13446. // },
  13447. //
  13448. // /**
  13449. // * 模板渲染成功
  13450. // * @param width 返回view的宽 单位 vp
  13451. // * @param height 返回view的高 单位 vp
  13452. // */
  13453. // onRenderSuccess: (width: number, height: number) => {
  13454. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  13455. // this.bannerAd = ad;
  13456. // this.status = "广告加载完成待展示";
  13457. //
  13458. // this.showBannerAd()
  13459. // }
  13460. // })
  13461. // //渲染广告
  13462. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  13463. // this.setDislikeCallback(ad); //设置dislike
  13464. // ad.render(this.getUIContext())
  13465. // this.status = "广告加载中...";
  13466. // });
  13467. // }
  13468. // }
  13469. // }
  13470. //
  13471. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  13472. // ad.setDislikeCallback({
  13473. // /**
  13474. // * dislike show
  13475. // */
  13476. // onShow: () => {
  13477. // console.log("BannerExpressAdPage==dislike......show");
  13478. // },
  13479. //
  13480. // /**
  13481. // * @param position 选择的位置
  13482. // * @param value 选择的内容
  13483. // * @param enforceRemove 是否强制关闭广告
  13484. // */
  13485. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  13486. // this.isShowAd = false;
  13487. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  13488. // ",enforce=" + enforceRemove);
  13489. // },
  13490. //
  13491. // /**
  13492. // * 点击取消
  13493. // */
  13494. // onCancel: () => {
  13495. // console.log("BannerExpressAdPage==dislike......onCancel");
  13496. // }
  13497. //
  13498. // })
  13499. // }
  13500. /**
  13501. * 加载Banner广告
  13502. */
  13503. loadBannerAd(rit: string) {
  13504. // if (Utility.isNoble()) {
  13505. // return
  13506. // }
  13507. // if (!Utility.isPassInstallTime(2)) {
  13508. // return
  13509. // }
  13510. // this.isShowAd = false;
  13511. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  13512. // this.mAdSlot = new AdSlotBuilder()
  13513. // .setCodeId(rit)
  13514. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  13515. // .setAdCount(1)
  13516. // .setBidAdm(this.mBiddingAdm)
  13517. // .build()
  13518. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  13519. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  13520. // this.status = "广告加载中..."
  13521. }
  13522. /**
  13523. * 展示Banner广告
  13524. */
  13525. // showBannerAd() {
  13526. // if (!this.bannerAd) {
  13527. // return
  13528. // }
  13529. // this.isShowAd = true
  13530. // this.status = "已展示"
  13531. // }
  13532. /**
  13533. * 穿山甲广告代码结束
  13534. */
  13535. /**
  13536. * 处理歌单播放请求
  13537. */
  13538. private async handlePlaylistPlayRequest(playlistId: string, playlistName:
  13539. string, songFilePaths: string[], startIndex: number,isJump: boolean) {
  13540. try {
  13541. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 歌曲数量: ${songFilePaths.length}, 开始索引: ${startIndex}`)
  13542. // 检查是否为WebDAV播放请求
  13543. if (playlistId === 'webdav-playlist') {
  13544. Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
  13545. // 从全局内存读取videoItems数据
  13546. const videoItems = getWebdavVideoItems();
  13547. const currentPlayIndex = getWebdavCurrentPlayIndex();
  13548. Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
  13549. if (videoItems && videoItems.length > 0) {
  13550. // 验证webdav_account_id设置情况
  13551. const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
  13552. Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
  13553. if(isJump){
  13554. this.setShowPlayTrue()//显示播放页
  13555. }
  13556. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName)
  13557. return
  13558. } else {
  13559. return
  13560. }
  13561. }
  13562. if (playlistId === 'navidrome-playlist') {
  13563. Logger.info(`heanup 检测到Navidrome播放请求,从内存读取videoItems`);
  13564. const videoItems = getNavidromeVideoItems();
  13565. const currentPlayIndex = getNavidromeCurrentPlayIndex();
  13566. Logger.info(`heanup Navidrome歌曲列表长度: ${videoItems.length}`);
  13567. if (videoItems && videoItems.length > 0) {
  13568. if(isJump){
  13569. this.setShowPlayTrue()//显示播放页
  13570. }
  13571. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName);
  13572. return;
  13573. } else {
  13574. Logger.warn('heanup Navidrome播放请求缺少歌曲数据');
  13575. return;
  13576. }
  13577. }
  13578. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  13579. const songMap: Map<number, VideoItem> = new Map()
  13580. let completedQueries = 0
  13581. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  13582. // 遍历所有文件路径,使用索引记录位置
  13583. for (let i = 0; i < songFilePaths.length; i++) {
  13584. const filePath = songFilePaths[i]
  13585. const index = i
  13586. // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  13587. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  13588. const queryPromise = this.table.queryVideoByFilePath(filePath)
  13589. // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  13590. queryPromise.then((videoItem) => {
  13591. completedQueries++
  13592. // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  13593. if (videoItem) {
  13594. // 使用索引作为key保存到Map中,保持原始顺序
  13595. songMap.set(index, videoItem)
  13596. // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  13597. } else {
  13598. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  13599. }
  13600. // 检查是否所有歌曲都已加载完成
  13601. if (completedQueries === songFilePaths.length) {
  13602. // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  13603. // 按照索引顺序重建歌曲数组
  13604. const songs: VideoItem[] = []
  13605. for (let j = 0; j < songFilePaths.length; j++) {
  13606. const song = songMap.get(j)
  13607. if (song) {
  13608. songs.push(song)
  13609. // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  13610. }
  13611. }
  13612. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  13613. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  13614. }
  13615. }).catch((error: Error) => {
  13616. completedQueries++
  13617. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  13618. // 即使出错也要检查是否完成所有查询
  13619. if (completedQueries === songFilePaths.length) {
  13620. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  13621. // 按照索引顺序重建歌曲数组
  13622. const songs: VideoItem[] = []
  13623. for (let j = 0; j < songFilePaths.length; j++) {
  13624. const song = songMap.get(j)
  13625. if (song) {
  13626. songs.push(song)
  13627. }
  13628. }
  13629. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  13630. }
  13631. })
  13632. }
  13633. } catch (error) {
  13634. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  13635. ToastUtil.showToast('播放失败')
  13636. }
  13637. }
  13638. /**
  13639. * 完成歌单加载并开始播放
  13640. */
  13641. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string) {
  13642. if (songs.length === 0) {
  13643. Logger.error('heanup 没有找到任何可播放的歌曲')
  13644. ToastUtil.showToast('没有找到可播放的歌曲')
  13645. return
  13646. }
  13647. this.songList = songs
  13648. this.sonDataSource.pushArrayData(songs)
  13649. this.sonDataSource.notifyDataReload()
  13650. this.curIndex = startIndex
  13651. if (songs[startIndex]) {
  13652. // 确保当前播放的歌曲也更新到存储
  13653. AppStorage.setOrCreate('currentSong', songs[startIndex])
  13654. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  13655. this.doPlay(songs[startIndex], startIndex, true)
  13656. }
  13657. PreferencesUtil.putSync('LastMusicList', this.songList)
  13658. // ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  13659. }
  13660. }
  13661. //视频气泡窗口的布局
  13662. @Builder
  13663. function customPopupBuilder(dataBu: BubbleBean) {
  13664. List() {
  13665. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  13666. ListItem() {
  13667. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13668. Row() {
  13669. Column() {
  13670. Image(dataBu.imageRes[index])
  13671. .height(28)
  13672. .fillColor(dataBu.color)
  13673. .alignSelf(ItemAlign.Center)
  13674. }
  13675. .width(32)
  13676. Text(item)
  13677. .padding({
  13678. top: 10,
  13679. bottom: 10,
  13680. right: 10,
  13681. left: 10
  13682. })
  13683. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  13684. .textAlign(TextAlign.Start)
  13685. .width("100%")
  13686. }
  13687. }
  13688. .backgroundColor($r('app.color.settings_background_main'))
  13689. .margin({ top: 6, bottom: 6 })
  13690. }
  13691. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  13692. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  13693. TransitionEffect.scale({ x: 0, y: 0 })))
  13694. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  13695. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  13696. .onClick(() => {
  13697. dataBu.onItemClick?.(index)
  13698. })
  13699. })
  13700. }
  13701. .scrollBar(BarState.Off)
  13702. .width(120)
  13703. .divider({
  13704. strokeWidth: 1,
  13705. color: "#22FFFFFF"
  13706. })
  13707. }
  13708. // Function to calculate a hash for the file list
  13709. function simpleHash(fileList: string[]): string {
  13710. let hash = 0;
  13711. const str = fileList.join(',');
  13712. for (let i = 0; i < str.length; i++) {
  13713. const char = str.charCodeAt(i);
  13714. hash = (hash << 5) - hash + char;
  13715. hash |= 0; // Convert to 32bit integer
  13716. }
  13717. return hash.toString();
  13718. }
  13719. interface MoreItem {
  13720. id: number;
  13721. image: Resource;
  13722. title: string;
  13723. }
  13724. //视频气泡窗口的布局
  13725. @Builder
  13726. function cutPopupBuilder(dataBu: BubbleBean) {
  13727. Column() {
  13728. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  13729. .padding({
  13730. top: 10,
  13731. bottom: 10,
  13732. right: 10,
  13733. left: 10
  13734. })
  13735. .textAlign(TextAlign.Start)
  13736. .width(160)
  13737. .fontWeight(666)
  13738. .fontSize(16)
  13739. List() {
  13740. ForEach(dataBu.data, (item: string, index: number) => {
  13741. ListItem() {
  13742. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13743. Row() {
  13744. Column() {
  13745. Image($r('app.media.music_group'))
  13746. .height(28)
  13747. .fillColor(dataBu.color)
  13748. .alignSelf(ItemAlign.Center)
  13749. }
  13750. .width(32)
  13751. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  13752. .padding({
  13753. top: 10,
  13754. bottom: 10,
  13755. right: 10,
  13756. left: 10
  13757. })
  13758. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  13759. .fontSize(15)
  13760. }
  13761. }
  13762. .backgroundColor(Color.Transparent)
  13763. .margin({ top: 7, bottom: 7 })
  13764. }
  13765. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  13766. .animation({ duration: 500 }),
  13767. TransitionEffect.scale({ x: 0, y: 0 })))
  13768. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  13769. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  13770. .onClick(() => {
  13771. dataBu.onItemClick?.(index)
  13772. })
  13773. })
  13774. }
  13775. .scrollBar(BarState.Off)
  13776. .width(150)
  13777. .divider({
  13778. strokeWidth: 1,
  13779. color: "#22FFFFFF"
  13780. })
  13781. }
  13782. .height(300)
  13783. .padding({
  13784. bottom: 30
  13785. })
  13786. }
  13787. function getFileDirName(filePath: string,rootPath:string): string{
  13788. if(filePath===rootPath){
  13789. return '首页'
  13790. }
  13791. let result = FileUtil.getFileName(filePath)
  13792. if(StrUtil.isEmpty(result))
  13793. return ''
  13794. if(result.startsWith('.'))
  13795. result = result.replace(/\./g, '')
  13796. return result
  13797. }
  13798. //只扫描当前目录下文件(不扫描子文件夹)的方法
  13799. @Concurrent
  13800. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  13801. const table: MediaTable = new MediaTable(context);
  13802. try {
  13803. // 直接获取当前目录下的文件列表
  13804. const files = FileUtil.listFileSync(dirPath);
  13805. await Promise.all(files.map(async (file) => {
  13806. const fPath = `${dirPath}/${file}`;
  13807. // 跳过目录,只处理文件
  13808. if (FileUtil.isDirectory(fPath)) {
  13809. return;
  13810. }
  13811. // 跳过特定格式文件
  13812. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  13813. return;
  13814. }
  13815. // 检查是否为媒体文件
  13816. if (Utility.isMeidaByExtension(fPath)) {
  13817. let mType = CommonConstants.TYPE_LOCAL;
  13818. if (fPath.includes(lockPath)) {
  13819. mType = CommonConstants.TYPE_LOCK;
  13820. }
  13821. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  13822. context, fPath, mType, true
  13823. );
  13824. table.insert(mediaItem, (id: number) => {
  13825. // 插入回调函数
  13826. }, cover_api);
  13827. }
  13828. }));
  13829. } catch (error) {
  13830. console.error(' 扫描当前目录失败:', error);
  13831. }
  13832. }
  13833. //内嵌标签后更新库
  13834. @Concurrent
  13835. async function updateInfoDb(
  13836. context: Context,
  13837. filePath: string,
  13838. titleStr: string,
  13839. artistStr: string,
  13840. albumStr: string,
  13841. lyricConStr: string,
  13842. yearStr: string,
  13843. genreStr: string,
  13844. trackStr: string,
  13845. albumArtistStr: string,
  13846. composerStr: string,
  13847. lyricistStr: string,
  13848. commentStr: string,
  13849. discStr: string,
  13850. ): Promise<boolean> {
  13851. const table: MediaTable = new MediaTable(context);
  13852. await new Promise<void>((resolve, reject) => {
  13853. table.getRdbStore(context, (err:Error) => {
  13854. err ? reject(err) : resolve();
  13855. });
  13856. });
  13857. return await new Promise<boolean>((resolve) => {
  13858. table.updateMediaInfo(filePath, titleStr, artistStr, albumStr, lyricConStr,
  13859. yearStr, genreStr, trackStr, albumArtistStr, composerStr, lyricistStr, commentStr, discStr,
  13860. (success: boolean, error?: string) => {
  13861. if (success) {
  13862. console.log("onecold 编辑信息成功,数据库已同步");
  13863. } else {
  13864. console.error("onecold 编辑信息数据库失败原因: " + error);
  13865. }
  13866. resolve(success);
  13867. });
  13868. });
  13869. }