LocalMusic.ets 532 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397
  1. import TitleBar from './TitleBar'
  2. import { curves, display, MenuModifier,PiPWindow, promptAction, router, SymbolGlyphModifier, window } from '@kit.ArkUI';
  3. import { VideoItem } from '../viewmodel/VideoItem';
  4. import { LengthMetrics, SegmentButton,SegmentButtonOptions } from '@kit.ArkUI';
  5. import { getWebdavVideoItems, getWebdavCurrentPlayIndex } from '../pages/WebDavMainPage';
  6. import {
  7. ButtonFancyModifier,
  8. ImageFancyModifier,
  9. ShadowModifier,
  10. SymbolGlyphFancyModifier } from '../common/util/AttributeModifierUtil'
  11. import {
  12. AppUtil,
  13. ArrayUtil,
  14. Base64Util,
  15. DateUtil,
  16. DeviceUtil,
  17. FileUtil,
  18. GlobalContext,
  19. LogUtil,
  20. MD5,
  21. PreferencesUtil,
  22. RandomUtil,
  23. StrUtil,
  24. ToastUtil
  25. } from '@pura/harmony-utils';
  26. import { imagePathToPixelMap } from '../common/util/CommUtils';
  27. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  28. import { CommonConstants } from '../common/constants/CommonConstants';
  29. import { EventConstants } from '../common/constants/EventConstants';
  30. import Logger from '../common/util/Logger';
  31. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  32. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  33. import { BubbleBean } from '../viewmodel/BubbleBean';
  34. import { PopupPosition, XPopup } from '@chinalike/popup';
  35. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  36. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  37. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  38. import { MessageEvents, util, worker, ErrorEvent } from '@kit.ArkTS';
  39. import { Verify } from './Verify';
  40. import { taskpool } from '@kit.ArkTS';
  41. import { RotatingCover } from './RotatingCover';
  42. import { PlayConstants } from '../common/constants/PlayConstants';
  43. import { effectKit } from '@kit.ArkGraphics2D';
  44. import { ColorConversion } from '../common/util/ColorConversion';
  45. import { LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  46. import { AvSessionController } from '../controller/AvSessionController';
  47. import { repairAudioMetadata, convertDsfToWav, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  48. import { FFMpegTags,Utility } from '../common/util/Utility';
  49. import { TagsContentCover } from '../view/TagsContentCover';
  50. import {
  51. // DeviceChangeReason,
  52. IjkMediaPlayer,
  53. InterruptEvent,
  54. InterruptHintType,
  55. LogUtils,
  56. OnBufferingUpdateListener,
  57. OnCompletionListener,
  58. OnErrorListener,
  59. OnInfoListener,
  60. OnPreparedListener,
  61. OnSeekCompleteListener,
  62. OnTimedTextListener,
  63. OnVideoSizeChangedListener
  64. } from '@ohos/ijkplayer';
  65. import { PlayStatus } from '../common/PlayStatus';
  66. import fs from '@ohos.file.fs';
  67. import { image } from '@kit.ImageKit';
  68. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  69. import { UniversalDetector } from '@ohos/juniversalchardet';
  70. import { SettingPage } from '../pages/SettingPage';
  71. import { secondToTime,getTransverterText } from '../common/util/CommUtils';
  72. import { CommonConstants2 } from '../common/util/CommonConstants2';
  73. import { hilog } from '@kit.PerformanceAnalysisKit';
  74. import { LazyDataSource } from '../common/util/LazyDataSource';
  75. import MediaTable from '../common/util/MediaTable';
  76. import FileDeletionWatcher from '../common/util/FileDeletionWatcher';
  77. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  78. import ImageUtils from '../common/util/ImageUtils';
  79. import { ringtone } from '@kit.RingtoneKit';
  80. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  81. import { resourceManager } from '@kit.LocalizationKit';
  82. import { deviceInfo } from '@kit.BasicServicesKit';
  83. import { ensureSmbFileCached } from '../common/network/SmbFileCache';
  84. import { findWebDavCacheIfExists, triggerWebDavCacheDownload } from '../common/network/WebDavFileCache';
  85. import { navidromeApi } from '../common/network/NavidromeApi';
  86. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  87. import app from '@system.app';
  88. import { TextNodeController } from './PipLyricTextBuilder';
  89. import { IndexerView } from './IndexerView';
  90. import { KeyCode } from '@kit.InputKit';
  91. import { KnockController } from '../controller/KnockController';
  92. import { DeleteComptent } from '../view/DeleteComptent';
  93. import { ABLoopComptent } from '../view/ABLoopComptent';
  94. import { FixMessyView } from '../view/FixMessyView';
  95. import { parseCueFile,CueTrack,CueInfo } from '../common/util/CueUtils';
  96. import { CueComptent } from '../view/CueComptent';
  97. import PlaylistTable from '../common/util/PlaylistTable';
  98. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  99. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  100. import { convertPlaylistSongsToVideoItems, emptyView,updateAllSongsSortOrder } from '../pages/PlaylistDetailPage';
  101. import { Playlist, PlaylistSong } from '../viewmodel/Playlist';
  102. import { Song } from '../viewmodel/Song';
  103. import { SongType } from '../common/enums/SongType';
  104. import { RemoteDriveManager, WebDavAuthInfo as WebDavManagerAuthInfo,
  105. buildHttpHeadersWithWebDav,
  106. WebDavAuthItem} from '../common/util/RemoteDriveManager';
  107. import PermissionUtil from '../common/util/PermissionUtil'
  108. import { EditAudio, setRingTone } from './EditAudio';
  109. import { ExtractAccompaniment } from './ExtractAccompaniment';
  110. import { ExtractAudioFromVideo } from './ExtractAudioFromVideo';
  111. import { AudioFormatConverter } from './AudioFormatConverter';
  112. import { MergeAudio } from './MergeAudio';
  113. import { AIVoiceSeparation } from './AIVoiceSeparation';
  114. import { WebDavUrlUtil } from '../common/util/WebDavUrlUtil';
  115. import { ChangeTone } from './ChangeTone';
  116. import {
  117. hdsEffect,
  118. HdsVisualComponent,
  119. HdsSceneController,
  120. HdsSceneType,
  121. HdsVisualComponentAttribute,
  122. } from '@kit.UIDesignKit';
  123. import { GlobalAlphabetIndexerModifier } from '../Styels/GlobalStyles'
  124. import { getFirstLetter } from '../Constants';
  125. const TAG = 'LocalMusic';
  126. /**
  127. * 歌单播放事件数据
  128. */
  129. interface PlaylistEventData {
  130. playlistId: string;
  131. playlistName: string;
  132. songCount: number;
  133. startIndex: number;
  134. songFilePaths: string[];
  135. webDavAuthInfo?: WebDavAuthItem; // 新增WebDAV认证信息
  136. }
  137. const DEFAULT_INDEX =
  138. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  139. 'X', 'Y', 'Z']
  140. //排序类型
  141. function getTypeOrder(type: number) {
  142. switch (type) {
  143. case CommonConstants.TYPE_IS_DIR:
  144. return 1; // First
  145. case CommonConstants.TYPE_IS_CSJAD:
  146. return 2; // Middle
  147. case CommonConstants.TYPE_LOCAL:
  148. return 3; // Last
  149. case CommonConstants.TYPE_WEBDAV:
  150. case CommonConstants.TYPE_SMB:
  151. case CommonConstants.TYPE_NAVIDROME:
  152. return 3;
  153. default:
  154. return 4; // Unknown types, if any, go last
  155. }
  156. }
  157. function isWebDavType(type: number): boolean {
  158. return type === CommonConstants.TYPE_WEBDAV;
  159. }
  160. function isSmbType(type: number): boolean {
  161. return type === CommonConstants.TYPE_SMB;
  162. }
  163. function isNavidromeType(type: number): boolean {
  164. return type === CommonConstants.TYPE_NAVIDROME;
  165. }
  166. function isRemoteCloudType(type: number): boolean {
  167. return isWebDavType(type) || isSmbType(type) || isNavidromeType(type);
  168. }
  169. function getShareNameFromFilePath(filePath?: string): string | undefined {
  170. if (!filePath) {
  171. return undefined;
  172. }
  173. const match = filePath.match(/^smb:\/\/[^/]+\/([^/]+)/i);
  174. return match && match[1] ? match[1] : undefined;
  175. }
  176. function removeSharePrefixFromPath(path: string, primaryShare?: string, secondaryShare?: string): string {
  177. const uniqueShares: string[] = [];
  178. [primaryShare, secondaryShare].forEach((name?: string) => {
  179. const cleaned = name ? name.replace(/^\/+|\/+$/g, '') : '';
  180. if (cleaned.length > 0 && !uniqueShares.some(item => item.toLowerCase() === cleaned.toLowerCase())) {
  181. uniqueShares.push(cleaned);
  182. }
  183. });
  184. if (uniqueShares.length === 0) {
  185. return path;
  186. }
  187. let result = path;
  188. for (let i = 0; i < uniqueShares.length; i++) {
  189. const share = uniqueShares[i];
  190. const lowerPath = result.toLowerCase();
  191. const lowerShare = share.toLowerCase();
  192. if (lowerPath === lowerShare) {
  193. result = '';
  194. break;
  195. }
  196. const prefix = `${lowerShare}/`;
  197. if (lowerPath.startsWith(prefix)) {
  198. result = result.substring(share.length + 1);
  199. break;
  200. }
  201. }
  202. return result;
  203. }
  204. function extractSmbRelativePath(song: VideoItem, shareNameOverride?: string): string {
  205. const shareFromFilePath = getShareNameFromFilePath(song.filePath);
  206. const shareName = shareNameOverride ?? shareFromFilePath;
  207. if (song.remote_rel_path && song.remote_rel_path.length > 0) {
  208. const cleaned = song.remote_rel_path.replace(/^\/+/, '');
  209. return removeSharePrefixFromPath(cleaned, shareName, shareFromFilePath);
  210. }
  211. if (!song.filePath) {
  212. return '';
  213. }
  214. const match = song.filePath.match(/^smb:\/\/[^/]+\/([^/]+)(\/.*)?$/i);
  215. if (!match) {
  216. return song.filePath.replace(/^\/+/, '');
  217. }
  218. const remainder = match[2] ? match[2].replace(/^\/+/, '') : '';
  219. if (remainder.length === 0) {
  220. return '';
  221. }
  222. return remainder;
  223. }
  224. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  225. interface MetadataExtractionOptions {
  226. context?: common.Context;
  227. autoParseMusicName?: boolean;
  228. }
  229. interface WorkerEditMusicResult {
  230. success: boolean;
  231. error?: string;
  232. coverResult?: boolean;
  233. needRefreshList?: boolean;
  234. metadataResult?: boolean;
  235. }
  236. interface LocalEditMusicPayload {
  237. context: Context;
  238. item: VideoItem;
  239. titleStr: string;
  240. artistStr: string;
  241. ablumStr: string;
  242. yearStr: string;
  243. genreStr: string;
  244. trackStr: string;
  245. albumArtistStr: string;
  246. composerStr: string;
  247. lyricistStr: string;
  248. commentStr: string;
  249. discStr: string;
  250. lyricConStr: string;
  251. imagePathStr: string;
  252. currentPath: string;
  253. packName: string;
  254. modeType: number;
  255. autoParseMusicName: boolean;
  256. }
  257. interface WorkerMetadataPayload {
  258. originFilePath: string;
  259. originId?: string;
  260. bit_rate?: string;
  261. duration?: string;
  262. sampleRate?: string;
  263. mimeType?: string;
  264. md5Str?: string;
  265. videoSize?: number;
  266. size?: string;
  267. pixelMapPath?: string;
  268. artist?: string;
  269. album?: string;
  270. name?: string;
  271. lyricContent?: string;
  272. bits_per_raw_sample?: string;
  273. channels?: string;
  274. channel_layout?: string;
  275. start_time?: string;
  276. genre?: string;
  277. year?: string;
  278. probe_score?: number;
  279. track?: string;
  280. disc?: string;
  281. ALBUMARTIST?: string;
  282. COMPOSER?: string;
  283. COMMENT?: string;
  284. LYRICIST?: string;
  285. nb_streams?: number;
  286. nb_programs?: number;
  287. error?: string;
  288. }
  289. interface WebDavMetadataUpdatePayload {
  290. filePath: string;
  291. pixelMapPath?: string;
  292. name?: string;
  293. artist?: string;
  294. }
  295. const metadataExtractionInFlight: Set<string> = new Set();
  296. function scheduleMetadataExtractionFromCache(
  297. song: VideoItem,
  298. cachePath: string,
  299. options?: MetadataExtractionOptions
  300. ): void {
  301. if (!song || !cachePath || !song.filePath || !options || !options.context) {
  302. return;
  303. }
  304. if (!isRemoteCloudType(song.type ?? -1)) {
  305. return;
  306. }
  307. if (metadataExtractionInFlight.has(song.filePath)) {
  308. return;
  309. }
  310. if (song.bit_rate && song.sampleRate && song.duration) {
  311. return;
  312. }
  313. metadataExtractionInFlight.add(song.filePath);
  314. workerInstance.postMessage({
  315. code: 5,
  316. data: options.context,
  317. data2: cachePath,
  318. data3: song.type,
  319. data4: {
  320. name:song.name,
  321. originFilePath: song.filePath,
  322. originId: song.id,
  323. autoParseMusicName: options.autoParseMusicName ?? false
  324. }
  325. });
  326. }
  327. function sanitizePlaybackUrl(rawUrl: string | null | undefined): string {
  328. if (!rawUrl) {
  329. return '';
  330. }
  331. try {
  332. const decoded = decodeURI(rawUrl);
  333. const encoded = encodeURI(decoded);
  334. // encodeURI 不会处理 #,手动转义避免播放器把剩余内容当作片段
  335. return encoded.replace(/#/g, '%23');
  336. } catch (error) {
  337. const err = error as Error;
  338. Logger.warn(TAG, `URL 编码失败,使用降级方案: ${err?.message}`);
  339. return rawUrl.replace(/ /g, '%20').replace(/#/g, '%23');
  340. }
  341. }
  342. function cloneVideoItem(item: VideoItem): VideoItem {
  343. const copy = new VideoItem(
  344. item.name,
  345. item.id,
  346. item.filePath,
  347. item.type,
  348. item.videoSize,
  349. item.cTime,
  350. item.size,
  351. item.pixelMapPath,
  352. item.artist,
  353. item.album,
  354. item.fileName,
  355. item.lastPlayed
  356. );
  357. copy.parentPath = item.parentPath;
  358. copy.isFav = item.isFav;
  359. copy.size = item.size;
  360. copy.pixelMapPath = item.pixelMapPath;
  361. copy.artist = item.artist;
  362. copy.album = item.album;
  363. copy.duration = item.duration;
  364. copy.mimeType = item.mimeType;
  365. copy.sampleRate = item.sampleRate;
  366. copy.trackCount = item.trackCount;
  367. copy.lastPlayedStr = item.lastPlayedStr;
  368. copy.playCount = item.playCount;
  369. copy.lyricContent = item.lyricContent;
  370. copy.md5Str = item.md5Str;
  371. copy.extra_json = item.extra_json;
  372. copy.pyStr = item.pyStr;
  373. copy.bit_rate = item.bit_rate;
  374. copy.probe_score = item.probe_score;
  375. copy.year = item.year;
  376. copy.nb_streams = item.nb_streams;
  377. copy.nb_programs = item.nb_programs;
  378. copy.genre = item.genre;
  379. copy.track = item.track;
  380. copy.bits_per_raw_sample = item.bits_per_raw_sample;
  381. copy.channels = item.channels;
  382. copy.channel_layout = item.channel_layout;
  383. copy.start_time = item.start_time;
  384. copy.ALBUMARTIST = item.ALBUMARTIST;
  385. copy.COMPOSER = item.COMPOSER;
  386. copy.LYRICIST = item.LYRICIST;
  387. copy.COMMENT = item.COMMENT;
  388. copy.disc = item.disc;
  389. copy.webdav_account_id = item.webdav_account_id;
  390. copy.remote_rel_path = item.remote_rel_path;
  391. return copy;
  392. }
  393. /**
  394. * 异步设置videoUrl的辅助方法,处理WebDAV URL的构建
  395. * @param song 歌曲对象
  396. * @returns Promise<string> 完整的URL
  397. */
  398. /**
  399. * 设置videoUrl,通过webdav_account_id设置完整的 URL
  400. * @param song 歌曲对象
  401. * @returns Promise<string> 完整的URL
  402. */
  403. async function setVideoUrlForSong(song: VideoItem, options?: MetadataExtractionOptions): Promise<string> {
  404. const metadataOptions = options ?? {};
  405. if (isWebDavType(song.type) && song.webdav_account_id) {
  406. try {
  407. Logger.info(TAG, `WebDAV 路径信息 remote_rel_path: ${song.remote_rel_path}`);
  408. Logger.info(TAG, `WebDAV 路径信息 filePath: ${song.filePath}`);
  409. const relativePath = song.remote_rel_path || song.filePath;
  410. const manager = RemoteDriveManager.getInstance();
  411. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  412. if (account) {
  413. const cachePath = await findWebDavCacheIfExists(account, relativePath);
  414. if (cachePath) {
  415. Logger.info(TAG, `WebDAV 缓存命中,直接播放: ${cachePath}`);
  416. scheduleMetadataExtractionFromCache(song, cachePath, metadataOptions);
  417. return cachePath;
  418. }
  419. const fullUrlFromAccount = WebDavUrlUtil.buildFullUrl(account, relativePath);
  420. if (fullUrlFromAccount) {
  421. const sanitizedUrl = sanitizePlaybackUrl(fullUrlFromAccount);
  422. const downloadPromise = triggerWebDavCacheDownload(account, relativePath, sanitizedUrl);
  423. if (downloadPromise) {
  424. downloadPromise.then((completedPath?: string | null) => {
  425. if (completedPath) {
  426. scheduleMetadataExtractionFromCache(song, completedPath, metadataOptions);
  427. }
  428. }).catch((error: Error) => {
  429. Logger.error(TAG, `WebDAV 缓存后台下载失败: ${error.message}`);
  430. });
  431. }
  432. Logger.info(TAG, `WebDAV 启动异步缓存: ${relativePath}`);
  433. return sanitizedUrl;
  434. }
  435. }
  436. const fallbackUrl = await WebDavUrlUtil.buildFullUrlByAccountId(song.webdav_account_id, relativePath);
  437. if (fallbackUrl) {
  438. Logger.warn(TAG, `WebDAV 使用全局查询到的URL: ${fallbackUrl}`);
  439. return sanitizePlaybackUrl(fallbackUrl);
  440. }
  441. Logger.error(TAG, `WebDAV URL构建失败,使用原始路径: ${relativePath}`);
  442. return sanitizePlaybackUrl(relativePath);
  443. } catch (error) {
  444. Logger.error(TAG, `WebDAV URL构建出错: ${(error as Error).message}`);
  445. const fallbackPath = song.remote_rel_path || song.filePath;
  446. return sanitizePlaybackUrl(fallbackPath);
  447. }
  448. }
  449. if (isNavidromeType(song.type) && song.webdav_account_id) {
  450. try {
  451. const manager = RemoteDriveManager.getInstance();
  452. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  453. if (!account) {
  454. throw new Error('Navidrome账号不可用');
  455. }
  456. const navSongId = song.remote_rel_path || song.id || song.filePath;
  457. const streamUrl = await navidromeApi.buildStreamUrl(account, navSongId);
  458. Logger.info(TAG, `Navidrome 流地址构建成功: ${streamUrl}`);
  459. return sanitizePlaybackUrl(streamUrl);
  460. } catch (error) {
  461. const err = error as Error;
  462. Logger.error(TAG, `Navidrome URL构建失败: ${err.message}`);
  463. throw new Error(err.message);
  464. }
  465. }
  466. if (isSmbType(song.type) && song.webdav_account_id) {
  467. try {
  468. const manager = RemoteDriveManager.getInstance();
  469. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  470. if (!account) {
  471. throw new Error('SMB账号不可用');
  472. }
  473. const relativePath = extractSmbRelativePath(song, account.smbShare);
  474. const cachedPath = await ensureSmbFileCached(account, relativePath);
  475. Logger.info(TAG, `SMB 缓存路径: ${cachedPath}`);
  476. scheduleMetadataExtractionFromCache(song, cachedPath, metadataOptions);
  477. return cachedPath;
  478. } catch (error) {
  479. const err = error as Error;
  480. Logger.error(TAG, `SMB 缓存失败: ${err.message}`);
  481. throw new Error(err.message);
  482. }
  483. }
  484. if (isWebDavType(song.type)) {
  485. Logger.warn(TAG, `WebDAV歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
  486. return sanitizePlaybackUrl(song.filePath);
  487. }
  488. if (isSmbType(song.type)) {
  489. Logger.warn(TAG, `SMB歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
  490. return song.filePath;
  491. }
  492. if (isNavidromeType(song.type)) {
  493. throw new Error('Navidrome歌曲缺少webdav_account_id,无法构建播放链接');
  494. }
  495. return song.filePath;
  496. }
  497. // 定义接口
  498. interface HiCarAspectRatio {
  499. ratio: number;
  500. name: string;
  501. }
  502. interface GeneratedObjectLiteralInterface_1 {
  503. assetId: string;
  504. title: string;
  505. artist: string;
  506. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  507. mediaUri: string;
  508. // 该字段大写,音频'AUDIO',视频'VIDEO'
  509. mediaType: string;
  510. mediaSize: number;
  511. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  512. startPosition: number;
  513. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  514. duration: number;
  515. albumCoverUri: string;
  516. albumTitle: string;
  517. appName: string;
  518. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  519. drmScheme: string;
  520. }
  521. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  522. const ITEM_HEIGHT: number = 65; // 列表项中高度
  523. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  524. //功能强大的音乐播放器
  525. @Preview
  526. @Component
  527. export struct LocalMusic {
  528. // 字母表
  529. @State alphaBet: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
  530. 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  531. @State alphaBetStyle: GlobalAlphabetIndexerModifier = new GlobalAlphabetIndexerModifier()
  532. @State selectAlphaBetIndex: number = 0
  533. @State isShowAlphaBet: boolean = false
  534. @State isScrolling: boolean = false
  535. @State isTouchingAlphaBet: boolean = false
  536. @State alphabetHeight: number = 0
  537. public enableShowAlphabet: boolean = true // 是否显示字母表
  538. @State isShowPrecious: boolean = false //播控条显示上一首按钮
  539. //背景两侧流光控制器
  540. @State sceneBgController: HdsSceneController|undefined = deviceInfo.sdkApiVersion>=20
  541. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  542. new HdsSceneController()
  543. .setSceneParams({
  544. backgroundMaskColors: [Color.Green, Color.Red],
  545. firstEdgeFlowLight: {
  546. startPos: 0,
  547. endPos: 0.5,
  548. color: Color.Red
  549. },
  550. secondEdgeFlowLight: {
  551. startPos: 0,
  552. endPos: -0.5,
  553. color: Color.Green
  554. }
  555. }) : undefined;
  556. //背景流光控制器
  557. @State bgController: hdsEffect.ShaderEffectController|undefined = deviceInfo.sdkApiVersion>=20
  558. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  559. new hdsEffect.ShaderEffectController():undefined;
  560. @State showAddSheet:boolean = false
  561. searchController: SearchController = new SearchController()
  562. @State rightTopImage:Resource = $r('sys.symbol.sort')
  563. @State isEditAudio:boolean = false
  564. @State isExtractAcc:boolean = false
  565. @State isConverter:boolean = false
  566. @State isAIVoiceSeparation:boolean = false
  567. @State isExtractAudio:boolean = false
  568. @State isMergeAudio:boolean = false
  569. @State isCopyFileToDownLoad: boolean = false
  570. @State isChangeTone:boolean = false
  571. @State offHeight: number = 75
  572. @State currentSongList: Array<VideoItem> = []//当前歌单
  573. @Consume currentSongListName:string //当前歌单名称
  574. @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
  575. @State isRefreshing: boolean = false;
  576. @State maxRefreshingHeight: number = 100.0;
  577. private contentNode?: ComponentContent<Object> = undefined;
  578. // WebDAV相关实例变量(现在改为从内存读取,不再需要存储)
  579. @State ratioL: number = 1;
  580. @State mediaKuCount: number = 0;
  581. @State albumCount: number = 0;
  582. @State artistCount: number = 0;
  583. @State fastForwardSeconds: string = '10'
  584. @State isShowBackFast: boolean = true//快进快退按钮
  585. @State isCanAuto:boolean = true
  586. @State opacityValueImage: number = 1;
  587. @State tipPopup:boolean = false
  588. @Consume mType: number;
  589. @StorageProp('themeColor') themeColor: string =
  590. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  591. themeMode: number = 0;
  592. @State titleName: string = '首页'
  593. @State textStr: string = ''
  594. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  595. // private download_path: string = '';
  596. @Consume rootPath: string //音频根目录
  597. @Consume currentPath: string
  598. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  599. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  600. @State lockPath: string = ''
  601. @State favPath: string = ''
  602. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  603. @State historyPath: string = ''
  604. @State historyList: Array<VideoItem> = []
  605. @Consume isHistory: boolean
  606. static readonly HISTORY_MUSIC: string = 'music_historyList';
  607. private table: MediaTable = new MediaTable(getContext(this))
  608. private playlistTable: PlaylistTable | null = null
  609. private deletionWatcher: FileDeletionWatcher | null = null
  610. @State allPlaylists: Playlist[] = []
  611. @State isZero: boolean = false
  612. @State fileList: Array<string> = []
  613. @State dirList: Array<VideoItem> = []
  614. @Consume videoLocalList:VideoItem[]
  615. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  616. @State listRefreshKey: number = 0
  617. // @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  618. @StorageProp('mediaKuList') mediaKuList: Array<VideoItem> = []; //媒体库文件
  619. @State artistList: Array<VideoItem> = []; //艺术家文件
  620. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  621. @State albumList: Array<VideoItem> = []; //专辑文件
  622. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  623. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  624. @State imageOpacities: number[] = [];
  625. @Consume isCanBack: boolean
  626. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  627. @State showSingleLyric: boolean = false
  628. @State sortType: number = 4 //默认排序方式
  629. @State isShowSimi: boolean = false //是否显示私密音频
  630. @State isShowFAV: boolean = true //是否显示我的收藏
  631. @State @Watch('onTopBarhange')isShowTitleBar: boolean = true //是否显示分类导航条
  632. @State isShowAllBar: boolean = true //是否显示播放全部条
  633. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  634. @State isShowHistory: boolean = true //是否显示最近播放
  635. @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
  636. @State isGridMusic: boolean = false //是否网格布局
  637. @State isCircleBtn: boolean = false //是否圆形播放按钮
  638. @State twoFingerType: number = 3 //双支放大缩小的类型
  639. @State isScrollHide: boolean = false //是否滚动隐藏
  640. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  641. @State isStartAutoPlay: boolean = false //启动后自动播放
  642. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  643. @State isShowHeader: boolean = true
  644. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  645. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  646. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  647. @State isSwipe: boolean = false //listItem的左滑开关
  648. @State openSkipSongAnimate: boolean = true//切歌动画效果
  649. @State customizeBgPath: string | undefined = '';
  650. @State isDarkMode: boolean = false
  651. @State lyricTextWeight: number = 400
  652. @State lyricTextWeightPip: number = 400
  653. @State currentSwiperIndex: number = 0
  654. @State blurValue: number = 0 //背景模糊
  655. @State bgBrightness: number = 0 //背景亮度
  656. private listScroller: ListScroller = new ListScroller()
  657. private playListScroller: Scroller = new Scroller()
  658. @State isOneKeyTags:boolean = false
  659. @State isFixMessy:boolean = false
  660. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  661. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  662. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  663. @StorageProp('windowWidth') windowWidth: number = 0;
  664. @StorageProp('windowHeight') windowHeight: number = 0;
  665. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  666. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  667. private UNKONWN:string = '';
  668. private listArea: Area = {
  669. width: 0,
  670. height: 0,
  671. position: {},
  672. globalPosition: {}
  673. }
  674. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  675. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  676. // WebDAV认证信息缓存(作为实例变量,比全局上下文更可靠)
  677. private currentWebDavAuthInfo: WebDavAuthItem | null = null;
  678. //瀑布流的列数横竖屏动态切换
  679. onIsLandscapeChange() {
  680. if(this.isLandscape){
  681. this.columns = 4
  682. }else{
  683. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  684. }
  685. }
  686. onColorModeChange() {
  687. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  688. }
  689. //bar导航条显示状态变化,不显示的话把topBarHeight=0
  690. onTopBarhange(){
  691. if(this.isShowTitleBar){
  692. console.log('onecold 导航条显示')
  693. this.topBarHeight = 50
  694. this.offHeight = 75
  695. }else{
  696. console.log('onecold 导航条隐藏')
  697. this.topBarHeight = 0
  698. if(this.twoFingerType!=4){
  699. this.offHeight = 30
  700. }
  701. }
  702. }
  703. //点击某个歌单id发生变化的时候回调
  704. onIDChange(){
  705. console.log('onecold 歌单id发生变化this.currentSongListID='+this.currentSongListID)
  706. console.log('onecold 歌单id发生变化this.currentSongListName='+this.currentSongListName)
  707. if(this.modeType==4){
  708. this.isShowTitleBar = false
  709. this.titleName = this.currentSongListName
  710. this.rightTopImage = $r('sys.symbol.sort')
  711. //获取缓存
  712. const cacheSongs:string =PreferencesUtil.getStringSync(this.currentSongListID+'currentSongList', '')
  713. console.log('onecold 歌单id发生变化获取缓存2 cacheSongs = '+cacheSongs)
  714. if(StrUtil.isNotEmpty(cacheSongs)){
  715. this.currentSongList = JSON.parse(cacheSongs) as VideoItem[]
  716. this.updateListData(this.currentSongList, true)
  717. }
  718. this.doSongListTask()//获取歌单信息
  719. }
  720. }
  721. async doSongListTask() {
  722. // 初始化歌单数据库
  723. const playlistTable = new PlaylistTable(this.context);
  724. // 查询歌单中的所有歌曲
  725. const playlistSongs: PlaylistSong[] = await playlistTable.queryPlaylistSongs(this.currentSongListID);
  726. console.log('onecold 歌单id发生变化获取缓存7 playlistSongs='+playlistSongs.length)
  727. if (ArrayUtil.isEmpty(playlistSongs)) {
  728. this.updateListData([], true)
  729. } else {
  730. this.currentSongList = await convertPlaylistSongsToVideoItems(this.context, playlistSongs);
  731. console.log('onecold 从数据库读取的歌曲为 playlistSongs='+this.currentSongList.length)
  732. this.updateListData(this.currentSongList, true)
  733. if (ArrayUtil.isNotEmpty(this.currentSongList)&&this.currentSongList.length > 100) {
  734. // 只保存前100条记录到缓存中
  735. let canceList = this.currentSongList.slice(0, 100);
  736. PreferencesUtil.putSync(this.currentSongListID+'currentSongList',
  737. JSON.stringify(canceList))
  738. } else {
  739. PreferencesUtil.putSync(this.currentSongListID+'currentSongList', JSON.stringify(this.currentSongList));
  740. }
  741. }
  742. this.isRefreshing = false
  743. }
  744. onModeChange() {
  745. this.isFavMusic = false
  746. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, false)
  747. switch (this.modeType) {
  748. case 0:
  749. this.getSortedFiles(this.currentPath)
  750. break
  751. case 1:
  752. this.rightTopImage = $r('sys.symbol.sort')
  753. this.updateListData(this.mediaKuList)
  754. this.titleName = Utility.resourceToString(this.context,$r('app.string.media_ku'))
  755. break
  756. case 2:
  757. this.rightTopImage = $r('sys.symbol.sort')
  758. this.updateListData(this.artistList)
  759. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  760. break
  761. case 3:
  762. this.rightTopImage = $r('sys.symbol.sort')
  763. this.updateListData(this.albumList)
  764. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  765. break
  766. }
  767. }
  768. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  769. // @StorageLink('isPlay') isPlay: boolean = false;
  770. @StorageLink('isShowPlay') isShowPlay: boolean = false;
  771. @StorageLink('songList') songList: Array<VideoItem> = [];
  772. @State translateY: number = 0;
  773. @State isShowSheet: boolean = false;
  774. @State isShowSheetView: boolean = false;
  775. @State isShowTimeCloseView: boolean = false;
  776. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  777. @StorageLink('currIndex') curIndex: number = 0;
  778. @Consume isShowDrawer: boolean;
  779. @Consume offsetX: number;
  780. @State isFac: boolean = false;
  781. @State favList: Array<VideoItem> = []
  782. @Consume isFavMusic: boolean
  783. @State isClickedPLayAll: boolean = false;
  784. private scrollerForlist: ListScroller = new ListScroller();
  785. private knockController: KnockController | undefined = undefined;
  786. // 修改为:
  787. imagesF: ImageFrameInfo[] = CommonConstants.IMAGE_FRAME_INFO;
  788. @StorageProp('animationState') animationState: AnimationStatus = AnimationStatus.Initial
  789. // 缓存机制
  790. private cache: Map<string, Array<VideoItem>> = new Map();
  791. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  792. // 持久化缓存
  793. private async saveCacheToStorage() {
  794. const cacheArray = Array.from(this.cache.entries());
  795. const stringCacheArray = Array.from(this.stringCache.entries());
  796. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  797. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  798. }
  799. // 载入缓存
  800. private async loadCacheFromStorage() {
  801. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  802. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  803. if (cacheString) {
  804. const cacheArray: [string, Array<VideoItem>][] = JSON.parse(cacheString);
  805. this.cache = new Map(cacheArray);
  806. }
  807. if (stringCacheString) {
  808. const stringCacheArray: [string, string][] = JSON.parse(stringCacheString);
  809. this.stringCache = new Map(stringCacheArray);
  810. }
  811. }
  812. // 查找缓存
  813. private findCache(key: string): Array<VideoItem> | undefined {
  814. return this.cache.get(key);
  815. }
  816. // 查找字符串缓存
  817. private findStringCache(key: string): string | undefined {
  818. return this.stringCache.get(key);
  819. }
  820. // 添加缓存
  821. private addCache(key: string, value: Array<VideoItem>) {
  822. this.cache.set(key, value);
  823. }
  824. // 添加字符串缓存
  825. private addStringCache(key: string, value: string) {
  826. this.stringCache.set(key, value);
  827. }
  828. // 删除缓存
  829. private deleteCache(key: string) {
  830. this.cache.delete(key);
  831. this.saveCacheToStorage()
  832. }
  833. // 删除字符串缓存
  834. private deleteStringCache(key: string) {
  835. this.stringCache.delete(key);
  836. }
  837. // 多选机制
  838. @State selectedFiles: Array<VideoItem> = [];
  839. @State isMultiSelect: boolean = false;
  840. @State isAllSelected: boolean = false;
  841. @State appName: string = ''
  842. @State isHasDir: boolean = false
  843. @State packName: string = ''
  844. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  845. doSwipBack() {
  846. if(this.isSearchMode){
  847. console.info('onecold doSwipBack = ' +this.isSearchMode)
  848. this.isSearchMode = false
  849. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  850. this.searchText = ''
  851. this.getSortedFiles(this.currentPath)
  852. return
  853. }
  854. this.onSearchInput('')
  855. return
  856. }
  857. this.isZero = false
  858. if (this.modeType !== 0 && this.isCanBack) {
  859. this.onModeChange()
  860. this.isCanBack = false
  861. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  862. setTimeout(() => {
  863. if (this.modeType == 2) {
  864. if (this.isGridMusic||this.twoFingerType==4) {
  865. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  866. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  867. if(this.twoFingerType==4){
  868. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  869. }else{
  870. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  871. }
  872. } else {
  873. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  874. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  875. }
  876. } else if (this.modeType == 3) {
  877. if (this.isGridMusic||this.twoFingerType==4) {
  878. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  879. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 0
  880. if(this.twoFingerType==4){
  881. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  882. }else{
  883. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  884. }
  885. } else {
  886. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  887. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  888. }
  889. }
  890. }, 200)
  891. return
  892. }
  893. if (this.isHistory || this.isFavMusic) {
  894. this.isHistory = false
  895. this.getSortedFiles(this.currentPath)
  896. return
  897. }
  898. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  899. animateTo({ duration: 555 }, () => {
  900. // 动画闭包内控制Image组件的出现和消失
  901. this.isShowDrawer = !this.isShowDrawer
  902. this.offsetX = 0
  903. })
  904. return
  905. }
  906. //返回上一级歌单的滚动位置
  907. setTimeout(() => {
  908. if (this.modeType == 0) {
  909. if (this.isGridMusic||this.twoFingerType==4) {
  910. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  911. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
  912. if(this.twoFingerType==4){
  913. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  914. }else{
  915. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  916. }
  917. } else {
  918. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  919. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  920. }
  921. }
  922. }, 300)
  923. this.currentPath = Utility.getParentDirectory(this.currentPath)
  924. Logger.info('this.currentPath2 = ' + this.currentPath)
  925. this.getSortedFiles(this.currentPath)
  926. }
  927. // 组件生命周期
  928. aboutToAppear() {
  929. console.info('onecold aboutToAppear sdkApiVersion = '+deviceInfo.sdkApiVersion)
  930. if(ArrayUtil.isNotEmpty(this.videoLocalList)&&this.modeType==0){
  931. this.updateListData(this.videoLocalList)
  932. }
  933. // 初始化 PlaylistTable
  934. this.playlistTable = new PlaylistTable(getContext(this))
  935. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  936. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  937. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  938. this.tipPopup = !this.tipPopup
  939. PreferencesUtil.putSync('isFirstTiped',false)
  940. }
  941. this.initSetting()
  942. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  943. Utility.getAppName(getContext(this)).then((appName: string) => {
  944. this.appName = appName
  945. })
  946. this.packName = AppUtil.getBundleName()
  947. this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
  948. this.loadCacheFromStorage(); // 加载文件夹缓存
  949. // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
  950. this.initLoadCache()
  951. this.mkDownLoadDir()
  952. let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
  953. // 监听广播事件(打开其他应用处理)
  954. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  955. this.saveVideoDatas([eventData.data?.message], true)
  956. });
  957. //侧滑广播接收时间
  958. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
  959. // 监听广播事件(打开其他应用处理)
  960. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  961. animateTo({ duration: 555 }, () => {
  962. this.doSwipBack()
  963. })
  964. });
  965. //ScanFilePage广播接收时间
  966. let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
  967. // 监听ScanFilePage广播事件(更新数据库)
  968. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  969. this.doUpdateData()
  970. });
  971. // 监听歌单播放请求事件
  972. let eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY }
  973. emitter.on(eventPlaylistPlay, async (eventData: emitter.EventData) => {
  974. const data = eventData.data as Record<string, Object>
  975. if (!data) {
  976. Logger.error('heanup eventPlaylistPlay: eventData.data is undefined or null')
  977. return
  978. }
  979. // 检查歌单播放数据结构
  980. if (data.playlistId && data.songFilePaths && data.startIndex !== undefined) {
  981. const playlistData: PlaylistEventData = {
  982. playlistId: data.playlistId as string,
  983. playlistName: data.playlistName as string,
  984. songCount: data.songCount as number,
  985. startIndex: data.startIndex as number,
  986. songFilePaths: data.songFilePaths as string[]
  987. }
  988. await this.handlePlaylistPlayRequest(
  989. playlistData.playlistId,
  990. playlistData.playlistName,
  991. playlistData.songFilePaths,
  992. playlistData.startIndex
  993. )
  994. return
  995. }
  996. Logger.error('heanup eventPlaylistPlay: 接收到无效的数据结构')
  997. });
  998. let eventRefreshSort: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_REFRESH_SORT }
  999. // 监听广播事件(通用设置配置更新)
  1000. emitter.on(eventRefreshSort, (eventData: emitter.EventData) => {
  1001. if(this.modeType ==4){
  1002. this.doSongListTask()//获取歌单信息
  1003. }
  1004. });
  1005. let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
  1006. // 监听广播事件(通用设置配置更新)
  1007. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  1008. this.doChangeSetting()
  1009. });
  1010. let event: Callback<InterruptEvent> = (event) => {
  1011. // LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  1012. console.info(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  1013. this.savePlaybackPosition()
  1014. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  1015. this.pause();
  1016. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  1017. console.info(`onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  1018. console.info('onecold startPlayOrResumePlay 514')
  1019. this.startPlayOrResumePlay();
  1020. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  1021. this.stop();
  1022. }
  1023. }
  1024. this.mIjkMediaPlayer.on('audioInterrupt', event);
  1025. // 音频设备断连回调处理
  1026. // let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  1027. // LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  1028. // if (event.reason === DeviceChangeReason.REASON_NEW_DEVICE_AVAILABLE) { // 音频设备连接
  1029. //
  1030. // } else if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  1031. // this.pause();
  1032. // }
  1033. // }
  1034. // // 订阅音频设备断开和连接事件
  1035. // this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  1036. const eventPause: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_PAUSE }
  1037. // 监听广播事件(hicar断开暂停播放)
  1038. emitter.on(eventPause, (eventData: emitter.EventData) => {
  1039. this.pause();
  1040. });
  1041. this.makeWorker()
  1042. //折叠屏的屏幕显示模式变化
  1043. display.on('foldDisplayModeChange', (data) => {
  1044. this.doChangeBarHeight()
  1045. });
  1046. display.on('foldStatusChange', (data) => {
  1047. Logger.info('onecold foldStatusChange ')
  1048. });
  1049. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  1050. // 读取 themeMode 并同步 currentColorMode
  1051. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  1052. this.applyThemeMode(this.themeMode)
  1053. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  1054. AppStorage.setOrCreate('themeColor', themeColor);
  1055. this.themeColor = themeColor;
  1056. this.doChangeSetting()
  1057. this.windowClass.on('windowSizeChange', (size) => {
  1058. LogUtil.info('onecold windowSizeChange')
  1059. this.doChangeBarHeight()
  1060. let viewWidth = px2vp(size.width);
  1061. let viewHeight = px2vp(size.height);
  1062. if(this.isPhoneLan()){
  1063. this.is_auto_hide_progress = false
  1064. if(this.isHiCar()){
  1065. return
  1066. }
  1067. setTimeout(() => {
  1068. this.is_auto_hide_progress = true
  1069. }, 6000)
  1070. }else{
  1071. this.startAutoHide()
  1072. }
  1073. });
  1074. this.eventHub.on('onStateChange', (fg: boolean) => {
  1075. if (fg && this.curState === 'STARTED') {
  1076. this.stopPip();
  1077. }
  1078. });
  1079. }
  1080. //载入媒体库,艺术家,专辑等缓存
  1081. initLoadCache(){
  1082. this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
  1083. this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
  1084. this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
  1085. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  1086. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  1087. if(ArrayUtil.isNotEmpty(cachedList)){
  1088. this.mediaKuList = cachedList
  1089. if(this.modeType==1){
  1090. this.updateListData(this.mediaKuList)
  1091. }
  1092. }
  1093. let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
  1094. let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
  1095. if(ArrayUtil.isNotEmpty(artistCachedList)){
  1096. this.artistList = artistCachedList
  1097. let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
  1098. const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
  1099. this.artistMap = new Map(parsedArray);
  1100. // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
  1101. if(this.modeType==2){
  1102. this.updateListData(this.artistList)
  1103. }
  1104. }
  1105. let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
  1106. let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
  1107. if(ArrayUtil.isNotEmpty(albumCachedList)){
  1108. this.albumList = albumCachedList
  1109. let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
  1110. const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
  1111. this.albumMap = new Map(parsedArray);
  1112. if(this.modeType==3){
  1113. this.updateListData(this.albumList)
  1114. }
  1115. }
  1116. }
  1117. startAutoHide() {
  1118. if(this.isHiCar()){
  1119. return
  1120. }
  1121. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  1122. console.info('onecold startAutoHide')
  1123. this.is_auto_hide_progress = false
  1124. setTimeout(() => {
  1125. this.is_auto_hide_progress = true
  1126. }, 6000)
  1127. }
  1128. }
  1129. applyThemeMode(mode: number) {
  1130. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  1131. if (mode === 1) {
  1132. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  1133. } else if (mode === 2) {
  1134. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1135. }
  1136. AppStorage.setOrCreate('currentColorMode', colorMode)
  1137. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  1138. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  1139. AppStorage.setOrCreate('themeMode', mode)
  1140. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1141. // 只有强制浅色/深色时才主动设置
  1142. const context = getContext(this) as common.UIAbilityContext
  1143. context.getApplicationContext().setColorMode(colorMode)
  1144. }
  1145. initSetting() {
  1146. this.isShowPrecious = PreferencesUtil.getBooleanSync('isShowPrecious', false)
  1147. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1148. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  1149. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  1150. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, false)
  1151. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  1152. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  1153. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  1154. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  1155. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  1156. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  1157. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  1158. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, false)
  1159. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  1160. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 2)
  1161. this.isCoverTop = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP, true)
  1162. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  1163. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  1164. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  1165. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  1166. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  1167. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  1168. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  1169. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  1170. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  1171. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  1172. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  1173. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  1174. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  1175. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  1176. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  1177. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  1178. this.isCopyFileToDownLoad = PreferencesUtil.getBooleanSync(SettingPage.IS_COPYFILE_TO_DOWNLOAD, false)
  1179. if(this.volumeSmall){
  1180. this.volume = 0.5
  1181. }else{
  1182. this.volume = 1
  1183. }
  1184. //如果是hicar连接状态,这些都是false
  1185. if(this.isHiCar()){
  1186. this.isShowTitleBar = false//不显示导航栏
  1187. this.columns=4
  1188. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  1189. {
  1190. this.isShowHeader = false//二级菜单不显示头部
  1191. this.isGridMusic= false//用list不用网格
  1192. this.isCoverTopBig = false
  1193. }
  1194. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  1195. }
  1196. if (this.isSavePlayMode) {
  1197. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  1198. }
  1199. }
  1200. doChangeSetting() {
  1201. this.initSetting()
  1202. this.deleteCache(this.currentPath)
  1203. if (this.modeType === 0) {
  1204. this.getSortedFiles(this.currentPath)
  1205. }
  1206. }
  1207. doChangeBarHeight() {
  1208. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  1209. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  1210. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  1211. this.setBarHeightNormal()
  1212. }
  1213. }
  1214. onPageShow() {
  1215. this.knockController?.immersiveListening();
  1216. app.setImageCacheCount(100);
  1217. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  1218. app.setImageRawDataCacheSize(104857600);
  1219. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  1220. }
  1221. //开启线程查看各个数据库
  1222. makeWorker() {
  1223. setTimeout(() => {
  1224. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  1225. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  1226. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  1227. // workerInstance.postMessage({
  1228. // code: 1,
  1229. // data1: this.context,
  1230. // data2: this.rootPath,
  1231. // data3: this.lockPath,
  1232. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1233. // data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  1234. // });
  1235. PreferencesUtil.putSync('isFirstApp', false)
  1236. } else {
  1237. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1238. workerInstance.postMessage({ code: 3, data: this.context });
  1239. workerInstance.postMessage({ code: 4, data: this.context });
  1240. this.getHistoryList(false)
  1241. }
  1242. }, 1000)
  1243. workerInstance.onmessage = (e: MessageEvents): void => {
  1244. switch (e.data.code) {
  1245. case 101: //第一次扫描文件夹入库
  1246. ToastUtil.showToast('刷新同步数据库成功!')
  1247. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  1248. this.doAllUpdateData()
  1249. break;
  1250. case 102: //查询媒体库列表
  1251. this.isRefreshing = false
  1252. this.mediaKuList = e.data.data
  1253. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  1254. Utility.doSortListAscending(this.mediaKuList)
  1255. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  1256. if (this.modeType === 1) {
  1257. this.updateListData(this.mediaKuList)
  1258. }
  1259. PreferencesUtil.putSync('mediaKuCount', this.mediaKuList.length)
  1260. // 处理媒体库前100条记录,列表长度并存储到PreferencesUtil
  1261. if (ArrayUtil.isNotEmpty(this.mediaKuList)&&this.mediaKuList.length > 100) {
  1262. // 只保存前100条记录到缓存中
  1263. let truncatedList = this.mediaKuList.slice(0, 100);
  1264. PreferencesUtil.putSync('mediaKuList', JSON.stringify(truncatedList));
  1265. } else {
  1266. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  1267. }
  1268. break;
  1269. case 103: //收到查询艺术家列表
  1270. this.isRefreshing = false
  1271. this.artistMap = e.data.data1;
  1272. this.artistList = e.data.data2;
  1273. PreferencesUtil.putSync('artistCount', this.artistList.length)
  1274. // 处理艺术家前100条记录,列表长度并存储到PreferencesUtil
  1275. if (ArrayUtil.isNotEmpty(this.artistList)&&this.artistList.length > 100) {
  1276. // 只保存前100条记录到缓存中
  1277. let truncatedList = this.artistList.slice(0, 100);
  1278. PreferencesUtil.putSync('artistList', JSON.stringify(truncatedList));
  1279. } else {
  1280. PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
  1281. }
  1282. // 处理并缓存前60条艺术家数据
  1283. const sortedEntries = Array.from(this.artistMap.entries())
  1284. .sort((a, b) => b[1].length - a[1].length)
  1285. .slice(0, 60);
  1286. PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
  1287. break;
  1288. case 104: //收到查询专辑列表
  1289. this.isRefreshing = false
  1290. this.albumMap = e.data.data1;
  1291. this.albumList = e.data.data2
  1292. //查询完毕在启动是否自动播放
  1293. if (this.isStartAutoPlay&&this.isCanAuto) {
  1294. this.isCanAuto = false
  1295. console.info('onecold startPlayOrResumePlay 757')
  1296. this.startPlayOrResumePlay()
  1297. }
  1298. PreferencesUtil.putSync('albumCount', this.albumList.length)
  1299. // 处理专辑前100条记录,列表长度并存储到PreferencesUtil
  1300. if (ArrayUtil.isNotEmpty(this.albumList)&&this.albumList.length > 100) {
  1301. // 只保存前100条记录到缓存中
  1302. let truncatedList = this.albumList.slice(0, 100);
  1303. PreferencesUtil.putSync('albumList', JSON.stringify(truncatedList));
  1304. } else {
  1305. PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
  1306. }
  1307. const mapArrayAlbum = Array.from(this.albumMap.entries())
  1308. .sort((a, b) => b[1].length - a[1].length)
  1309. .slice(0, 60);
  1310. PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
  1311. break;
  1312. case 105: // 缓存完成后返回的元数据
  1313. this.handleWorkerMetadataPayload(e.data.data as WorkerMetadataPayload);
  1314. break;
  1315. case 106: // 编辑音乐元数据和封面完成
  1316. this.handleEditMusicResult(e.data);
  1317. break;
  1318. }
  1319. };
  1320. // 在调用terminate后,执行onexit
  1321. workerInstance.onexit = (code) => {
  1322. metadataExtractionInFlight.clear();
  1323. Logger.info(TAG, 'workerInstance 线程已退出,code: ' + code);
  1324. }
  1325. workerInstance.onerror = (err: ErrorEvent) => {
  1326. metadataExtractionInFlight.clear();
  1327. console.error('workerInstance 线程执行发生异常: ' + err.message)
  1328. }
  1329. }
  1330. private handleWorkerMetadataPayload(payload: WorkerMetadataPayload | undefined): void {
  1331. if (!payload || !payload.originFilePath) {
  1332. return;
  1333. }
  1334. metadataExtractionInFlight.delete(payload.originFilePath);
  1335. if (payload.error) {
  1336. Logger.warn(TAG, `缓存文件元数据解析失败: ${payload.error}`);
  1337. return;
  1338. }
  1339. this.applyMetadataToCollections(payload.originFilePath, payload);
  1340. }
  1341. private applyMetadataToCollections(filePath: string, payload: WorkerMetadataPayload): void {
  1342. const targets: Array<VideoItem> = [];
  1343. if (this.currentSong && this.currentSong.filePath === filePath) {
  1344. targets.push(this.currentSong);
  1345. }
  1346. const collectFromList = (list?: Array<VideoItem>) => {
  1347. if (!list || list.length === 0) {
  1348. return;
  1349. }
  1350. const found = Utility.getItemByFilePath(list, filePath);
  1351. if (found) {
  1352. targets.push(found);
  1353. }
  1354. };
  1355. collectFromList(this.songList);
  1356. collectFromList(this.videoLocalList);
  1357. collectFromList(this.historyList);
  1358. collectFromList(this.favList);
  1359. const remoteManager = RemoteDriveManager.getInstance();
  1360. collectFromList(remoteManager.webDavSongs);
  1361. const updated = new Set<VideoItem>();
  1362. const webDavUpdates: Map<string, WebDavMetadataUpdatePayload> = new Map();
  1363. for (let i = 0; i < targets.length; i++) {
  1364. const target = targets[i];
  1365. if (!target || updated.has(target)) {
  1366. continue;
  1367. }
  1368. updated.add(target);
  1369. this.mergeVideoItemWithPayload(target, payload);
  1370. if (target.type === CommonConstants.TYPE_WEBDAV && StrUtil.isNotEmpty(target.filePath)) {
  1371. webDavUpdates.set(target.filePath, {
  1372. filePath: target.filePath,
  1373. pixelMapPath: target.pixelMapPath,
  1374. name: target.name,
  1375. artist: target.artist
  1376. });
  1377. }
  1378. }
  1379. if (this.currentSong && this.currentSong.filePath === filePath) {
  1380. this.mergeVideoItemWithPayload(this.currentSong, payload);
  1381. if (payload.name) {
  1382. this.name = payload.name;
  1383. }
  1384. if (payload.artist) {
  1385. this.artist = payload.artist;
  1386. }
  1387. if (payload.pixelMapPath) {
  1388. this.cover = payload.pixelMapPath;
  1389. }
  1390. if (payload.lyricContent) {
  1391. this.applyInlineLyricContent(payload.lyricContent);
  1392. }
  1393. this.currentSong = cloneVideoItem(this.currentSong);
  1394. AppStorage.setOrCreate('currentSong', this.currentSong);
  1395. }
  1396. const primaryTarget = targets.length > 0 ? targets[0] : undefined;
  1397. if (primaryTarget) {
  1398. this.persistRemoteMetadataToDb(primaryTarget).catch((error: Error) => {
  1399. Logger.error(TAG, `缓存元数据持久化失败: ${error.message}`);
  1400. });
  1401. }
  1402. if (webDavUpdates.size > 0) {
  1403. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  1404. emitter.emit(eventUpdate, { data: Array.from(webDavUpdates.values()) });
  1405. }
  1406. }
  1407. private handleEditMusicResult(result: WorkerEditMusicResult): void {
  1408. // 关闭进度条
  1409. DialogHelper.closeLoading();
  1410. if (result.success) {
  1411. console.log("heanup 编辑信息成功,数据库已同步");
  1412. if (result.coverResult) {
  1413. ToastUtil.showToast('内嵌封面成功');
  1414. }
  1415. ToastUtil.showToast('内嵌音乐标签成功');
  1416. this.isShowMoreView = false;
  1417. this.name = this.titleStr;
  1418. // 同步当前播放的歌曲信息
  1419. if (this.editingItem && this.editingItem.filePath == this.currentSong?.filePath) {
  1420. this.currentSong.name = this.titleStr;
  1421. this.artist = this.artistStr;
  1422. this.currentSong.artist = this.artistStr;
  1423. this.currentSong.album = this.ablumStr;
  1424. this.currentSong.year = this.yearStr;
  1425. this.currentSong.genre = this.genreStr;
  1426. this.currentSong.track = this.trackStr;
  1427. this.currentSong.lyricContent = this.lyricConStr;
  1428. this.currentSong.ALBUMARTIST = this.albumArtistStr;
  1429. this.currentSong.COMPOSER = this.composerStr;
  1430. this.currentSong.LYRICIST = this.lyricistStr;
  1431. this.currentSong.COMMENT = this.commentStr;
  1432. }
  1433. // if (result.needRefreshList && this.modeType == 0) {
  1434. // this.deleteCache(this.currentPath);
  1435. // this.getSortedFiles(this.currentPath);
  1436. // }
  1437. // 同步编辑字段到本地列表
  1438. if (this.editingItem) {
  1439. this.syncEditedFields(this.editingItem);
  1440. this.syncListsAfterEdit(this.editingItem.filePath);
  1441. this.doUpateEditedFields(this.editingItem);
  1442. }
  1443. // 清理临时变量
  1444. this.longItemFilePath = '';
  1445. this.tempLyricContent = '';
  1446. this.isShowEdit = false;
  1447. this.imagePathStr = '';
  1448. } else {
  1449. console.error("heanup 编辑信息失败: " + result.error);
  1450. ToastUtil.showToast('编辑失败: ' + (result.error || '未知错误'));
  1451. // 清理临时变量
  1452. this.longItemFilePath = '';
  1453. this.tempLyricContent = '';
  1454. this.isShowEdit = false;
  1455. this.imagePathStr = '';
  1456. }
  1457. }
  1458. private assignStringMetadata(target: VideoItem, key: keyof VideoItem, value?: string | null, allowEmpty = false): void {
  1459. if (value === undefined || value === null) {
  1460. return;
  1461. }
  1462. const text = value.toString();
  1463. if (!allowEmpty && text.trim().length === 0) {
  1464. return;
  1465. }
  1466. Reflect.set(target, key as string, value);
  1467. }
  1468. private assignNumberMetadata(target: VideoItem, key: keyof VideoItem, value?: number | null): void {
  1469. if (value === undefined || value === null || Number.isNaN(value)) {
  1470. return;
  1471. }
  1472. Reflect.set(target, key as string, value);
  1473. }
  1474. private mergeVideoItemWithPayload(target: VideoItem, payload: WorkerMetadataPayload): void {
  1475. if (!target || !payload) {
  1476. return;
  1477. }
  1478. this.assignStringMetadata(target, 'name', payload.name);
  1479. this.assignStringMetadata(target, 'artist', payload.artist);
  1480. this.assignStringMetadata(target, 'album', payload.album);
  1481. this.assignStringMetadata(target, 'bit_rate', payload.bit_rate);
  1482. this.assignStringMetadata(target, 'duration', payload.duration);
  1483. this.assignStringMetadata(target, 'sampleRate', payload.sampleRate);
  1484. this.assignStringMetadata(target, 'mimeType', payload.mimeType);
  1485. this.assignStringMetadata(target, 'size', payload.size);
  1486. this.assignStringMetadata(target, 'pixelMapPath', payload.pixelMapPath);
  1487. this.assignStringMetadata(target, 'lyricContent', payload.lyricContent, true);
  1488. this.assignStringMetadata(target, 'genre', payload.genre);
  1489. this.assignStringMetadata(target, 'track', payload.track);
  1490. this.assignStringMetadata(target, 'bits_per_raw_sample', payload.bits_per_raw_sample);
  1491. this.assignStringMetadata(target, 'channels', payload.channels);
  1492. this.assignStringMetadata(target, 'channel_layout', payload.channel_layout);
  1493. this.assignStringMetadata(target, 'start_time', payload.start_time);
  1494. this.assignStringMetadata(target, 'year', payload.year);
  1495. this.assignStringMetadata(target, 'disc', payload.disc);
  1496. this.assignStringMetadata(target, 'ALBUMARTIST', payload.ALBUMARTIST);
  1497. this.assignStringMetadata(target, 'COMPOSER', payload.COMPOSER);
  1498. this.assignStringMetadata(target, 'LYRICIST', payload.LYRICIST);
  1499. this.assignStringMetadata(target, 'COMMENT', payload.COMMENT, true);
  1500. this.assignNumberMetadata(target, 'videoSize', payload.videoSize);
  1501. this.assignNumberMetadata(target, 'probe_score', payload.probe_score);
  1502. this.assignNumberMetadata(target, 'nb_streams', payload.nb_streams);
  1503. this.assignNumberMetadata(target, 'nb_programs', payload.nb_programs);
  1504. }
  1505. private mergeVideoItemFromSource(target: VideoItem, source: VideoItem): void {
  1506. if (!target || !source) {
  1507. return;
  1508. }
  1509. this.assignStringMetadata(target, 'name', source.name);
  1510. this.assignStringMetadata(target, 'artist', source.artist);
  1511. this.assignStringMetadata(target, 'album', source.album);
  1512. this.assignStringMetadata(target, 'bit_rate', source.bit_rate);
  1513. this.assignStringMetadata(target, 'duration', source.duration);
  1514. this.assignStringMetadata(target, 'sampleRate', source.sampleRate);
  1515. this.assignStringMetadata(target, 'trackCount', source.trackCount);
  1516. this.assignStringMetadata(target, 'mimeType', source.mimeType);
  1517. this.assignStringMetadata(target, 'size', source.size);
  1518. this.assignStringMetadata(target, 'pixelMapPath', source.pixelMapPath);
  1519. this.assignStringMetadata(target, 'lyricContent', source.lyricContent, true);
  1520. this.assignStringMetadata(target, 'genre', source.genre);
  1521. this.assignStringMetadata(target, 'track', source.track);
  1522. this.assignStringMetadata(target, 'bits_per_raw_sample', source.bits_per_raw_sample);
  1523. this.assignStringMetadata(target, 'channels', source.channels);
  1524. this.assignStringMetadata(target, 'channel_layout', source.channel_layout);
  1525. this.assignStringMetadata(target, 'start_time', source.start_time);
  1526. this.assignStringMetadata(target, 'year', source.year);
  1527. this.assignStringMetadata(target, 'disc', source.disc);
  1528. this.assignStringMetadata(target, 'ALBUMARTIST', source.ALBUMARTIST);
  1529. this.assignStringMetadata(target, 'COMPOSER', source.COMPOSER);
  1530. this.assignStringMetadata(target, 'LYRICIST', source.LYRICIST);
  1531. this.assignStringMetadata(target, 'COMMENT', source.COMMENT, true);
  1532. this.assignNumberMetadata(target, 'videoSize', source.videoSize);
  1533. this.assignNumberMetadata(target, 'probe_score', source.probe_score);
  1534. this.assignNumberMetadata(target, 'nb_streams', source.nb_streams);
  1535. this.assignNumberMetadata(target, 'nb_programs', source.nb_programs);
  1536. if (source.remote_rel_path && StrUtil.isEmpty(target.remote_rel_path)) {
  1537. target.remote_rel_path = source.remote_rel_path;
  1538. }
  1539. }
  1540. private async hydrateRemoteSongFromDb(item: VideoItem | undefined): Promise<void> {
  1541. if (!item || !isRemoteCloudType(item.type)) {
  1542. return;
  1543. }
  1544. const storagePath = item.remote_rel_path || WebDavUrlUtil.toStoragePath(item.filePath);
  1545. if (!storagePath) {
  1546. return;
  1547. }
  1548. try {
  1549. const cached = await this.table.queryVideoByFilePath(storagePath);
  1550. if (!cached) {
  1551. return;
  1552. }
  1553. this.mergeVideoItemFromSource(item, cached);
  1554. if (StrUtil.isEmpty(item.remote_rel_path)) {
  1555. item.remote_rel_path = storagePath;
  1556. }
  1557. if (item === this.currentSong) {
  1558. if (StrUtil.isNotEmpty(item.name)) {
  1559. this.name = item.name;
  1560. }
  1561. if (StrUtil.isNotEmpty(item.artist)) {
  1562. this.artist = item.artist!;
  1563. }
  1564. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  1565. this.cover = item.pixelMapPath!;
  1566. }
  1567. if (StrUtil.isNotEmpty(item.lyricContent) && StrUtil.isEmpty(this.lyricContent)) {
  1568. this.applyInlineLyricContent(item.lyricContent as string);
  1569. }
  1570. }
  1571. } catch (error) {
  1572. Logger.error(TAG, `hydrateRemoteSongFromDb 失败: ${(error as Error).message}`);
  1573. }
  1574. }
  1575. private applyInlineLyricContent(content: string): void {
  1576. if (StrUtil.isEmpty(content)) {
  1577. return;
  1578. }
  1579. this.lyricContent = content;
  1580. const lines = content.split('\n').map(line => line.trim());
  1581. const lyric = this.parser.parse(lines);
  1582. this.lyricController.setLyric(lyric);
  1583. this.lyricControllerXF.setLyric(lyric);
  1584. this.lyricControllerSingle.setLyric(lyric);
  1585. }
  1586. private extractParentPathFromStoragePath(path: string): string {
  1587. if (!path) {
  1588. return '';
  1589. }
  1590. const lastSlash = path.lastIndexOf('/');
  1591. if (lastSlash <= 0) {
  1592. return '';
  1593. }
  1594. return path.substring(0, lastSlash);
  1595. }
  1596. private async persistRemoteMetadataToDb(target: VideoItem): Promise<void> {
  1597. if (!this.context || !target || !isWebDavType(target.type)) {
  1598. return;
  1599. }
  1600. const storagePath = target.remote_rel_path || WebDavUrlUtil.toStoragePath(target.filePath);
  1601. if (!storagePath) {
  1602. return;
  1603. }
  1604. target.remote_rel_path = target.remote_rel_path || storagePath;
  1605. const table = new MediaTable(this.context);
  1606. await new Promise<void>((resolve) => {
  1607. table.getRdbStore(this.context as Context, () => resolve());
  1608. });
  1609. const cloneItem = cloneVideoItem(target);
  1610. cloneItem.filePath = storagePath;
  1611. cloneItem.remote_rel_path = storagePath;
  1612. cloneItem.parentPath = this.extractParentPathFromStoragePath(storagePath);
  1613. await table.saveOrUpdateWebDavItem(cloneItem);
  1614. }
  1615. onPageHide(): void {
  1616. this.knockController?.immersiveDisableListening();
  1617. }
  1618. @State isFirstStartPlay: boolean = false
  1619. private async startFileDeletionWatcher(): Promise<void> {
  1620. if (!this.rootPath) {
  1621. return;
  1622. }
  1623. if (!this.deletionWatcher) {
  1624. this.deletionWatcher = new FileDeletionWatcher(this.context, this.table);
  1625. }
  1626. try {
  1627. await this.deletionWatcher.watchDirectories([
  1628. this.rootPath,
  1629. this.lockPath,
  1630. this.favPath,
  1631. this.historyPath
  1632. ]);
  1633. } catch (error) {
  1634. Logger.error(TAG, `初始化文件删除监听失败: ${(error as Error).message}`);
  1635. }
  1636. }
  1637. //获取download_path
  1638. async mkDownLoadDir() {
  1639. const documentViewPicker = new picker.DocumentViewPicker()
  1640. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  1641. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  1642. PreferencesUtil.putSync('download_path', this.rootPath+'/')
  1643. this.currentPath = this.rootPath
  1644. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  1645. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  1646. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  1647. Logger.info('onecold rootPath = ' + this.rootPath)
  1648. Logger.info('onecold lockPath = ' + this.lockPath)
  1649. if (!FileUtil.accessSync(this.lockPath)) {
  1650. FileUtil.mkdirSync(this.lockPath)
  1651. }
  1652. if (!FileUtil.accessSync(this.favPath)) {
  1653. FileUtil.mkdirSync(this.favPath)
  1654. }
  1655. if (!FileUtil.accessSync(this.historyPath)) {
  1656. FileUtil.mkdirSync(this.historyPath)
  1657. }
  1658. // await this.startFileDeletionWatcher();
  1659. this.getSortedFiles(this.rootPath).then(async () => {
  1660. this.isFavMusic = false
  1661. //穿山甲
  1662. // this.loadBannerAd(CSJUtil.getBannerID())
  1663. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  1664. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  1665. if (ArrayUtil.isEmpty(this.songList)) {
  1666. this.songList = this.getCurFileList()
  1667. } else {
  1668. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  1669. }
  1670. if (ArrayUtil.isNotEmpty(this.songList)) {
  1671. this.isFirstStartPlay = true
  1672. this.sonDataSource.pushArrayData(this.songList)
  1673. if (this.currentSong === undefined) {
  1674. this.isFirstStartPlay = false
  1675. this.currentSong = this.songList[0]
  1676. }
  1677. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  1678. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  1679. context: this.context,
  1680. autoParseMusicName: this.autoParseMusicName
  1681. });
  1682. Logger.info(TAG, `WebDAV URL同步构建完成: ${this.videoUrl}`);
  1683. this.name = this.currentSong.name
  1684. this.cover = this.currentSong.pixelMapPath
  1685. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  1686. } else {
  1687. this.name = '空空如也'
  1688. }
  1689. })
  1690. this.getFavList(false)
  1691. }
  1692. getFavList(isFavRefresh: boolean) {
  1693. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  1694. this.favList = result
  1695. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  1696. this.videoLocalList = this.favList
  1697. this.updateListData(this.videoLocalList)
  1698. }
  1699. })
  1700. }
  1701. getHistoryList(isRefresh: boolean) {
  1702. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  1703. this.historyList = result
  1704. // for (let i = 0; i < this.historyList.length; i++) {
  1705. //
  1706. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  1707. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  1708. // }
  1709. if (isRefresh) {
  1710. this.videoLocalList = this.historyList
  1711. this.updateListData(this.videoLocalList, true)
  1712. }
  1713. })
  1714. }
  1715. // 组件消失生命周期
  1716. aboutToDisappear() {
  1717. console.info('LifeCycleComponent aboutToDisappear');
  1718. this.deletionWatcher?.stop();
  1719. this.knockController?.immersiveDisableListening();
  1720. this.curIndex = 0
  1721. emitter.off(EventConstants.EVENT_AUDIO_OPEN);
  1722. emitter.off(EventConstants.EVENT_SCAN_UPDATE);
  1723. emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
  1724. emitter.off(EventConstants.EVENT_SETTING_UPDATE);
  1725. this.mDestroyPage = true;
  1726. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  1727. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  1728. this.stop();
  1729. }
  1730. this.mIjkMediaPlayer.off('audioInterrupt');
  1731. if (workerInstance) {
  1732. workerInstance.terminate();
  1733. }
  1734. this.stopPip();
  1735. this.destroyPipController()
  1736. }
  1737. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean,openItem?:VideoItem) {
  1738. this.isFavMusic = false
  1739. console.info('onecold getSortedFiles 1 curPath '+curPath)
  1740. if (isWorkerPost) {
  1741. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1742. }
  1743. if (this.modeType !== 0) {
  1744. return
  1745. }
  1746. console.info('onecold getSortedFiles 2')
  1747. this.isCanBack = false
  1748. this.currentPath = curPath
  1749. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  1750. this.titleName = getFileDirName(this.currentPath,this.rootPath)
  1751. if (curPath === this.rootPath) {
  1752. this.rightTopImage = $r('sys.symbol.sort')
  1753. } else {
  1754. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  1755. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  1756. this.rightTopImage = $r('sys.symbol.chevron_left')
  1757. }
  1758. }
  1759. // Get the current file list and calculate its hash
  1760. this.fileList = FileUtil.listFileSync(curPath);
  1761. const currentHash = simpleHash(this.fileList);
  1762. // Check cache
  1763. const cachedValue = this.findCache(curPath);
  1764. Logger.info('onecold cachedValue = ' + cachedValue)
  1765. const cachedHash = this.findStringCache(curPath + '_hash');
  1766. const cachedDirList = this.findCache(curPath + "_dirList");
  1767. if (cachedValue !== undefined&&!this.isRefreshing) {
  1768. // this.videoLocalList = cachedValue;
  1769. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  1770. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  1771. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  1772. }
  1773. this.isRefreshing = false
  1774. this.updateListData(cachedValue)
  1775. }
  1776. if (cachedDirList !== undefined) {
  1777. this.dirList = cachedDirList
  1778. }
  1779. //通过当前hash值和缓存hash判断list有没有变化
  1780. if (cachedValue && cachedHash === currentHash) {
  1781. return;
  1782. }
  1783. this.fileList = FileUtil.listFileSync(curPath)
  1784. let directories: Array<VideoItem> = [];
  1785. let files: Array<VideoItem> = [];
  1786. for (let i = 0; i < this.fileList.length; i++) {
  1787. console.info(`The name of file: ${this.fileList[i]}`);
  1788. let path = curPath + '/' + this.fileList[i]
  1789. if (FileUtil.isDirectory(path)) {
  1790. let item: VideoItem =
  1791. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  1792. '')
  1793. if (this.isShowDir(item.name)) {
  1794. directories.push(item);
  1795. }
  1796. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1797. // Utility.doSortListAscending(directories)
  1798. } else {
  1799. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  1800. let item: VideoItem =
  1801. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  1802. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  1803. files.push(item);
  1804. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1805. // this.doSortListAscending(files)
  1806. }
  1807. }
  1808. }
  1809. }
  1810. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  1811. if (this.currentPath !== this.lockPath) {
  1812. files = result;
  1813. }
  1814. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1815. Utility.doSortListAscending(files)
  1816. if (this.currentPath === this.rootPath) {
  1817. this.dirList = directories
  1818. this.addCache(curPath + "_dirList", this.dirList);
  1819. }
  1820. //插入广告先注释掉
  1821. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  1822. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  1823. // directories.push(adItem)
  1824. // }
  1825. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  1826. this.videoLocalList = directories.concat(files);
  1827. this.updateListData(this.videoLocalList)
  1828. if (ArrayUtil.isNotEmpty(files)) {
  1829. if (this.currentPath != this.rootPath) {
  1830. if (files) {
  1831. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  1832. }
  1833. }
  1834. // 缓存结果
  1835. this.addCache(curPath, this.videoLocalList);
  1836. await this.saveCacheToStorage(); // 保存缓存至本地存储
  1837. this.addStringCache(curPath + '_hash', currentHash);
  1838. }
  1839. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  1840. for (let i = 0; i < this.videoLocalList.length; i++) {
  1841. console.info(`onecold gengxin 1: ${this.videoLocalList[i].name}`);
  1842. }
  1843. // this.setButtonStatus()
  1844. this.openMusic(isOpen, destPath,openItem)
  1845. this.isRefreshing = false
  1846. });
  1847. }
  1848. //第三方app打开天天静听导入音乐后播放
  1849. openMusic(isOpen?: boolean, destPath?: string,openItem?:VideoItem){
  1850. if (isOpen&&destPath) {
  1851. if (destPath === undefined) {
  1852. // 处理 destPath 为 undefined 的情况
  1853. return
  1854. }
  1855. if (destPath.endsWith('.lrc')) {
  1856. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  1857. if (StrUtil.isNotEmpty(this.videoUrl)) {
  1858. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  1859. this.initLyric(lyricPath);
  1860. }
  1861. return
  1862. }
  1863. if(openItem){
  1864. this.doPlay(openItem,0,false,true)
  1865. // this.isShowPlay = true
  1866. this.setShowPlayTrue()
  1867. }
  1868. }
  1869. }
  1870. //扫描文件夹入库
  1871. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  1872. const files = FileUtil.listFileSync(curPath);
  1873. let mediaItems: VideoItem[] = [];
  1874. Logger.info('onecold scanDirectory start ')
  1875. for (const file of files) {
  1876. const fPath = `${curPath}/${file}`;
  1877. if (fPath === this.lockPath) {
  1878. Logger.info(`Skipping locked path: ${fPath}`);
  1879. continue;
  1880. }
  1881. if (FileUtil.isDirectory(fPath)) {
  1882. // Recursively scan subdirectories
  1883. const subDirItems = await this.scanDirectory(fPath);
  1884. mediaItems = mediaItems.concat(subDirItems);
  1885. } else {
  1886. Logger.info('onecold scanDirectory filePath = ' + fPath)
  1887. // Process media files
  1888. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  1889. let mediaItem: VideoItem =
  1890. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1891. mediaItems.push(mediaItem);
  1892. this.table.insert(mediaItem, (id: number) => {
  1893. });
  1894. }
  1895. }
  1896. }
  1897. return mediaItems;
  1898. }
  1899. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  1900. animateTo({ duration: 666 }, () => {
  1901. this.opacityItem = 0.5;
  1902. });
  1903. setTimeout(() => {
  1904. this.videoLocalList = mList;
  1905. if (!noSort) {
  1906. if (this.modeType === 0 || this.modeType === 1) {
  1907. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1908. this.doSortType(this.sortType)
  1909. }
  1910. }
  1911. this.dataSource.pushArrayData(this.videoLocalList)
  1912. animateTo({ duration: 666 }, () => {
  1913. this.opacityItem = 1;
  1914. });
  1915. //添加到字母索引表
  1916. this.setAlphaBet()
  1917. this.setButtonStatus()
  1918. }, 200);
  1919. }
  1920. getCurFileList(): Array<VideoItem> {
  1921. if(this.isSearchMode){
  1922. return this.filteredList
  1923. }
  1924. let files: Array<VideoItem> = [];
  1925. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1926. for (let i = 0; i < this.videoLocalList.length; i++) {
  1927. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  1928. files.push(this.videoLocalList[i]);
  1929. }
  1930. }
  1931. }
  1932. return files
  1933. }
  1934. setButtonStatus() {
  1935. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1936. this.isZero = false
  1937. } else {
  1938. this.isZero = true
  1939. }
  1940. if (this.currentPath !== this.rootPath &&
  1941. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  1942. this.isHasDir = true //不为空,说明有子文件夹
  1943. } else {
  1944. this.isHasDir = false
  1945. }
  1946. }
  1947. @Builder
  1948. SortMenuBuilder() {
  1949. Menu() {
  1950. MenuItem({
  1951. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  1952. content: "按艺术家升序"
  1953. })
  1954. .onClick(async () => {
  1955. this.doSortType(0)
  1956. PreferencesUtil.put(SettingPage.SORT_TYPE, 0)
  1957. this.updateListData(this.videoLocalList, true)
  1958. })
  1959. MenuItem({
  1960. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  1961. content: "按艺术家降序"
  1962. })
  1963. .onClick(async () => {
  1964. this.doSortType(1)
  1965. PreferencesUtil.put(SettingPage.SORT_TYPE, 1)
  1966. this.updateListData(this.videoLocalList, true)
  1967. })
  1968. MenuItem({
  1969. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat_size_square')),
  1970. content: "按专辑升序"
  1971. })
  1972. .onClick(async () => {
  1973. this.doSortType(2)
  1974. PreferencesUtil.put(SettingPage.SORT_TYPE, 2)
  1975. this.updateListData(this.videoLocalList, true)
  1976. })
  1977. MenuItem({
  1978. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.character_arrow_clockwise')),
  1979. content: "按专辑降序"
  1980. })
  1981. .onClick(async () => {
  1982. this.doSortType(3)
  1983. PreferencesUtil.put(SettingPage.SORT_TYPE, 3)
  1984. this.updateListData(this.videoLocalList, true)
  1985. })
  1986. MenuItem({
  1987. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  1988. content: $r('app.string.sort_by_name')
  1989. })
  1990. .onClick(async () => {
  1991. this.doSortType(4)
  1992. PreferencesUtil.put(SettingPage.SORT_TYPE, 4)
  1993. this.updateListData(this.videoLocalList, true)
  1994. })
  1995. MenuItem({
  1996. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  1997. content: '按名称降序'
  1998. })
  1999. .onClick(async () => {
  2000. this.doSortType(5)
  2001. PreferencesUtil.put(SettingPage.SORT_TYPE, 5)
  2002. this.updateListData(this.videoLocalList, true)
  2003. })
  2004. MenuItem({
  2005. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2006. content: $r('app.string.sort_by_time')
  2007. })
  2008. .onClick(async () => {
  2009. this.doSortType(6)
  2010. PreferencesUtil.put(SettingPage.SORT_TYPE, 6)
  2011. this.updateListData(this.videoLocalList, true)
  2012. })
  2013. MenuItem({
  2014. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  2015. content: '按添加时间降序'
  2016. })
  2017. .onClick(async () => {
  2018. this.doSortType(7)
  2019. PreferencesUtil.put(SettingPage.SORT_TYPE, 7)
  2020. this.updateListData(this.videoLocalList, true)
  2021. })
  2022. }.attributeModifier(new MenuModifier())
  2023. }
  2024. @Builder
  2025. SortMenuForArtistAblumBuilder() {
  2026. Menu() {
  2027. MenuItem({
  2028. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2029. content: $r('app.string.sort_by_name')
  2030. })
  2031. .onClick(async () => {
  2032. this.doSortType(4)
  2033. // PreferencesUtil.put(SettingPage.SORT_TYPE, 2)
  2034. this.updateListData(this.videoLocalList, true)
  2035. })
  2036. MenuItem({
  2037. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2038. content: '按名称降序'
  2039. })
  2040. .onClick(async () => {
  2041. this.doSortType(5)
  2042. this.updateListData(this.videoLocalList, true)
  2043. })
  2044. MenuItem({
  2045. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2046. content: '按数量升序'
  2047. })
  2048. .onClick(async () => {
  2049. this.doSortType(8)
  2050. this.updateListData(this.videoLocalList, true)
  2051. })
  2052. MenuItem({
  2053. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  2054. content: '按数量降序'
  2055. })
  2056. .onClick(async () => {
  2057. this.doSortType(9)
  2058. this.updateListData(this.videoLocalList, true)
  2059. })
  2060. }.attributeModifier(new MenuModifier())
  2061. }
  2062. doSortType(index: number) {
  2063. switch (index) {
  2064. case 0:
  2065. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2066. // 类型排序优先级
  2067. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2068. if (typeOrder !== 0) {
  2069. return typeOrder;
  2070. }
  2071. // 处理艺术家可能为undefined的字符串比较
  2072. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  2073. const artistB = b.artist?.trim() || '';
  2074. return artistA.localeCompare(artistB);
  2075. });
  2076. break;
  2077. case 1:
  2078. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2079. // 类型排序优先级
  2080. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2081. if (typeOrder !== 0) {
  2082. return typeOrder;
  2083. }
  2084. // 处理艺术家可能为undefined的字符串比较
  2085. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  2086. const artistB = b.artist?.trim() || '';
  2087. return artistB.localeCompare(artistA);
  2088. });
  2089. break;
  2090. case 2:
  2091. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2092. // 类型排序优先级
  2093. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2094. if (typeOrder !== 0) {
  2095. return typeOrder;
  2096. }
  2097. // 处理专辑可能为undefined的字符串比较
  2098. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  2099. const albumB = b.album?.trim() || '';
  2100. return albumA.localeCompare(albumB);
  2101. });
  2102. break;
  2103. case 3:
  2104. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2105. // 类型排序优先级
  2106. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2107. if (typeOrder !== 0) {
  2108. return typeOrder;
  2109. }
  2110. // 处理专辑可能为undefined的字符串比较
  2111. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  2112. const albumB = b.album?.trim() || '';
  2113. return albumB.localeCompare(albumA);
  2114. });
  2115. break;
  2116. case 4:
  2117. Utility.doSortListAscending(this.videoLocalList,this.isShowFileName)
  2118. break;
  2119. case 5:
  2120. Utility.doSortListDescending(this.videoLocalList,this.isShowFileName)
  2121. break;
  2122. case 6:
  2123. this.videoLocalList.sort((a, b) => {
  2124. // First, sort by type
  2125. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2126. if (typeOrder !== 0) {
  2127. return typeOrder;
  2128. }
  2129. // If types are the same, sort by cTime in ascending order
  2130. return a.cTime.localeCompare(b.cTime);
  2131. });
  2132. break;
  2133. case 7:
  2134. this.videoLocalList.sort((a, b) => {
  2135. // First, sort by type
  2136. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2137. if (typeOrder !== 0) {
  2138. return typeOrder;
  2139. }
  2140. // If types are the same, sort by cTime in descending order
  2141. return b.cTime.localeCompare(a.cTime);
  2142. });
  2143. break;
  2144. case 8:
  2145. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  2146. // 1. Sort by type first
  2147. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  2148. if (typeOrder !== 0) {
  2149. return typeOrder;
  2150. }
  2151. // 2. Then sort by artist count (numeric comparison)
  2152. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  2153. if(this.modeType === 2){
  2154. sortMap = this.artistMap
  2155. }else{
  2156. sortMap = this.albumMap
  2157. }
  2158. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  2159. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  2160. return aArtistCount - bArtistCount;
  2161. });
  2162. break;
  2163. case 9:
  2164. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  2165. // 1. Sort by type first
  2166. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  2167. if (typeOrder !== 0) {
  2168. return typeOrder;
  2169. }
  2170. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  2171. if(this.modeType === 2){
  2172. sortMap = this.artistMap
  2173. }else{
  2174. sortMap = this.albumMap
  2175. }
  2176. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  2177. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  2178. return bArtistCount - aArtistCount;
  2179. });
  2180. break;
  2181. }
  2182. }
  2183. showSheelDialog() {
  2184. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  2185. // this.showTips()
  2186. // return
  2187. // }
  2188. this.showAddDialog()
  2189. }
  2190. showAddDialog() {
  2191. if (this.modeType === 2 || this.modeType === 3) {
  2192. return
  2193. }
  2194. DialogHelper.showActionSheetDialog({
  2195. title: "请选择添加方式(建议歌词文件一起导入)",
  2196. sheets: [
  2197. { value: "新建文件夹", fontColor: $r('app.color.text_color') },
  2198. { value: "手动导入", fontColor: $r('app.color.text_color') },
  2199. { value: "自动导入", fontColor: $r('app.color.text_color') },
  2200. { value: "全选导入", fontColor: $r('app.color.text_color') },
  2201. ],
  2202. maskColor: Color.Transparent,
  2203. backgroundColor: $r('app.color.bg_card'),
  2204. transition: AnimationHelper.transitionInDown(555),
  2205. onAction: (index) => {
  2206. switch (index) {
  2207. case 0:
  2208. if (this.modeType === 0) {
  2209. this.showMkDialog()
  2210. } else {
  2211. ToastUtil.showToast('请切换到首页才能新建文件夹!')
  2212. }
  2213. break;
  2214. case 1:
  2215. this.callFilePickerSelectFile()
  2216. break;
  2217. case 2:
  2218. this.showTips()
  2219. break;
  2220. case 3:
  2221. this.goSelectMusic()
  2222. break;
  2223. }
  2224. }
  2225. })
  2226. }
  2227. //拉起音频
  2228. goSelectMusic() {
  2229. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  2230. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  2231. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  2232. ) {
  2233. ToastUtil.showToast('暂时不支持该设备')
  2234. return
  2235. }
  2236. try {
  2237. let documentSelectOptions = new picker.DocumentSelectOptions();
  2238. documentSelectOptions.authMode = true
  2239. documentSelectOptions.multiAuthMode = true
  2240. if( deviceInfo.sdkApiVersion>=21){//如果api大于21 ,可以支持1w首歌以上
  2241. documentSelectOptions.maxSelectNumber = 20000
  2242. }
  2243. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  2244. let documentPicker = new picker.DocumentViewPicker(this.context);
  2245. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  2246. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  2247. this.saveVideoDatas(documentSelectResult)
  2248. }
  2249. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  2250. JSON.stringify(documentSelectResult));
  2251. }).catch((err: BusinessError) => {
  2252. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  2253. });
  2254. } catch (error) {
  2255. let err: BusinessError = error as BusinessError;
  2256. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2257. }
  2258. }
  2259. async showTips() {
  2260. try {
  2261. this.getUIContext().getPromptAction().showDialog({
  2262. title: '导入指南',
  2263. message:'用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2264. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2265. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2266. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后去文件扫描一下。\n',
  2267. buttons: [
  2268. {
  2269. text: '知道了',
  2270. color: '#000000'
  2271. },
  2272. ]
  2273. }, (err, data) => {
  2274. if (err) {
  2275. console.error('showDialog err: ' + err);
  2276. return;
  2277. }
  2278. console.info('showDialog success callback, click button: ' + data.index);
  2279. });
  2280. } catch (error) {
  2281. let message = (error as BusinessError).message;
  2282. let code = (error as BusinessError).code;
  2283. console.error(`showDialog args error code is ${code}, message is ${message}`);
  2284. };
  2285. // DialogHelper.showTipsDialog({
  2286. // title: '使用提示:自动导入教程',
  2287. //
  2288. // content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2289. // + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2290. // '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2291. // '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  2292. // onAction: (action) => {
  2293. // if (action == DialogAction.TWO) {
  2294. // PreferencesUtil.putSync('isFirstMusic', false)
  2295. // router.pushUrl({
  2296. // url: 'pages/ScanFilePage'
  2297. // });
  2298. // }
  2299. // }
  2300. // })
  2301. }
  2302. showMkDialog() {
  2303. DialogHelper.showTextInputDialog({
  2304. title: '新建歌单',
  2305. maskColor: Color.Transparent,
  2306. text: '',
  2307. transition: AnimationHelper.transitionInDown(666),
  2308. onChange: (text) => {
  2309. console.error("onChange: " + text);
  2310. },
  2311. onAction: (action, dialogId, content) => {
  2312. // ToastUtil.showToast('content = ' +content)
  2313. if (action == DialogAction.TWO) {
  2314. const newName = content
  2315. const newPath = this.currentPath + '/' + newName
  2316. FileUtil.mkdir(newPath, true).then(() => {
  2317. this.cache.delete(this.currentPath); // 删除目标路径缓存
  2318. this.getSortedFiles(this.currentPath)
  2319. }).catch((error: BusinessError) => {
  2320. console.error(error.message);
  2321. });
  2322. }
  2323. }
  2324. })
  2325. }
  2326. @State progress: number = 0;
  2327. async saveVideoDatas(uris:string[],isOpen?:boolean){
  2328. if (ArrayUtil.isEmpty(uris)) {
  2329. return;
  2330. }
  2331. console.info('onecold this.isCopyFileToDownLoad = ' + this.isCopyFileToDownLoad);
  2332. if(this.isCopyFileToDownLoad||this.currentPath==this.lockPath||isOpen){
  2333. this.saveVideoDatasToDownLoad(uris,isOpen)
  2334. return
  2335. }
  2336. // 初始化进度条
  2337. this.progress = 0;
  2338. DialogHelper.showLoadingProgress({
  2339. progress: this.progress,
  2340. backCancel: false,
  2341. autoCancel: false,
  2342. loadColor: $r('app.color.title_bar_bg'),
  2343. fontColor: $r('app.color.title_bar_bg')
  2344. });
  2345. // 计算处理总数用于进度计算
  2346. const totalItems = uris.length;
  2347. let processedItems = 0;
  2348. for (let i = 0; i < uris.length; i++) {
  2349. let filePath = uris[i];
  2350. try {
  2351. if (this.currentPath !== this.lockPath) { // 判断不是私密音乐,才入库
  2352. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2353. let mediaItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context,
  2354. filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2355. console.info('onecold saveVideoDatas filePath = ' + filePath)
  2356. if (!filePath.includes(this.rootPath)) {
  2357. console.info('onecold saveVideoDatas mediaItem.parentPath111 = ' + mediaItem.parentPath)
  2358. mediaItem.parentPath = this.currentPath;
  2359. }
  2360. console.info('onecold saveVideoDatas mediaItem.parentPath = ' + mediaItem.parentPath)
  2361. this.table.insert(mediaItem, (id: number) => {
  2362. // 插入完成回调
  2363. });
  2364. }
  2365. }
  2366. // 更新进度
  2367. processedItems++;
  2368. this.progress = Math.floor((processedItems / totalItems) * 100);
  2369. DialogHelper.updateLoading(' 正在处理', this.progress);
  2370. } catch (error) {
  2371. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2372. // 即使出错也更新进度
  2373. processedItems++;
  2374. this.progress = Math.floor((processedItems / totalItems) * 100);
  2375. DialogHelper.updateLoading(' 正在处理', this.progress);
  2376. }
  2377. }
  2378. // 关闭进度条
  2379. DialogHelper.closeLoading();
  2380. this.isZero = false
  2381. // 删除目标路径缓存
  2382. setTimeout(() => {
  2383. this.cache.delete(this.currentPath);
  2384. this.getSortedFiles(this.currentPath,false,uris[0],isOpen)
  2385. this.setButtonStatus()
  2386. }, 500);
  2387. }
  2388. async saveVideoDatasToDownLoad(uris: string[], isOpen?: boolean) {
  2389. if (ArrayUtil.isEmpty(uris)) {
  2390. return;
  2391. }
  2392. let newUris: string[] = [];
  2393. this.progress = 0
  2394. DialogHelper.showLoadingProgress({
  2395. progress: this.progress,
  2396. backCancel: false,
  2397. autoCancel: false,
  2398. loadColor: this.themeColor,
  2399. fontColor: this.themeColor
  2400. });
  2401. // 计算所有文件的总大小
  2402. let totalSize = 0;
  2403. for (let uri of uris) {
  2404. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  2405. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  2406. await fileIo.close(sourceFile.fd);
  2407. }
  2408. let totalRead = 0;
  2409. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  2410. Logger.info(TAG, 'destPath uri: ' + destPath);
  2411. for (let i = 0; i < uris.length; i++) {
  2412. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  2413. Logger.info(TAG, 'filePath uri: ' + filePath);
  2414. newUris.push(filePath);
  2415. try {
  2416. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  2417. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  2418. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  2419. const buffer = new ArrayBuffer(buffSize);
  2420. let len = await fileIo.read(sourceFile.fd, buffer);
  2421. while (len > 0) {
  2422. await fileIo.write(destFile.fd, buffer.slice(0, len));
  2423. totalRead += len;
  2424. // 计算总进度
  2425. this.progress = Math.floor((totalRead / totalSize) * 100);
  2426. DialogHelper.updateLoading('正在导入', this.progress);
  2427. len = await fileIo.read(sourceFile.fd, buffer);
  2428. }
  2429. await fileIo.close(sourceFile.fd);
  2430. await fileIo.close(destFile.fd);
  2431. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  2432. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2433. let mediaItem: VideoItem =
  2434. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2435. this.table.insert(mediaItem, (id: number) => {
  2436. // 删除目标路径缓存
  2437. this.cache.delete(this.currentPath);
  2438. this.getSortedFiles(this.currentPath, true, destPath, isOpen,mediaItem)
  2439. });
  2440. }
  2441. }
  2442. } catch (error) {
  2443. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2444. }
  2445. }
  2446. DialogHelper.closeLoading()
  2447. this.isZero = false
  2448. // setTimeout(() => {
  2449. // // 删除目标路径缓存
  2450. // this.cache.delete(this.currentPath);
  2451. // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
  2452. // }, 500);
  2453. Logger.info(TAG, 'scan select video result:' + newUris)
  2454. }
  2455. //拉起音频
  2456. // goSelectMusic(){
  2457. //
  2458. // try {
  2459. // let audioSelectOptions = new picker.AudioSelectOptions();
  2460. // let audioPicker = new picker.AudioViewPicker(this.context);
  2461. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  2462. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  2463. // this.saveVideoDatas(audioSelectResult)
  2464. // }
  2465. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  2466. // }).catch((err: BusinessError) => {
  2467. //
  2468. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  2469. // });
  2470. // } catch (error) {
  2471. // let err: BusinessError = error as BusinessError;
  2472. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2473. // }
  2474. //
  2475. //
  2476. //
  2477. // }
  2478. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  2479. if (!item) {
  2480. return undefined;
  2481. }
  2482. try {
  2483. let selectUris: Array<string> = [];
  2484. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  2485. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  2486. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  2487. photoSelectOptions.maxSelectNumber = 1;
  2488. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  2489. selectUris = photoSelectResult.photoUris;
  2490. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  2491. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  2492. console.info('file fd: ' + file.fd);
  2493. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  2494. let imagePath = this.context.filesDir + FileUtil.separator + name
  2495. imagePath = fileUri.getUriFromPath(imagePath)
  2496. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  2497. fileIo.copyFileSync(file.fd, file2.fd)
  2498. fileIo.closeSync(file);
  2499. fileIo.closeSync(file2);
  2500. if (item.filePath == this.currentSong?.filePath) {
  2501. this.cover = imagePath
  2502. }
  2503. if (item) {
  2504. item.pixelMapPath = imagePath
  2505. }
  2506. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  2507. if (success) {
  2508. this.doUpdateData()
  2509. console.log("onecold 更新音乐封面成功,数据库已同步");
  2510. } else {
  2511. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  2512. }
  2513. });
  2514. LogUtil.debug("onecold this.cover =" + this.cover)
  2515. return FileUtil.getFilePath(imagePath); // Return the image path here
  2516. } catch (err) {
  2517. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  2518. return undefined;
  2519. }
  2520. }
  2521. // 拉起picker选择文件管理器
  2522. async callFilePickerSelectFile(): Promise<void> {
  2523. try {
  2524. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  2525. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  2526. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  2527. } else {
  2528. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  2529. }
  2530. let documentPicker = new picker.DocumentViewPicker();
  2531. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  2532. Logger.info(TAG,
  2533. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  2534. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  2535. this.saveVideoDatas(DocumentSelectResult)
  2536. }
  2537. }).catch((err: BusinessError) => {
  2538. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  2539. });
  2540. } catch (err) {
  2541. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  2542. }
  2543. }
  2544. //重命名的对话框
  2545. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  2546. if(!item.filePath.includes(this.packName)){
  2547. ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限重命名')
  2548. return
  2549. }
  2550. DialogHelper.showTextInputDialog({
  2551. title: '重命名',
  2552. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  2553. maskColor: Color.Transparent,
  2554. backgroundColor: Color.Grey,
  2555. transition: AnimationHelper.transitionInDown(666),
  2556. onChange: (text) => {
  2557. console.error("onChange: " + text);
  2558. },
  2559. onAction: (action, dialogId, content) => {
  2560. // ToastUtil.showToast('content = ' +content)
  2561. if (action == DialogAction.TWO) {
  2562. const newName = content
  2563. const newPath = this.currentPath + '/' + newName
  2564. console.log("onecold item = " + item.type);
  2565. this.doReName(index, newName, filePath, newPath, item)
  2566. }
  2567. }
  2568. })
  2569. }
  2570. //剪切 移动到另个文件夹的对话框
  2571. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2572. Logger.info('onecold showCutDialog')
  2573. let mList: Array<string> = []
  2574. let rPath = this.rootPath
  2575. if (isCurrent) {
  2576. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2577. rPath = this.currentPath
  2578. } else {
  2579. mList = Utility.getNameList(this.dirList);
  2580. rPath = this.rootPath
  2581. }
  2582. let dataBean = new BubbleBean()
  2583. dataBean.data = mList
  2584. dataBean.color = this.themeColor
  2585. dataBean.onItemClick = (i) => {
  2586. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2587. Logger.info('newPath = ' + newPath)
  2588. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  2589. ToastUtil.showToast('移动成功')
  2590. this.table.deleteData(item, () => {
  2591. });
  2592. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2593. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2594. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2595. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2596. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2597. this.table.insert(newItem, (id: number) => {
  2598. //加入数据库
  2599. });
  2600. }
  2601. this.cache.delete(this.currentPath); // 删除原路径缓存
  2602. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2603. this.getSortedFiles(this.currentPath, true)
  2604. }).catch((error: BusinessError) => {
  2605. console.error(error.message);
  2606. });
  2607. XPopup.dismissTop()
  2608. }
  2609. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2610. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2611. popupPosition = PopupPosition.TOP
  2612. }
  2613. if (index <= 3) {
  2614. popupPosition = PopupPosition.BOTTOM
  2615. }
  2616. let pup: XPopup
  2617. if (this.isDarkMode) {
  2618. pup = XPopup.Builder()
  2619. .setPopupPosition(popupPosition)
  2620. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  2621. .setBackgroundColor(Color.Black)
  2622. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2623. .show()
  2624. } else {
  2625. pup = XPopup.Builder()
  2626. .setPopupPosition(popupPosition)
  2627. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  2628. .setBackgroundColor(Color.White)
  2629. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2630. .show()
  2631. }
  2632. }
  2633. //复制 到另个文件夹的对话框
  2634. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2635. Logger.info('onecoldv showCopyDialog')
  2636. let mList: Array<string> = []
  2637. let rPath = this.rootPath
  2638. if (isCurrent) {
  2639. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2640. rPath = this.currentPath
  2641. } else {
  2642. mList = Utility.getNameList(this.dirList);
  2643. rPath = this.rootPath
  2644. }
  2645. let dataBean = new BubbleBean()
  2646. dataBean.data = mList
  2647. dataBean.isCopy = true
  2648. dataBean.color = this.themeColor
  2649. dataBean.onItemClick = (i) => {
  2650. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2651. Logger.info('newPath = ' + newPath)
  2652. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2653. ToastUtil.showToast('复制成功')
  2654. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2655. this.getSortedFiles(this.currentPath)
  2656. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2657. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2658. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2659. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2660. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2661. this.table.insert(newItem, (id: number) => {
  2662. //加入数据库
  2663. });
  2664. }
  2665. }).catch((error: BusinessError) => {
  2666. console.error(error.message);
  2667. });
  2668. XPopup.dismissTop()
  2669. }
  2670. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2671. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2672. popupPosition = PopupPosition.TOP
  2673. }
  2674. if (index <= 3) {
  2675. popupPosition = PopupPosition.BOTTOM
  2676. }
  2677. let pup: XPopup
  2678. if (this.isDarkMode) {
  2679. pup = XPopup.Builder()
  2680. .setPopupPosition(popupPosition)
  2681. .atView(id)
  2682. .setMaxHeight('60%')
  2683. .setBackgroundColor(Color.Black)
  2684. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2685. .show();
  2686. } else {
  2687. pup = XPopup.Builder()
  2688. .setPopupPosition(popupPosition)
  2689. .atView(id)
  2690. .setMaxHeight('60%')
  2691. .setBackgroundColor(Color.White)
  2692. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2693. .show();
  2694. }
  2695. }
  2696. //重命名索引index的视频
  2697. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  2698. FileUtil.rename(oldPath, newPath).then(async () => {
  2699. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2700. if (info.type === CommonConstants.TYPE_IS_DIR) {
  2701. //如果是文件夹先删除源数据,再添加新数据
  2702. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  2703. if (success) {
  2704. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  2705. } else {
  2706. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  2707. }
  2708. });
  2709. this.scanDirectory(newPath)
  2710. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  2711. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  2712. if (success) {
  2713. console.log(" onecold 重命名成功,数据库已同步");
  2714. } else {
  2715. console.error(" onecold 重命名数据库失败原因: " + error);
  2716. }
  2717. });
  2718. }
  2719. let mediaItem: VideoItem =
  2720. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2721. this.videoLocalList[index] = mediaItem;
  2722. }
  2723. this.cache.delete(this.currentPath)
  2724. this.getSortedFiles(this.currentPath, true)
  2725. }).catch((error: BusinessError) => {
  2726. console.error(error.message);
  2727. });
  2728. }
  2729. build() {
  2730. Stack() {
  2731. this.ContentBuild()
  2732. Stack() {
  2733. this.PlayController()
  2734. }
  2735. .hitTestBehavior(HitTestMode.Transparent)
  2736. .opacity(this.barBottomOpacity)
  2737. .width('90%')
  2738. .borderRadius(20)
  2739. .margin({ bottom:DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_2IN1
  2740. ? 30 :this.bottomSafeHeight })
  2741. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  2742. .backgroundImage( this.cover)
  2743. .visibility(this.isMultiSelect ? Visibility.None : Visibility.Visible)
  2744. .backgroundImageSize( { width: '100%' })
  2745. .opacity(0.9)
  2746. .clickEffect({ level: ClickEffectLevel.HEAVY })
  2747. }
  2748. .alignContent(Alignment.Bottom)
  2749. .width('100%')
  2750. .height('100%')
  2751. }
  2752. @Builder
  2753. ContentBuild() {
  2754. Scroll() {
  2755. Column() {
  2756. Stack() {
  2757. //libraryname加上去后onKeyEvent监听不了,因为目前的解决方案是上面的XComponent,去掉libraryname
  2758. XComponent({ id: 'for_onKeyEvent',type: XComponentType.SURFACE,
  2759. controller: this.xcomponentController })
  2760. .onLoad(async (event?: object) => {
  2761. })
  2762. .focusable(true)
  2763. .height(0)
  2764. .focusOnTouch(true)
  2765. .defaultFocus(true) // 自动获取键盘焦点
  2766. .onKeyEvent((event?: KeyEvent) => {
  2767. console.info('onecold点击 onKeyEvent')
  2768. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  2769. if (!event || event.type !== KeyType.Down) {
  2770. return;
  2771. }
  2772. console.info('onecold点击 onKeyEvent event.keyCode: ' + event.keyCode)
  2773. //空格键 Space key controls pause/play
  2774. if (event.keyCode === KeyCode.KEYCODE_SPACE|| event.keyCode === KeyCode.KEYCODE_MEDIA_PLAY_PAUSE) {
  2775. this.playOrPause()
  2776. }
  2777. if (event.keyCode === KeyCode.KEYCODE_DPAD_UP) {
  2778. this.playPrevious()
  2779. }
  2780. if (event.keyCode === KeyCode.KEYCODE_DPAD_DOWN) {
  2781. this.playNext()
  2782. }
  2783. // Right-click to fast forward
  2784. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  2785. this.fastForward()
  2786. }
  2787. // Left-click to rewind
  2788. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  2789. this.backForward()
  2790. }
  2791. })
  2792. Column() {
  2793. XComponent({
  2794. id: 'xcomponentId',
  2795. type: 'surface',
  2796. libraryname: 'ijkplayer_napi',
  2797. controller: this.xcomponentController
  2798. })
  2799. .onLoad((event?: object) => {
  2800. if (!!event) {
  2801. this.initDelayPlay(event);
  2802. }
  2803. })
  2804. .onDestroy(() => {
  2805. })
  2806. .width('100%')// .width(this.videoWidth)
  2807. .aspectRatio(this.videoAspectRatio)
  2808. }
  2809. .aspectRatio(this.videoAspectRatio)
  2810. .justifyContent(FlexAlign.Center)
  2811. .backgroundColor(Color.Transparent)
  2812. .visibility(Visibility.Hidden)
  2813. .height(CommonConstants.FULL_PERCENT)
  2814. .width(CommonConstants.FULL_PERCENT)
  2815. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  2816. height:this.isLandscape?'80%': '43%',
  2817. dragBar: true,
  2818. showClose: true,
  2819. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  2820. blurStyle:BlurStyle.Thin,
  2821. backgroundColor:Color.Transparent,
  2822. title: { title: 'AB循环' }
  2823. })
  2824. Stack() {
  2825. Column() {
  2826. if(this.twoFingerType==4){
  2827. this.getWaterView()
  2828. }else{
  2829. if(this.isGridMusic){
  2830. this.getGridView()
  2831. }else {
  2832. this.getList()
  2833. }
  2834. }
  2835. if (this.modeType ==0||this.modeType==4) {
  2836. Column() {
  2837. emptyView(this.themeColor)
  2838. }
  2839. .position({ top: 200 })
  2840. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  2841. .animation({ duration: 500 }),
  2842. TransitionEffect.scale({ x: 0, y: 0 })))
  2843. .justifyContent(FlexAlign.Center)
  2844. .opacity(this.isZero ? 1 : 0)
  2845. .visibility(this.isZero && !this.isFavMusic && !this.isHistory
  2846. ? Visibility.Visible : Visibility.None)
  2847. .animation({
  2848. duration: 500,
  2849. curve: 'ease-in-out' // 可选动画曲线
  2850. })
  2851. .width('100%')
  2852. }
  2853. }
  2854. .layoutWeight(1)
  2855. .height('100%')
  2856. // 右侧居中的字母表索引
  2857. this.indexBuilder()
  2858. this.topTitleBar()
  2859. }
  2860. .alignContent(Alignment.Top)
  2861. .layoutWeight(1)
  2862. .height('100%')
  2863. Row() {
  2864. Button(this.isAllSelected ? '反选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  2865. .width(45)
  2866. .height(45)
  2867. .fontSize(10)
  2868. .margin({ top: 10, bottom: 10, right: 6 })
  2869. .backgroundColor(this.themeColor)
  2870. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2871. .onClick(() => {
  2872. if (this.isAllSelected) {
  2873. // 全不选
  2874. this.selectedFiles = [];
  2875. } else {
  2876. // 全选
  2877. this.selectedFiles = [...this.getCurFileList()];
  2878. }
  2879. this.isAllSelected = !this.isAllSelected;
  2880. })
  2881. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  2882. .width(72)
  2883. .height(45)
  2884. .fontSize(10)
  2885. .margin({ top: 10, bottom: 10, right: 6 })
  2886. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2887. .backgroundColor(this.themeColor)
  2888. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  2889. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2890. })
  2891. .onClick(() => {
  2892. // if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  2893. this.isOneKeyTags = !this.isOneKeyTags
  2894. // }else{
  2895. // ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限批量内嵌')
  2896. // }
  2897. })
  2898. Button('合并', { type: ButtonType.Circle, stateEffect: true })
  2899. .width(45)
  2900. .height(45)
  2901. .fontSize(10)
  2902. .margin({ top: 10, bottom: 10, right: 6 })
  2903. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2904. .backgroundColor(this.themeColor)
  2905. .bindContentCover($$this.isMergeAudio, this.MergeAudioBuilder(), {
  2906. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2907. })
  2908. .onClick(() => {
  2909. if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  2910. this.isMergeAudio = !this.isMergeAudio
  2911. }else{
  2912. ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限合并')
  2913. }
  2914. })
  2915. Button('+歌单', { type: ButtonType.Circle, stateEffect: true })
  2916. .width(45)
  2917. .height(45)
  2918. .fontSize(10)
  2919. .margin({ top: 10, bottom: 10, right: 6 })
  2920. .backgroundColor(this.themeColor)
  2921. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2922. .onClick(async () => {
  2923. this.longItemFilePath = ''
  2924. await this.openAddToPlaylistDialog(this.selectedFiles)
  2925. })
  2926. // Button('乱码', { type: ButtonType.Circle, stateEffect: true })
  2927. // .width(45)
  2928. // .height(45)
  2929. // .fontSize(10)
  2930. // .margin({ top: 10, bottom: 10, right: 6 })
  2931. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2932. // .backgroundColor(this.themeColor)
  2933. // .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  2934. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2935. // })
  2936. // .onClick(() => {
  2937. // this.isFixMessy = !this.isFixMessy
  2938. // })
  2939. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  2940. // .width('35%')
  2941. // .height(60)
  2942. // .id('music_cut')
  2943. // .margin({ top: 10, bottom: 10, right: 6 })
  2944. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2945. // .backgroundColor(this.themeColor)
  2946. // .onClick(() => {
  2947. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  2948. // })
  2949. //
  2950. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  2951. // .width('35%')
  2952. // .height(60)
  2953. // .id('music_cut_current')
  2954. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  2955. // .margin({ top: 10, bottom: 10, right: 6 })
  2956. // .backgroundColor(this.themeColor)
  2957. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2958. // .onClick(() => {
  2959. //
  2960. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  2961. // })
  2962. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  2963. // .width('35%')
  2964. // .height(60)
  2965. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  2966. // .margin({ top: 10, bottom: 10, right: 6 })
  2967. // .backgroundColor(this.themeColor)
  2968. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2969. // .onClick(() => {
  2970. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  2971. // })
  2972. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  2973. .width(45)
  2974. .height(45)
  2975. .fontSize(10)
  2976. .margin({ top: 10, bottom: 10, right: 6 })
  2977. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  2978. .backgroundColor(this.themeColor)
  2979. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2980. .onClick(() => {
  2981. this.showWarnIsDelete()
  2982. })
  2983. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  2984. .width(45)
  2985. .height(45)
  2986. .fontSize(10)
  2987. .margin({ top: 10, bottom: 10, right: 6 })
  2988. .backgroundColor(this.themeColor)
  2989. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2990. .onClick(() => {
  2991. this.selectedFiles = [];
  2992. this.isAllSelected = false
  2993. this.isMultiSelect = false
  2994. })
  2995. }
  2996. .width('100%')
  2997. .justifyContent(FlexAlign.Center)
  2998. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2999. .opacity(this.isMultiSelect ? 1 : 0)
  3000. .animation({
  3001. duration: 666,
  3002. curve: 'ease-in-out' // 可选动画曲线
  3003. })
  3004. .position({ bottom: 20 }) // 将 Row 固定在底部
  3005. }
  3006. .width('100%')
  3007. .height('100%')
  3008. .alignContent(Alignment.Top)
  3009. }
  3010. .width('100%')
  3011. .height('100%')
  3012. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  3013. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  3014. .backgroundImagePosition(Alignment.Center)
  3015. .backdropBlur(this.blurValue)
  3016. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  3017. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  3018. }
  3019. }
  3020. //字母表索引
  3021. @Builder
  3022. indexBuilder(){
  3023. if(this.enableShowAlphabet){
  3024. Column({space: 5}){
  3025. if(this.isShowAlphaBet){
  3026. AlphabetIndexer({arrayValue: this.alphaBet,selected: this.selectAlphaBetIndex})
  3027. .attributeModifier(this.alphaBetStyle)
  3028. .usingPopup(this.isTouchingAlphaBet)
  3029. .onAreaChange((old_value,new_value)=>{
  3030. this.alphabetHeight = new_value.height as number
  3031. })
  3032. .popupPosition({
  3033. x: 40,
  3034. y: this.alphabetHeight / 2
  3035. })
  3036. .onSelect((index: number) => {
  3037. this.onSelectIndexItem(this.alphaBet[index])
  3038. })
  3039. .onTouch((event: TouchEvent) =>{
  3040. this.isShowAlphaBet = true
  3041. if(event.type === TouchType.Up || event.type === TouchType.Cancel){
  3042. this.isTouchingAlphaBet = false
  3043. }else{
  3044. this.isTouchingAlphaBet = true
  3045. }
  3046. })
  3047. .transition(
  3048. TransitionEffect.translate({x: 10})
  3049. .combine(TransitionEffect.opacity(0.1))
  3050. .animation({
  3051. duration: 150,
  3052. curve: Curve.EaseInOut,
  3053. })
  3054. )
  3055. }else{
  3056. Blank()
  3057. .layoutWeight(1)
  3058. }
  3059. // ListLocateButton()
  3060. // .onClick(() =>{
  3061. // this.locateSong()
  3062. // })
  3063. // .clickEffect({level:ClickEffectLevel.LIGHT,scale: 0.5})
  3064. // .margin({
  3065. // bottom: 10
  3066. // })
  3067. }
  3068. .padding({
  3069. bottom: 0
  3070. })
  3071. .position({x:'92%'})
  3072. .height('100%')
  3073. .justifyContent(FlexAlign.Center)
  3074. }
  3075. }
  3076. onSelectIndexItem(letter: string) {
  3077. let songs = this.videoLocalList
  3078. let targetIndex = -1;
  3079. for (let i = 0; i < songs.length; i++) {
  3080. let song = songs[i]
  3081. let text = this.isShowFileName?song.fileName:song.name
  3082. if(this.sortType === 0||this.sortType==1){
  3083. text = song.artist
  3084. }else if(this.sortType === 2||this.sortType==3){
  3085. text = song.album
  3086. }
  3087. if(text){
  3088. let firstPinyin = getFirstLetter(text)
  3089. if (firstPinyin&&firstPinyin === letter) {
  3090. targetIndex = i;
  3091. break;
  3092. }
  3093. }
  3094. }
  3095. if (targetIndex !== -1) {
  3096. this.listScroller.scrollToIndex(targetIndex);
  3097. }
  3098. }
  3099. // 找到对应字母表的索引
  3100. findAlphaBetIndex(song: VideoItem):number{
  3101. let text = this.isShowFileName?song.fileName:song.name
  3102. if(this.sortType === 0||this.sortType==1){
  3103. text = song.artist
  3104. }else if(this.sortType === 2||this.sortType==3){
  3105. text = song.album
  3106. }
  3107. if(text){
  3108. let firstLetter = getFirstLetter(text)
  3109. for(let i=0;i<this.alphaBet.length;i++){
  3110. if(this.alphaBet[i] === firstLetter){
  3111. return i
  3112. }
  3113. }
  3114. }
  3115. return 0
  3116. }
  3117. async setAlphaBet(){
  3118. return new Promise<void>((resolve,reject) => {
  3119. try {
  3120. let songs = this.videoLocalList
  3121. if(songs.length > 40000){
  3122. this.alphaBet = []
  3123. resolve()
  3124. return
  3125. }
  3126. let alphabetSet = new Set<string>();
  3127. for (let song of songs) {
  3128. let text = this.isShowFileName?song.fileName:song.name
  3129. if(this.sortType === 0||this.sortType==1){
  3130. text = song.artist
  3131. }else if(this.sortType === 2||this.sortType==3){
  3132. text = song.album
  3133. }
  3134. if(text){
  3135. let firstPinyin = getFirstLetter(text)
  3136. if(!alphabetSet.has(firstPinyin)){
  3137. alphabetSet.add(firstPinyin)
  3138. }
  3139. }
  3140. // const pyStr = song.pyStr
  3141. // if(pyStr){
  3142. // if(!alphabetSet.has(pyStr)){
  3143. // alphabetSet.add(pyStr)
  3144. // }
  3145. // }
  3146. }
  3147. this.alphaBet = Array.from(alphabetSet).sort((a,b)=>{
  3148. if(this.sortType ===4||this.sortType==0||this.sortType==2||this.sortType==6){
  3149. return a.localeCompare(b)
  3150. }else{
  3151. return b.localeCompare(a)
  3152. }
  3153. })
  3154. if(this.videoLocalList.length > 0){
  3155. this.listScroller.scrollToIndex(0)
  3156. this.selectAlphaBetIndex = 0
  3157. }
  3158. resolve()
  3159. }catch (e) {
  3160. console.error('testTag','排序字母表出错',JSON.stringify(e))
  3161. resolve()
  3162. }
  3163. })
  3164. }
  3165. @Builder
  3166. topTitleBar(){
  3167. Column() {
  3168. Row({ space: 15 }) {
  3169. if (!this.isSearchMode ) {
  3170. //左侧滑动按钮
  3171. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3172. SymbolGlyph(this.rightTopImage)
  3173. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3174. }
  3175. .attributeModifier(new ButtonFancyModifier(40, 40))
  3176. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3177. .animation({ duration: 300, curve: Curve.Ease })
  3178. .onClick(() => {
  3179. this.doSwipBack()
  3180. })
  3181. .attributeModifier(new ShadowModifier())
  3182. .zIndex(0)
  3183. }else{
  3184. //左侧搜索返回按钮
  3185. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3186. SymbolGlyph($r('sys.symbol.chevron_left'))
  3187. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3188. }
  3189. .attributeModifier(new ButtonFancyModifier(40, 40))
  3190. .margin({bottom:5})
  3191. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3192. .animation({ duration: 300, curve: Curve.Ease })
  3193. .onClick(() => {
  3194. this.isSearchMode = false
  3195. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  3196. this.searchText = ''
  3197. this.getSortedFiles(this.currentPath)
  3198. return
  3199. }
  3200. this.onSearchInput('')
  3201. })
  3202. .attributeModifier(new ShadowModifier())
  3203. .zIndex(0)
  3204. }
  3205. if (!this.isSearchMode) {
  3206. Text(this.titleName)
  3207. .margin({left:3,right:10})
  3208. .fontColor($r('app.color.text_color'))
  3209. .fontSize(this.twoFingerType==3?19:this.twoFingerType==2?17:15)
  3210. .maxLines(1)
  3211. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3212. .layoutWeight(1)
  3213. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3214. }
  3215. //搜索框
  3216. Search({ controller: this.searchController,value: this.searchText, placeholder: '搜索标题、艺术家...' })
  3217. .searchButton('搜索',{fontColor:this.themeColor})
  3218. .searchIcon({
  3219. src: $r('sys.media.ohos_ic_public_search_filled')
  3220. })
  3221. .cancelButton({
  3222. style: CancelButtonStyle.CONSTANT,
  3223. icon: {
  3224. src: $r('sys.media.ohos_ic_public_cancel_filled')
  3225. }
  3226. })
  3227. .layoutWeight(1)
  3228. .height(40)
  3229. .maxLength(20)
  3230. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  3231. .placeholderColor(Color.Grey)
  3232. .placeholderFont({ size: 14, weight: 400 })
  3233. .textFont({ size: 14, weight: 400 })
  3234. .onSubmit((value: string) => {
  3235. console.log('onecold onSubmit ='+value)
  3236. this.searchController.stopEditing()
  3237. this.onSearchInput(this.searchText);
  3238. })
  3239. .onChange((value: string) => {
  3240. console.log('onecold onChange ='+value)
  3241. this.onSearchInput(value);
  3242. })
  3243. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  3244. .animation({ duration: 300, curve: Curve.Ease })
  3245. //搜索按钮
  3246. if (!this.isSearchMode) {
  3247. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3248. SymbolGlyph($r('sys.symbol.magnifyingglass'))
  3249. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3250. }
  3251. .attributeModifier(new ButtonFancyModifier(40, 40))
  3252. .animation({ duration: 300, curve: Curve.Ease })
  3253. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3254. .attributeModifier(new ShadowModifier())
  3255. .zIndex(0)
  3256. .onClick(()=>{
  3257. this.isSearchMode = true
  3258. })
  3259. //排序按钮
  3260. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3261. SymbolGlyph($r('sys.symbol.list_number'))
  3262. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3263. }
  3264. .attributeModifier(new ButtonFancyModifier(40, 40))
  3265. .animation({ duration: 300, curve: Curve.Ease })
  3266. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3267. .bindMenu((this.modeType==2&&!this.isCanBack)||(this.modeType==3&&!this.isCanBack)
  3268. ?this.SortMenuForArtistAblumBuilder:this.SortMenuBuilder)
  3269. .attributeModifier(new ShadowModifier())
  3270. .zIndex(0)
  3271. //添加按钮
  3272. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3273. SymbolGlyph($r('sys.symbol.plus'))
  3274. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3275. }
  3276. .attributeModifier(new ButtonFancyModifier(40, 40))
  3277. .animation({ duration: 300, curve: Curve.Ease })
  3278. .visibility(this.modeType==0||this.modeType==1?Visibility.Visible:Visibility.None)
  3279. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3280. .bindSheet($$this.showAddSheet, this.addSheet(), {
  3281. height: SheetSize.FIT_CONTENT,
  3282. dragBar: true,
  3283. showClose: true,
  3284. preferType: SheetType.CENTER ,
  3285. title: {
  3286. title: '导入音乐'
  3287. }
  3288. })
  3289. .onClick(() => {
  3290. this.showAddSheet = !this.showAddSheet;
  3291. })
  3292. .attributeModifier(new ShadowModifier())
  3293. .zIndex(0)
  3294. }
  3295. }
  3296. }
  3297. .padding({ top: this.topSafeHeight+10, left: 10, right: 10 })
  3298. .width('100%')
  3299. }
  3300. @Builder
  3301. addSheet() {
  3302. Scroll() {
  3303. Column() {
  3304. Column() {
  3305. Row() {
  3306. Text('导入音乐复制到DownLoad目录')
  3307. .margin({ left: 18 })
  3308. .fontSize(14)
  3309. .fontColor($r('app.color.text_color'))
  3310. .fontWeight(480)
  3311. .layoutWeight(1)
  3312. Toggle({ type: ToggleType.Switch, isOn: this.isCopyFileToDownLoad })
  3313. .selectedColor(this.themeColor)
  3314. .switchPointColor(Color.White)
  3315. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  3316. .margin({ right: 18 })
  3317. .onChange((checked: boolean) => {
  3318. this.isCopyFileToDownLoad = checked;
  3319. PreferencesUtil.put(SettingPage.IS_COPYFILE_TO_DOWNLOAD, this.isCopyFileToDownLoad)
  3320. })
  3321. .width(50)
  3322. .height(30);
  3323. }
  3324. .height(88)
  3325. }
  3326. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3327. .backgroundColor($r('app.color.start_window_background'))
  3328. .borderRadius(15)
  3329. .margin({
  3330. left: 30,
  3331. right: 30,
  3332. top: 10,
  3333. bottom: 10
  3334. })
  3335. .padding(0)
  3336. .border({
  3337. color: Color.White,
  3338. width: 1.8
  3339. })
  3340. Menu() {
  3341. MenuItem({
  3342. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder_badge_plus')),
  3343. content: "新建文件夹"
  3344. })
  3345. .backgroundColor($r('app.color.silvery'))
  3346. .border({
  3347. width: { bottom: 1 },
  3348. color: '#12ec5c87'
  3349. })
  3350. .margin(10)
  3351. .padding({left:15,right:15})
  3352. .onClick(async () => {
  3353. this.showMkDialog()
  3354. this.showAddSheet = !this.showAddSheet
  3355. })
  3356. MenuItem({
  3357. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder')),
  3358. content: $r('app.string.import_from_files')
  3359. })
  3360. .padding({left:15,right:15})
  3361. .backgroundColor($r('app.color.silvery'))
  3362. .border({
  3363. width: { bottom: 1 },
  3364. color: '#12ec5c87'
  3365. })
  3366. .margin(10)
  3367. .onClick(async () => {
  3368. this.callFilePickerSelectFile()
  3369. this.showAddSheet = !this.showAddSheet
  3370. })
  3371. MenuItem({
  3372. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square')),
  3373. content: '全选导入'
  3374. // content: '从下载文件夹导入(路径:Download/' +
  3375. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  3376. })
  3377. .padding({left:15,right:15})
  3378. .backgroundColor($r('app.color.silvery'))
  3379. .border({
  3380. width: { bottom: 1 },
  3381. color: '#12ec5c87'
  3382. })
  3383. .margin(10)
  3384. .onClick(async () => {
  3385. this.goSelectMusic()
  3386. this.showAddSheet = !this.showAddSheet
  3387. })
  3388. MenuItem({
  3389. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.save')),
  3390. content: '自动导入教程'
  3391. // content: '从下载文件夹导入(路径:Download/' +
  3392. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  3393. })
  3394. .padding({left:15,right:15})
  3395. .backgroundColor($r('app.color.silvery'))
  3396. .border({
  3397. width: { bottom: 1 },
  3398. color: '#12ec5c87'
  3399. })
  3400. .margin(10)
  3401. .onClick(async () => {
  3402. this.showTips()
  3403. this.showAddSheet = !this.showAddSheet
  3404. })
  3405. }.attributeModifier(new MenuModifier())
  3406. .margin({bottom:30})
  3407. }
  3408. .layoutWeight(1)
  3409. }
  3410. }
  3411. @Builder
  3412. TagsContentCoverBuilder() {
  3413. Scroll() {
  3414. Column() {
  3415. TagsContentCover(
  3416. {
  3417. selectedFiles:this.selectedFiles,
  3418. isOneKeyTags:this.isOneKeyTags,
  3419. table:this.table,
  3420. onTagsResult:(result: boolean,deleteCache_path?:string)=>{
  3421. this.isMultiSelect = false
  3422. if(result){//如果嵌入成功,更新数据
  3423. setTimeout(()=>{
  3424. this.doUpdateData()
  3425. },500)
  3426. }
  3427. console.info('onecold onTagsResult deleteCache_path =' +deleteCache_path)
  3428. if(deleteCache_path){
  3429. this.deleteCache(deleteCache_path)
  3430. }
  3431. }
  3432. }
  3433. )
  3434. }
  3435. }
  3436. .width('100%')
  3437. .height('100%')
  3438. }
  3439. @Builder
  3440. FixMessyViewBuilder() {
  3441. Scroll() {
  3442. Column() {
  3443. FixMessyView(
  3444. {
  3445. selectedFiles:this.selectedFiles,
  3446. isFixMessy:this.isFixMessy,
  3447. onFixResult:(result: boolean)=>{
  3448. this.isMultiSelect = false
  3449. if(result){//如果嵌入成功,更新数据
  3450. this.deleteCache(this.currentPath)
  3451. this.doUpdateData()
  3452. }
  3453. }
  3454. }
  3455. )
  3456. }
  3457. }
  3458. .width('100%')
  3459. .height('100%')
  3460. }
  3461. //剪辑音频
  3462. @Builder
  3463. EditAudioBuilder(item:VideoItem) {
  3464. Scroll() {
  3465. Column() {
  3466. EditAudio(
  3467. {
  3468. mVideoItem:item,
  3469. currentPath:this.currentPath,
  3470. videoUrl:this.videoUrl,
  3471. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3472. currentTime:this.currentTime,
  3473. progressValue:this.progressValue,
  3474. onBack:()=>{
  3475. this.isEditAudio = !this.isEditAudio
  3476. },
  3477. onSeeOutputPath:(outPutPath:string)=>{
  3478. this.isEditAudio = !this.isEditAudio
  3479. this.longItemFilePath = ''
  3480. this.modeType = 0
  3481. this.isShowFileName = true
  3482. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3483. },
  3484. onPlayOrPause:()=>{
  3485. if(this.videoUrl==item.filePath){
  3486. this.playOrPause()
  3487. }else{//如果不是当前播放的,则播放该文件
  3488. this.videoUrl==item.filePath
  3489. this.doPlay(item,0,false,true)
  3490. }
  3491. },
  3492. onSliderChange:(value:number)=>{
  3493. if(this.videoUrl!=item.filePath){
  3494. this.videoUrl==item.filePath
  3495. return
  3496. }
  3497. this.isSeekTo = true;
  3498. this.mDestroyPage = false;
  3499. this.showLoadIng();
  3500. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  3501. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3502. this.seekTo(seekValue + "");
  3503. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  3504. this.isSeekTo = false;
  3505. },
  3506. onResult:(result: boolean,outPath:string)=>{
  3507. if(result){//如果剪辑成功,更新数据
  3508. this.doUpdateData()
  3509. }else{
  3510. ToastUtil.showToast('剪辑失败')
  3511. }
  3512. }
  3513. }
  3514. )
  3515. }
  3516. }
  3517. .width('100%')
  3518. .height('100%')
  3519. }
  3520. //提取伴奏
  3521. @Builder
  3522. ConverterBuilder(item:VideoItem) {
  3523. Scroll() {
  3524. Column() {
  3525. AudioFormatConverter(
  3526. {
  3527. mVideoItem:item,
  3528. videoUrl:this.videoUrl,
  3529. currentPath:this.currentPath,
  3530. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3531. currentTime:this.currentTime,
  3532. progressValue:this.progressValue,
  3533. onBack:()=>{
  3534. this.isConverter = !this.isConverter
  3535. this.longItemFilePath = ''
  3536. },
  3537. onPlayOrPause:()=>{
  3538. if(this.videoUrl==item.filePath){
  3539. this.playOrPause()
  3540. }else{//如果不是当前播放的,则播放该文件
  3541. this.videoUrl==item.filePath
  3542. this.doPlay(item,0,false,true)
  3543. }
  3544. },
  3545. onSeeOutputPath:(outPutPath:string)=>{
  3546. this.isConverter = !this.isConverter
  3547. this.longItemFilePath = ''
  3548. this.modeType = 0
  3549. this.isShowFileName = true
  3550. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3551. },
  3552. onSliderChange:(value:number)=>{
  3553. if(this.videoUrl!=item.filePath){
  3554. this.videoUrl==item.filePath
  3555. return
  3556. }
  3557. this.isSeekTo = true;
  3558. this.mDestroyPage = false;
  3559. this.showLoadIng();
  3560. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3561. this.seekTo(seekValue + "");
  3562. this.isSeekTo = false;
  3563. },
  3564. onResult:(result: boolean,outPath:string)=>{
  3565. if(result){//如果成功,更新数据
  3566. this.doUpdateData()
  3567. }else{
  3568. ToastUtil.showToast('格式转化失败')
  3569. }
  3570. }
  3571. }
  3572. )
  3573. }
  3574. }
  3575. .width('100%')
  3576. .height('100%')
  3577. }
  3578. //提取伴奏
  3579. @Builder
  3580. ExtractAccBuilder(item:VideoItem) {
  3581. Scroll() {
  3582. Column() {
  3583. ExtractAccompaniment(
  3584. {
  3585. mVideoItem:item,
  3586. currentPath:this.currentPath,
  3587. videoUrl:this.videoUrl,
  3588. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3589. currentTime:this.currentTime,
  3590. progressValue:this.progressValue,
  3591. onBack:()=>{
  3592. this.isExtractAcc = !this.isExtractAcc
  3593. this.longItemFilePath = ''
  3594. },
  3595. onPlayOrPause:()=>{
  3596. if(this.videoUrl==item.filePath){
  3597. this.playOrPause()
  3598. }else{//如果不是当前播放的,则播放该文件
  3599. this.videoUrl==item.filePath
  3600. this.doPlay(item,0,false,true)
  3601. }
  3602. },
  3603. onSeeOutputPath:(outPutPath:string)=>{
  3604. this.isExtractAcc = !this.isExtractAcc
  3605. this.longItemFilePath = ''
  3606. this.modeType = 0
  3607. this.isShowFileName = true
  3608. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3609. },
  3610. onSliderChange:(value:number)=>{
  3611. if(this.videoUrl!=item.filePath){
  3612. this.videoUrl==item.filePath
  3613. return
  3614. }
  3615. this.isSeekTo = true;
  3616. this.mDestroyPage = false;
  3617. this.showLoadIng();
  3618. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3619. this.seekTo(seekValue + "");
  3620. this.isSeekTo = false;
  3621. },
  3622. onResult:(result: boolean,outPath:string)=>{
  3623. if(result){//如果成功,更新数据
  3624. this.doUpdateData()
  3625. }else{
  3626. ToastUtil.showToast('提取伴奏失败')
  3627. }
  3628. }
  3629. }
  3630. )
  3631. }
  3632. }
  3633. .width('100%')
  3634. .height('100%')
  3635. }
  3636. //AI人声分离
  3637. @Builder
  3638. AiBuilder(item:VideoItem) {
  3639. Scroll() {
  3640. Column() {
  3641. AIVoiceSeparation(
  3642. {
  3643. mVideoItem:item,
  3644. videoUrl:this.videoUrl,
  3645. currentPath:this.currentPath,
  3646. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3647. currentTime:this.currentTime,
  3648. progressValue:this.progressValue,
  3649. onBack:()=>{
  3650. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  3651. this.longItemFilePath = ''
  3652. },
  3653. onPlayOrPause:()=>{
  3654. if(this.videoUrl==item.filePath||this.isPlaying){
  3655. this.playOrPause()
  3656. }else{//如果不是当前播放的,则播放该文件
  3657. this.videoUrl==item.filePath
  3658. this.doPlay(item,0,false,true)
  3659. }
  3660. },
  3661. onPlayPath:(path:string)=>{
  3662. this.videoUrl==path
  3663. const itemP = Utility.getItemByFilePath(this.videoLocalList,path)
  3664. if(itemP)
  3665. this.doPlay(itemP,0,false,true)
  3666. },
  3667. onSeeOutputPath:(outPutPath:string)=>{
  3668. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  3669. this.longItemFilePath = ''
  3670. this.modeType = 0
  3671. this.isShowFileName = true
  3672. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3673. },
  3674. onSliderChange:(value:number)=>{
  3675. if(this.videoUrl!=item.filePath){
  3676. this.videoUrl==item.filePath
  3677. return
  3678. }
  3679. this.isSeekTo = true;
  3680. this.mDestroyPage = false;
  3681. this.showLoadIng();
  3682. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3683. this.seekTo(seekValue + "");
  3684. this.isSeekTo = false;
  3685. },
  3686. onResult:(result: boolean,outPath:string)=>{
  3687. if(result){//如果成功,更新数据
  3688. this.doUpdateData()
  3689. }else{
  3690. ToastUtil.showToast('Ai人声分离失败')
  3691. }
  3692. }
  3693. }
  3694. )
  3695. }
  3696. }
  3697. .width('100%')
  3698. .height('100%')
  3699. }
  3700. //变速变调
  3701. @Builder
  3702. ChangeToneBuilder(item:VideoItem) {
  3703. Scroll() {
  3704. Column() {
  3705. ChangeTone(
  3706. {
  3707. mVideoItem:item,
  3708. currentPath:this.currentPath,
  3709. videoUrl:this.videoUrl,
  3710. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3711. currentTime:this.currentTime,
  3712. progressValue:this.progressValue,
  3713. onBack:()=>{
  3714. this.isChangeTone = !this.isChangeTone
  3715. this.longItemFilePath = ''
  3716. },
  3717. onPlayOrPause:()=>{
  3718. if(this.videoUrl==item.filePath){
  3719. this.playOrPause()
  3720. }else{//如果不是当前播放的,则播放该文件
  3721. this.videoUrl==item.filePath
  3722. this.doPlay(item,0,false,true)
  3723. }
  3724. },
  3725. onSeeOutputPath:(outPutPath:string)=>{
  3726. this.isChangeTone = !this.isChangeTone
  3727. this.longItemFilePath = ''
  3728. this.modeType = 0
  3729. this.isShowFileName = true
  3730. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3731. },
  3732. onSliderChange:(value:number)=>{
  3733. if(this.videoUrl!=item.filePath){
  3734. this.videoUrl==item.filePath
  3735. return
  3736. }
  3737. this.isSeekTo = true;
  3738. this.mDestroyPage = false;
  3739. this.showLoadIng();
  3740. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3741. this.seekTo(seekValue + "");
  3742. this.isSeekTo = false;
  3743. },
  3744. onResult:(result: boolean,outPath:string)=>{
  3745. if(result){//如果成功,更新数据
  3746. this.doUpdateData()
  3747. }else{
  3748. ToastUtil.showToast('变速变调失败')
  3749. }
  3750. }
  3751. }
  3752. )
  3753. }
  3754. }
  3755. .width('100%')
  3756. .height('100%')
  3757. }
  3758. //提取视频中的音频
  3759. @Builder
  3760. extractAudioFromVideoBuilder(item:VideoItem) {
  3761. Scroll() {
  3762. Column() {
  3763. ExtractAudioFromVideo(
  3764. {
  3765. mVideoItem:item,
  3766. currentPath:this.currentPath,
  3767. videoUrl:this.videoUrl,
  3768. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3769. currentTime:this.currentTime,
  3770. progressValue:this.progressValue,
  3771. onBack:()=>{
  3772. this.isExtractAudio = !this.isExtractAudio
  3773. this.longItemFilePath = ''
  3774. },
  3775. onPlayOrPause:()=>{
  3776. if(this.videoUrl==item.filePath){
  3777. this.playOrPause()
  3778. }else{//如果不是当前播放的,则播放该文件
  3779. this.videoUrl==item.filePath
  3780. this.doPlay(item,0,false,true)
  3781. }
  3782. },
  3783. onSeeOutputPath:(outPutPath:string)=>{
  3784. this.isExtractAudio = !this.isExtractAudio
  3785. this.longItemFilePath = ''
  3786. this.modeType = 0
  3787. this.isShowFileName = true
  3788. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3789. },
  3790. onSliderChange:(value:number)=>{
  3791. if(this.videoUrl!=item.filePath){
  3792. this.videoUrl==item.filePath
  3793. return
  3794. }
  3795. this.isSeekTo = true;
  3796. this.mDestroyPage = false;
  3797. this.showLoadIng();
  3798. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3799. this.seekTo(seekValue + "");
  3800. this.isSeekTo = false;
  3801. },
  3802. onResult:(result: boolean,outPath:string)=>{
  3803. if(result){//如果成功,更新数据
  3804. this.doUpdateData()
  3805. }else{
  3806. ToastUtil.showToast('提取音频失败')
  3807. }
  3808. }
  3809. }
  3810. )
  3811. }
  3812. }
  3813. .width('100%')
  3814. .height('100%')
  3815. }
  3816. //合并音频
  3817. @Builder
  3818. MergeAudioBuilder() {
  3819. Scroll() {
  3820. Column() {
  3821. MergeAudio(
  3822. {
  3823. videoUrl:this.videoUrl,
  3824. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3825. currentPath:this.currentPath,
  3826. selectedFiles:this.selectedFiles,
  3827. currentTime:this.currentTime,
  3828. progressValue:this.progressValue,
  3829. onBack:()=>{
  3830. this.isMergeAudio = !this.isMergeAudio
  3831. this.longItemFilePath = ''
  3832. },
  3833. // onPlayPath:(path:string)=>{
  3834. // if(this.videoUrl==item.filePath){
  3835. // this.playOrPause()
  3836. // }else{//如果不是当前播放的,则播放该文件
  3837. // this.videoUrl==item.filePath
  3838. // this.doPlay(item,0,false,true)
  3839. // }
  3840. //
  3841. // },
  3842. onSeeOutputPath:(outPutPath:string)=>{
  3843. this.isMergeAudio = !this.isMergeAudio
  3844. this.longItemFilePath = ''
  3845. this.modeType = 0
  3846. this.isShowFileName = true
  3847. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3848. },
  3849. onResult:(result: boolean,outPath:string)=>{
  3850. if(result){//如果成功,更新数据
  3851. this.doUpdateData()
  3852. }else{
  3853. if(this.selectedFiles.length>=3){
  3854. ToastUtil.showToast('合并数量太多导致失败')
  3855. }else{
  3856. ToastUtil.showToast('合并失败')
  3857. }
  3858. }
  3859. }
  3860. }
  3861. )
  3862. }
  3863. }
  3864. .width('100%')
  3865. .height('100%')
  3866. }
  3867. asyncCurrentPathData() {
  3868. if (this.modeType == 0) {
  3869. workerInstance.postMessage({
  3870. code: 1,
  3871. data1: this.context,
  3872. data2: this.currentPath,
  3873. data3: this.lockPath,
  3874. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  3875. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  3876. });
  3877. }
  3878. }
  3879. // 处理文件选择的函数
  3880. handleFileSelection(item: VideoItem, checked: boolean) {
  3881. if (checked) {
  3882. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  3883. this.selectedFiles.push(item);
  3884. }
  3885. } else {
  3886. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  3887. if (index > -1) {
  3888. this.selectedFiles.splice(index, 1);
  3889. }
  3890. }
  3891. }
  3892. private deleteComponentId: number = 0
  3893. //多选删除文件
  3894. showWarnIsDelete(){
  3895. this.getUIContext().getPromptAction().openCustomDialog({
  3896. builder: () => {
  3897. this.deleteComptentBuilder()
  3898. },
  3899. isModal:true,
  3900. showInSubWindow:false,
  3901. maskColor: Color.Transparent,
  3902. dialogTransition: // 设置弹窗内容显示的过渡效果
  3903. TransitionEffect.translate({ x: 0, y: 290, z: 0 })
  3904. .animation({ duration: 600, curve: Curve.Smooth }),
  3905. maskTransition: // 设置蒙层显示的过渡效果
  3906. TransitionEffect.opacity(0)
  3907. .animation({ duration: 600, curve: Curve.Smooth })
  3908. }).then((dialogId: number) => {
  3909. this.deleteComponentId = dialogId
  3910. })
  3911. .catch((error: BusinessError) => {
  3912. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  3913. })
  3914. }
  3915. @Builder
  3916. deleteComptentBuilder(){
  3917. DeleteComptent({
  3918. selectedFiles:this.selectedFiles,
  3919. onCancel:()=>{
  3920. this.isMultiSelect = false
  3921. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  3922. },
  3923. onDeleteResult:(result: boolean)=>{
  3924. this.isMultiSelect = false
  3925. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  3926. if(result){//如果删除成功,更新数据
  3927. this.selectedFiles = [];
  3928. this.isAllSelected = false
  3929. this.cache.delete(this.currentPath);
  3930. this.getSortedFiles(this.currentPath, true);
  3931. }
  3932. }
  3933. })
  3934. }
  3935. //多选移动文件
  3936. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  3937. Logger.info('onecold showCutDialogForMultipleFiles')
  3938. let mList: Array<string> = []
  3939. let rPath = this.rootPath
  3940. if (isCurrent) {
  3941. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  3942. rPath = this.currentPath
  3943. } else {
  3944. mList = Utility.getNameList(this.dirList);
  3945. rPath = this.rootPath
  3946. }
  3947. let dataBean = new BubbleBean();
  3948. dataBean.data = mList;
  3949. dataBean.color = this.themeColor
  3950. dataBean.onItemClick = (i) => {
  3951. const newDirPath = rPath + '/' + mList[i];
  3952. // Logger.info('newDirPath = ' + newDirPath)
  3953. this.selectedFiles.forEach((item) => {
  3954. const newPath = newDirPath + '/' + item.fileName;
  3955. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  3956. ToastUtil.showToast('移动成功');
  3957. this.table.deleteData(item, () => {
  3958. this.cache.delete(this.currentPath); // 删除原路径缓存
  3959. this.cache.delete(newDirPath); // 删除目标路径缓存
  3960. this.getSortedFiles(this.currentPath, true);
  3961. });
  3962. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  3963. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  3964. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  3965. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3966. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  3967. this.table.insert(newItem, (id: number) => {
  3968. //加入数据库
  3969. });
  3970. }
  3971. }).catch((error: Error) => {
  3972. console.error(error.message);
  3973. });
  3974. });
  3975. this.isMultiSelect = false
  3976. this.selectedFiles = [];
  3977. this.isAllSelected = false
  3978. XPopup.dismissTop();
  3979. };
  3980. let pup: XPopup
  3981. if (this.isDarkMode) {
  3982. pup = XPopup.Builder()
  3983. .setPopupPosition(PopupPosition.TOP)
  3984. .atView(viewId)
  3985. .setBackgroundColor(Color.Black)
  3986. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3987. .show();
  3988. } else {
  3989. pup = XPopup.Builder()
  3990. .setPopupPosition(PopupPosition.TOP)
  3991. .atView(viewId)
  3992. .setBackgroundColor(Color.White)
  3993. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3994. .show();
  3995. }
  3996. }
  3997. /**
  3998. * 加载所有歌单
  3999. */
  4000. async loadAllPlaylists() {
  4001. try {
  4002. this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
  4003. LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
  4004. } catch (error) {
  4005. LogUtil.error('heaunp Failed to load playlists: ' + error.message)
  4006. }
  4007. }
  4008. /**
  4009. * 显示添加到歌单对话框
  4010. */
  4011. async openAddToPlaylistDialog(items: VideoItem | VideoItem[]) {
  4012. const songs = Array.isArray(items) ? items : [items]
  4013. const musicItems = songs.filter(song => song.type !== CommonConstants.TYPE_IS_DIR)
  4014. if (musicItems.length === 0) {
  4015. ToastUtil.showToast('请选择要添加的歌曲')
  4016. return
  4017. }
  4018. // 加载最新的歌单列表
  4019. await this.loadAllPlaylists()
  4020. showAddToPlaylistDialog(
  4021. musicItems,
  4022. this.allPlaylists,
  4023. async (playlistId: string) => {
  4024. // 添加歌曲到歌单
  4025. const success = await this.playlistTable?.addSongsToPlaylist(playlistId,
  4026. musicItems.map(song => song.filePath))
  4027. if (success) {
  4028. const count = musicItems.length
  4029. ToastUtil.showToast(count > 1 ? `已添加 ${count} 首歌曲` : '已添加到歌单')
  4030. // 重新加载歌单列表
  4031. await this.loadAllPlaylists()
  4032. } else {
  4033. ToastUtil.showToast(musicItems.length > 1 ? '选中的歌曲已在该歌单中' : '歌曲已在该歌单中')
  4034. }
  4035. this.longItemFilePath = ''
  4036. if (this.isMultiSelect) {
  4037. this.isMultiSelect = false
  4038. this.isAllSelected = false
  4039. this.selectedFiles = []
  4040. }
  4041. },
  4042. () => {
  4043. LogUtil.info('取消添加到歌单')
  4044. },
  4045. () => {
  4046. // 创建新歌单
  4047. showCreatePlaylistDialog(
  4048. async (name: string, description: string, coverPath?: string) => {
  4049. const success = await this.playlistTable?.createPlaylist(name, description, coverPath)
  4050. if (success) {
  4051. ToastUtil.showToast('歌单创建成功')
  4052. // 重新加载歌单列表并打开添加对话框
  4053. await this.loadAllPlaylists()
  4054. await this.openAddToPlaylistDialog(musicItems)
  4055. } else {
  4056. ToastUtil.showToast('歌单创建失败')
  4057. }
  4058. },
  4059. () => {
  4060. // 取消创建歌单
  4061. }
  4062. )
  4063. }
  4064. )
  4065. }
  4066. doFav(item: VideoItem) {
  4067. LogUtil.info('onecold doFav isFav=' + item.isFav)
  4068. let isFav = 0
  4069. if (Utility.getIsFav(this.favList, item)) {
  4070. isFav = 0
  4071. } else {
  4072. isFav = 1
  4073. }
  4074. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  4075. if (result) {
  4076. if (isFav === 1) {
  4077. ToastUtil.showToast('收藏成功');
  4078. } else {
  4079. ToastUtil.showToast('取消收藏成功');
  4080. }
  4081. this.deleteCache(this.currentPath)
  4082. this.getFavList(false)
  4083. if (this.modeType === 0 && !this.isFavMusic) {
  4084. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  4085. this.getSortedFiles(this.currentPath)
  4086. }
  4087. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  4088. workerInstance.postMessage({ code: 3, data: this.context });
  4089. workerInstance.postMessage({ code: 4, data: this.context });
  4090. }
  4091. })
  4092. }
  4093. //多选复制文件
  4094. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  4095. console.log('onecold showCopyDialogForMultipleFiles');
  4096. let mList: Array<string> = []
  4097. let rPath = this.rootPath
  4098. if (isCurrent) {
  4099. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  4100. rPath = this.currentPath
  4101. } else {
  4102. mList = Utility.getNameList(this.dirList);
  4103. rPath = this.rootPath
  4104. }
  4105. let dataBean = new BubbleBean();
  4106. dataBean.data = mList;
  4107. dataBean.isCopy = true
  4108. dataBean.color = this.themeColor
  4109. dataBean.onItemClick = (i) => {
  4110. const newDirPath = rPath + '/' + mList[i];
  4111. // Logger.info('newDirPath = ' + newDirPath)
  4112. this.selectedFiles.forEach((item) => {
  4113. const newPath = newDirPath + '/' + item.fileName;
  4114. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  4115. ToastUtil.showToast('复制成功');
  4116. this.cache.delete(newDirPath); // 删除目标路径缓存
  4117. this.getSortedFiles(this.currentPath);
  4118. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  4119. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  4120. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  4121. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  4122. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  4123. this.table.insert(newItem, (id: number) => {
  4124. //加入数据库
  4125. });
  4126. }
  4127. }).catch((error: Error) => {
  4128. console.error(error.message);
  4129. });
  4130. });
  4131. this.isMultiSelect = false
  4132. this.selectedFiles = [];
  4133. this.isAllSelected = false
  4134. XPopup.dismissTop();
  4135. };
  4136. let pup: XPopup
  4137. if (this.isDarkMode) {
  4138. pup = XPopup.Builder()
  4139. .setPopupPosition(PopupPosition.TOP)
  4140. .atView(viewId)
  4141. .setBackgroundColor(Color.Black)
  4142. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4143. .show();
  4144. } else {
  4145. pup = XPopup.Builder()
  4146. .setPopupPosition(PopupPosition.TOP)
  4147. .atView(viewId)
  4148. .setBackgroundColor(Color.White)
  4149. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4150. .show();
  4151. }
  4152. }
  4153. @Builder
  4154. private DirItem(item: VideoItem, index?: number) {
  4155. Button({ type: ButtonType.Normal, stateEffect: true }) {
  4156. Row() {
  4157. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  4158. $r('app.media.music_group'))
  4159. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4160. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4161. .fillColor(this.themeColor)// .fontSize(33)
  4162. .alt($r('app.media.music_group'))
  4163. .borderRadius('100%')
  4164. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4165. // .autoResize(true) // 重采样,可减少内存占用
  4166. .clip(true)
  4167. .sourceSize({width:38, height:38})
  4168. .margin({ left: 20, top: 8, bottom: 8 })
  4169. Column() {
  4170. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4171. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4172. .maxLines(1)// .width('88%')
  4173. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4174. .animation({
  4175. duration: 555,
  4176. curve: 'ease-in-out',
  4177. })
  4178. .transition({
  4179. type: TransitionType.Insert,
  4180. opacity: 0,
  4181. translate: { x: 160 }
  4182. })
  4183. .margin({ left: 10, right: 20 })
  4184. .fontColor($r('app.color.text_color'))
  4185. Row() {
  4186. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  4187. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4188. .padding({ top: 8 })
  4189. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  4190. .fontColor($r('app.color.text_color'))
  4191. .margin({ left: 10 })
  4192. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  4193. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4194. .padding({ top: 8 })
  4195. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  4196. .fontColor($r('app.color.text_color'))
  4197. .margin({ left: 10 })
  4198. Blank()
  4199. }
  4200. }
  4201. .height('100%')
  4202. .layoutWeight(1)
  4203. .justifyContent(FlexAlign.Center)
  4204. .alignItems(HorizontalAlign.Start)
  4205. Blank()
  4206. Image($r('app.media.arrow_right'))
  4207. .height(25)
  4208. .alignSelf(ItemAlign.Center)
  4209. .id(item.filePath)
  4210. .visibility(this.isShowAlphaBet?Visibility.None:Visibility.Visible)
  4211. .animation({ duration: 300, curve: Curve.Ease })
  4212. }
  4213. }
  4214. .backgroundColor(Color.Transparent)
  4215. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  4216. .width('98%')
  4217. .reuseId('dir_item')
  4218. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  4219. .opacity(this.opacityItem) // 绑定透明度
  4220. }
  4221. isShowDir(dirName: string) {
  4222. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  4223. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  4224. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  4225. if (dirName === undefined) {
  4226. return true
  4227. }
  4228. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  4229. return this.isShowSimi
  4230. }
  4231. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  4232. return this.isShowFAV
  4233. }
  4234. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  4235. return this.isShowHistory
  4236. }
  4237. return true
  4238. }
  4239. @State opacityItem: number = 1; // 控制透明度的状态变量
  4240. @Builder
  4241. private MusicItem(item: VideoItem, index?: number) {
  4242. Button({ type: ButtonType.Normal, stateEffect: true }) {
  4243. Row() {
  4244. Stack() {
  4245. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  4246. .fillColor(this.themeColor)
  4247. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4248. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4249. .alt($r('app.media.music_red'))
  4250. .borderRadius(this.isCoverRectangle?13:'100%')
  4251. .clip(true)
  4252. .draggable(false)
  4253. .sourceSize({width:38, height:38})
  4254. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4255. // .autoResize(true) // 重采样,可减少内存占用
  4256. .opacity(this.opacityItem)// 绑定透明度
  4257. .margin({ left: 20 })
  4258. .gesture(LongPressGesture()
  4259. .onAction(async () => {
  4260. //如果是专辑和艺术家的首页,不能长按
  4261. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4262. return
  4263. //如果是我的收藏 最近播放等也不能长按
  4264. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4265. item.name === LocalMusic.STR_HISTORY_MUSIC
  4266. )
  4267. return
  4268. this.longItemFilePath = item.filePath
  4269. this.tempLyricContent = await this.getLyricContent(item)
  4270. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4271. })
  4272. .onActionEnd((event: GestureEvent) => {
  4273. }))
  4274. .onClick(()=>{
  4275. if (this.isMultiSelect) {
  4276. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4277. this.handleFileSelection(item, !isChecked);
  4278. } else {
  4279. this.doPlay(item,index)
  4280. this.setShowPlayTrue()
  4281. }
  4282. })
  4283. }
  4284. Column() {
  4285. Column() {
  4286. Text(this.isShowFileName?item.fileName :item.name)
  4287. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4288. .maxLines(1)
  4289. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4290. .animation({
  4291. duration: 555,
  4292. curve: 'Linear',
  4293. })
  4294. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4295. $r('app.color.text_color'))
  4296. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4297. .padding({right:25})
  4298. .bindPopup(this.longItemFilePath === item.filePath, {
  4299. builder: this.MenuBuilder(item,index,item.filePath),
  4300. placement: Placement.Top,
  4301. // autoCancel: true,
  4302. mask: {color:'#33000000'},
  4303. // popupColor: Color.Yellow,
  4304. enableArrow: false,//是否显示箭头
  4305. showInSubWindow: false,
  4306. onStateChange: (e) => {
  4307. if (!e.isVisible) {
  4308. this.longItemFilePath = ''
  4309. this.tempLyricContent = ''
  4310. }
  4311. }
  4312. })
  4313. .gesture(LongPressGesture()
  4314. .onAction(async () => {
  4315. //如果是专辑和艺术家的首页,不能长按
  4316. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4317. return
  4318. //如果是我的收藏 最近播放等也不能长按
  4319. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4320. item.name === LocalMusic.STR_HISTORY_MUSIC
  4321. )
  4322. return
  4323. this.longItemFilePath = item.filePath
  4324. this.tempLyricContent = await this.getLyricContent(item)
  4325. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4326. })
  4327. .onActionEnd((event: GestureEvent) => {
  4328. })
  4329. )
  4330. Row() {
  4331. Column(){
  4332. Text(item.md5Str?.includes('Lossless')?
  4333. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4334. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  4335. .padding({ top: 3,right:6,left:6,bottom:3 })
  4336. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4337. $r('app.color.text_color'))
  4338. .fontWeight(500)
  4339. .borderRadius(12)
  4340. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  4341. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4342. .backgroundColor('#FFC107')
  4343. }
  4344. .padding({ top: 8 })
  4345. Text(StrUtil.isEmpty(item.artist) ? item.duration
  4346. :this.twoFingerType==2? item.artist +' ' + item.duration
  4347. : item.artist + ' ' + item?.duration)
  4348. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4349. .padding({ top: 8 ,right:25})
  4350. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  4351. .maxLines(1)
  4352. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4353. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4354. Color.Gray)
  4355. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4356. Blank()
  4357. Text(this.isShowFileName?item.duration:item.size)
  4358. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4359. .padding({ top: 8 })
  4360. .maxLines(1)
  4361. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  4362. ? Visibility.Visible : Visibility.None)
  4363. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4364. Color.Gray)
  4365. .margin({ left: StrUtil.isEmpty(item.artist) ?0:10 })
  4366. }
  4367. .gesture(LongPressGesture()
  4368. .onAction(async () => {
  4369. //如果是专辑和艺术家的首页,不能长按
  4370. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4371. return
  4372. //如果是我的收藏 最近播放等也不能长按
  4373. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4374. item.name === LocalMusic.STR_HISTORY_MUSIC
  4375. )
  4376. return
  4377. this.longItemFilePath = item.filePath
  4378. this.tempLyricContent = await this.getLyricContent(item)
  4379. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4380. })
  4381. .onActionEnd((event: GestureEvent) => {
  4382. })
  4383. )
  4384. }
  4385. .height('100%')
  4386. .width('100%')
  4387. .margin({ right: 10 })
  4388. .justifyContent(FlexAlign.Center)
  4389. .alignItems(HorizontalAlign.Start)
  4390. }
  4391. .height('100%')
  4392. .margin({ left: 5 })
  4393. .layoutWeight(1)
  4394. Column() {
  4395. Checkbox({ name: 'checkbox' + index })
  4396. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  4397. .selectedColor(this.themeColor)
  4398. .shape(CheckBoxShape.CIRCLE)
  4399. .opacity(this.isMultiSelect ? 1 : 0)
  4400. .animation({
  4401. duration: 666,
  4402. curve: 'Smooth' // 可选动画曲线
  4403. })
  4404. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  4405. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  4406. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  4407. .width(22)
  4408. .height(22)
  4409. ImageAnimator()
  4410. .images(this.imagesF)// 动画数组
  4411. .duration(1000)// 持续
  4412. .state(this.animationState)// 动画状态
  4413. .fillMode(FillMode.Forwards)
  4414. .width(18)
  4415. .margin({ right: 20, top: 8, bottom: 8 })
  4416. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  4417. Visibility.None)
  4418. .height(18)
  4419. .iterations(-1) // 播放次数
  4420. }
  4421. }
  4422. }
  4423. .backgroundColor(Color.Transparent)
  4424. .width('100%')
  4425. .reuseId('file_item')
  4426. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  4427. }
  4428. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  4429. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  4430. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  4431. direction: Direction.Ltr,
  4432. buttonPadding:{top:12,bottom:12},
  4433. backgroundColor: Color.Transparent,
  4434. fontSize:14,
  4435. selectedFontSize:15,
  4436. selectedFontColor:Color.White,
  4437. selectedBackgroundColor: this.themeColor,
  4438. localizedTextPadding: {
  4439. end: LengthMetrics.vp(20),
  4440. start: LengthMetrics.vp(20)
  4441. }
  4442. })
  4443. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  4444. //当胶囊按钮的选择发生变化时调用此函数
  4445. capsuleSelectedIndexesChanged() {
  4446. this.modeType = this.tabSelectedIndexes[0]
  4447. }
  4448. @Builder
  4449. tabTitle() {
  4450. Column({ space: 2 }) {
  4451. SegmentButton({ options: this.tabOptions, selectedIndexes: $tabSelectedIndexes })
  4452. Line()
  4453. .width('100%')
  4454. .height(1)
  4455. .backgroundColor($r('app.color.index_background'))
  4456. .opacity(this.barOpacity)
  4457. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  4458. }
  4459. .width('100%')
  4460. .height(this.topBarHeight)
  4461. .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  4462. }
  4463. // @Builder
  4464. // tabTitle() {
  4465. // Column() {
  4466. // // 使用 Stack 布局来实现绝对定位效果
  4467. // Stack() {
  4468. // // 背景动画容器
  4469. // Row() {
  4470. // ForEach(this.tabs, (i: string, index) => {
  4471. // Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  4472. // Flex()
  4473. // .backgroundColor(this.isDarkMode ? $r('app.color.tab_item_bg') : this.themeColor)
  4474. // .borderRadius(20)
  4475. // .padding(10)
  4476. // .margin(6)
  4477. // .width('100%')
  4478. // .height('100%')
  4479. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  4480. // .visibility(this.modeType === index ? Visibility.Visible : Visibility.None)
  4481. // .opacity(this.modeType === index ? 1 : 0)
  4482. // .animation({
  4483. // duration: 666,
  4484. // playMode: PlayMode.Normal,
  4485. // curve: 'ease-in-out'
  4486. // });
  4487. // }
  4488. // .layoutWeight(1)
  4489. // .margin({
  4490. // left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5,
  4491. // right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5, bottom: 1
  4492. // });
  4493. // });
  4494. // }
  4495. // .width('100%')
  4496. // .height(50);
  4497. //
  4498. // // 导航栏容器
  4499. // Row() {
  4500. // ForEach(this.tabs, (item: string, index) => {
  4501. // Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  4502. // Text(item)
  4503. // .fontSize(16)
  4504. // .fontColor(this.modeType === index ? Color.White : $r('app.color.text_color'))
  4505. // .padding(15)
  4506. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  4507. // .onClick(() => {
  4508. // this.modeType = index;
  4509. // // this.onModeChange();
  4510. // });
  4511. // }
  4512. // .layoutWeight(1)
  4513. // .stateStyles({
  4514. // pressed: { opacity: 0.6 } // 按压反馈
  4515. // });
  4516. // });
  4517. // }
  4518. // .width('100%')
  4519. // .height(this.topBarHeight)
  4520. // .opacity(this.barOpacity)
  4521. // .backgroundColor(Color.Transparent);
  4522. //
  4523. // }
  4524. // .width('100%')
  4525. // .height(this.topBarHeight)
  4526. // .opacity(this.barOpacity)
  4527. //
  4528. // Line()
  4529. // .width('100%')
  4530. // .height(1)
  4531. // .backgroundColor($r('app.color.index_background'))
  4532. // .opacity(this.barOpacity)
  4533. // .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  4534. // }
  4535. // .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  4536. // }
  4537. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  4538. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  4539. isShowCoverHeader() {
  4540. if (!this.isShowHeader) {
  4541. return false
  4542. }
  4543. if (this.modeType == 0) {
  4544. if (this.isHistory || this.isFavMusic) {
  4545. return true
  4546. }
  4547. if (this.currentPath != this.rootPath) {
  4548. return true
  4549. }
  4550. }
  4551. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  4552. }
  4553. getCoverTitleBg(): ResourceStr | image.PixelMap {
  4554. if (this.isCustomizeBg) {
  4555. return ('rgba(255,255,255,0.2)')
  4556. }
  4557. if (this.isDarkMode) {
  4558. return $r('app.color.user_center_card_background')
  4559. }
  4560. return this.currentTitleCover
  4561. }
  4562. // 第二步:popup构造器定义弹框内容
  4563. @Builder popupBuilder() {
  4564. Column({ space: 2 }) {
  4565. Text('友情提示:双指缩放可以放大缩小列表')
  4566. .fontSize(12)
  4567. .fontWeight(FontWeight.Regular)
  4568. .fontColor($r('app.color.text_color'))
  4569. }
  4570. .justifyContent(FlexAlign.SpaceAround)
  4571. .width(220)
  4572. .height(55)
  4573. .padding(15)
  4574. }
  4575. //搜索功能的实现
  4576. @State searchText: string = ''; // 用户输入内容
  4577. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  4578. @State isSearchMode: boolean = false
  4579. // 实时搜索逻辑(带防抖)
  4580. private onSearchInput(value: string) {
  4581. this.searchText = value.trim();
  4582. let mSearchList: Array<VideoItem> = []
  4583. switch (this.modeType) {
  4584. case 0:
  4585. case 1:
  4586. mSearchList = this.mediaKuList
  4587. break;
  4588. case 2:
  4589. mSearchList = this.artistList
  4590. break;
  4591. case 3:
  4592. mSearchList = this.albumList
  4593. break;
  4594. default :
  4595. mSearchList = this.videoLocalList
  4596. break;
  4597. }
  4598. // 新增条件判断:空输入时显示所有数据
  4599. if (this.searchText === '') {
  4600. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  4601. } else {
  4602. this.filteredList = mSearchList.filter((item: VideoItem) => {
  4603. //支持模糊匹配和艺术家 专辑匹配
  4604. const regex = new RegExp(this.searchText.toLowerCase().replace(/\s+/g, '.*'), 'i');
  4605. return regex.test(item.name.toLowerCase())||
  4606. regex.test(item.fileName?.toLowerCase() ?? "") ||
  4607. regex.test(item.artist?.toLowerCase() ?? "") ||
  4608. regex.test(item.album?.toLowerCase() ?? "")
  4609. });
  4610. }
  4611. this.updateListData(this.filteredList);
  4612. // this.isSearchMode = false; // 根据业务需求决定是否启用
  4613. }
  4614. @State dragItem: number = -1
  4615. @State scaleItem: number = -1
  4616. @State neighborItem: number = -1
  4617. @State neighborScale: number = -1
  4618. @State offsetY: number = 0
  4619. private dragRefOffset: number = 0
  4620. private ITEM_INTV: number = 78
  4621. scaleSelect(item: number): number {
  4622. if (this.scaleItem === item) {
  4623. return 1.05
  4624. } else if (this.neighborItem === item) {
  4625. return this.neighborScale
  4626. } else {
  4627. return 1
  4628. }
  4629. }
  4630. itemMove(index: number, newIndex: number): void {
  4631. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  4632. return;
  4633. }
  4634. let tmp = this.videoLocalList.splice(index, 1);
  4635. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  4636. this.dataSource.pushArrayData(this.videoLocalList)
  4637. if(this.modeType==4&&this.playlistTable){
  4638. updateAllSongsSortOrder(this.playlistTable, this.videoLocalList,this.currentSongListID)
  4639. }
  4640. }
  4641. //瀑布流布局 支持双指缩放
  4642. @State columns: number = 2;
  4643. @State waterFlowScale: number = 1;
  4644. @State imageScale: number = 1;
  4645. @State waterFlowOpacity: number = 1;
  4646. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  4647. private columnChanged: boolean = false;
  4648. private oldColumn: number = this.columns;
  4649. private pinchTime: number = 0;
  4650. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  4651. changeColumns(scale: number) {
  4652. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  4653. this.columns--;
  4654. this.columnChanged = true;
  4655. } else if (scale < 1 && this.columns < 4) {
  4656. this.columns++;
  4657. this.columnChanged = true;
  4658. }
  4659. }
  4660. @Builder
  4661. getWaterView(){
  4662. Scroll(this.scroller) {
  4663. Column() {
  4664. Blank().height(this.topSafeHeight + 55)
  4665. WaterFlow({
  4666. scroller:this.waterScroller,
  4667. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  4668. }) {
  4669. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  4670. FlowItem() {
  4671. this.MusicWaterCardItem(item,index)
  4672. }
  4673. .width('100%')
  4674. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  4675. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  4676. {
  4677. preview: MenuPreviewMode.IMAGE,
  4678. previewAnimationOptions: { scale: [0.8, 1.0] },
  4679. })
  4680. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  4681. {
  4682. preview: MenuPreviewMode.IMAGE,
  4683. previewAnimationOptions: { scale: [0.8, 1.0] },
  4684. })
  4685. .transition(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }))
  4686. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  4687. TransitionEffect.scale({ x: 0, y: 0 })))
  4688. .gesture(
  4689. GestureGroup(GestureMode.Exclusive,
  4690. SwipeGesture({ direction: SwipeDirection.Horizontal })
  4691. .onAction((event: GestureEvent) => {
  4692. if (event) {
  4693. // this.sideBarController.openSideBar()
  4694. }
  4695. }),
  4696. TapGesture({ count: 1, fingers: 1 })
  4697. .onAction(async () => {
  4698. })
  4699. )
  4700. )
  4701. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  4702. }
  4703. // .columnsTemplate('repeat(auto-fit, 160)')
  4704. .id('waterflow') // 设置id用于截图
  4705. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  4706. .columnsGap(12) // 列间距
  4707. .rowsGap(16) // 行间距
  4708. .cachedCount(6)
  4709. .padding({bottom:this.bottomBarHeight+10})
  4710. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4711. .animation({ duration: 500, curve: Curve.Ease }))
  4712. .scrollBar(BarState.Off)
  4713. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  4714. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  4715. .edgeEffect(EdgeEffect.Spring, { alwaysEnabled: true })
  4716. .width('90%')
  4717. .height('100%')
  4718. .opacity(this.waterFlowOpacity)
  4719. .scale({
  4720. x: this.waterFlowScale,
  4721. y: this.waterFlowScale,
  4722. centerX: 0,
  4723. centerY: 0
  4724. })
  4725. .onAppear(() => {
  4726. this.scroller.scrollEdge(Edge.Top)
  4727. })
  4728. .nestedScroll({
  4729. scrollForward: NestedScrollMode.PARENT_FIRST,
  4730. scrollBackward: NestedScrollMode.SELF_FIRST
  4731. })
  4732. .priorityGesture(
  4733. PinchGesture()
  4734. .onActionStart((event: GestureEvent) => {
  4735. // 双指捏合手势识别成功时截图
  4736. this.pinchTime = event.timestamp;
  4737. this.columnChanged = false;
  4738. this.oldColumn = this.columns;
  4739. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  4740. if (error) {
  4741. console.info('error:' + JSON.stringify(error));
  4742. return;
  4743. }
  4744. this.waterFlowSnapshot = pixmap;
  4745. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  4746. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  4747. if (this.oldColumn ===4) {
  4748. this.twoFingerType =3
  4749. this.isGridMusic = true
  4750. }else if (this.oldColumn ===1) {
  4751. this.twoFingerType =1
  4752. this.isGridMusic = false
  4753. }
  4754. return;
  4755. }
  4756. })
  4757. })
  4758. .onActionUpdate((event: GestureEvent) => {
  4759. // 手势更新:处理缩放逻辑和视觉效果
  4760. // 边界限制:防止超出列数范围时继续缩放
  4761. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  4762. return;
  4763. }
  4764. // 节流处理:避免过于频繁的更新,提升性能
  4765. if (event.timestamp - this.pinchTime < 10000000) {
  4766. return;
  4767. }
  4768. this.pinchTime = event.timestamp;
  4769. this.waterFlowScale = event.scale;
  4770. this.imageScale = event.scale;
  4771. // 根据缩放比例设置WaterFlow透明度
  4772. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  4773. this.waterFlowOpacity *= 3;
  4774. if (!this.columnChanged) {
  4775. this.changeColumns(event.scale);
  4776. }
  4777. // 列数改变后的缩放比例调整:避免出现空白区域
  4778. if (this.columnChanged) {
  4779. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  4780. // 限制缩放范围,确保视觉效果自然
  4781. if (event.scale < 1) {
  4782. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  4783. } else {
  4784. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  4785. }
  4786. }
  4787. })
  4788. .onActionEnd((event: GestureEvent) => {
  4789. // 手势结束:执行归位动画并保存状态
  4790. // 执行归位动画:平滑过渡到正常状态
  4791. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  4792. this.waterFlowScale = 1;
  4793. this.waterFlowOpacity = 1;
  4794. })
  4795. // 持久化保存当前列数:下次启动时恢复
  4796. PreferencesUtil.putSync('lastColumns', this.columns);
  4797. })
  4798. )
  4799. //允许拖拽音乐和视频到List或Grid上自动导入视频
  4800. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  4801. .onDrop((event?: DragEvent) => {
  4802. try {
  4803. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  4804. if (dragData !== undefined) {
  4805. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  4806. if (records.length > 0) {
  4807. for (let i = 0; i < records.length; i++) {
  4808. let types = records[i].getTypes();
  4809. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  4810. const fileUriUds =
  4811. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  4812. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  4813. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  4814. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  4815. this.targetFile = fileUriUds.oriUri;
  4816. this.saveVideoDatas([this.targetFile])
  4817. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  4818. }
  4819. }
  4820. }
  4821. } else {
  4822. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  4823. }
  4824. } else {
  4825. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  4826. }
  4827. } catch (error) {
  4828. const err = error as BusinessError;
  4829. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  4830. }
  4831. })
  4832. }
  4833. }
  4834. .scrollBar(BarState.Off)
  4835. }
  4836. //瀑布流卡片布局
  4837. @Builder
  4838. private MusicWaterCardItem(item: VideoItem, index: number) {
  4839. Button({ type: ButtonType.Normal, stateEffect: false }) {
  4840. Stack() {
  4841. Column() {
  4842. Image(item.pixelMapPath)
  4843. .backgroundImageSize(ImageSize.Auto)
  4844. .borderRadius({
  4845. topLeft: 12,
  4846. topRight : 12,
  4847. bottomLeft: 0,
  4848. bottomRight: 0
  4849. })
  4850. .draggable(false)// 禁止长按手势拖动
  4851. .autoResize(true) // 重采样,可减少内存占用
  4852. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4853. .width('100%')
  4854. .height('auto')
  4855. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  4856. .objectFit(ImageFit.Auto)
  4857. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  4858. height: '99%' ,
  4859. dragBar: true,
  4860. onDisappear: () => {
  4861. this.longItemFilePath = '';
  4862. this.tempLyricContent = ''
  4863. },
  4864. showClose: true,
  4865. preferType: SheetType.CENTER ,
  4866. title: { title: '编辑标签' }
  4867. })
  4868. .draggable(false)
  4869. .opacity(this.opacityItem)// 绑定透明度
  4870. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4871. // .animation({ duration: 500, curve: Curve.Ease }))
  4872. .animation({
  4873. duration: 666,
  4874. curve: 'ease-in-out' // 可选动画曲线
  4875. })
  4876. .margin({
  4877. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4878. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4879. })
  4880. Column() {
  4881. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4882. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  4883. .maxLines(1)
  4884. .fontWeight(FontWeight.Bold)
  4885. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4886. .animation({
  4887. duration: 555,
  4888. curve: 'Linear',
  4889. })
  4890. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  4891. height: '95%',
  4892. dragBar: true,
  4893. showClose: true,
  4894. onDisappear: () => {
  4895. this.longItemFilePathDetail = '';
  4896. },
  4897. blurStyle:BlurStyle.Thin,
  4898. backgroundColor:Color.Transparent,
  4899. preferType: SheetType.CENTER ,
  4900. title: { title: '详情' }
  4901. })
  4902. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4903. $r('app.color.text_color'))
  4904. Column() {
  4905. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  4906. .fontSize(11)
  4907. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  4908. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4909. .fontColor($r('app.color.text_color'))
  4910. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  4911. .fontSize(11)
  4912. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  4913. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4914. .fontColor($r('app.color.text_color'))
  4915. Row(){
  4916. Column(){
  4917. Text(item.md5Str?.includes('Lossless')?
  4918. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4919. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  4920. .padding({ top: 3,right:6,left:6,bottom:3 })
  4921. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4922. $r('app.color.text_color'))
  4923. .fontWeight(500)
  4924. .borderRadius(12)
  4925. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4926. .backgroundColor('#FFC107')
  4927. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  4928. }
  4929. .margin({ top: 2 ,right:6})
  4930. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  4931. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  4932. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  4933. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  4934. .maxLines(1)
  4935. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4936. .margin({ top: 2})
  4937. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  4938. || item.type == CommonConstants.TYPE_IS_ALBUM
  4939. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4940. .fontWeight(FontWeight.Medium)
  4941. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4942. $r('app.color.text_color'))
  4943. }
  4944. }
  4945. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  4946. }
  4947. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  4948. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  4949. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  4950. .width('100%')
  4951. .justifyContent(FlexAlign.Center)
  4952. .margin({
  4953. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4954. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4955. })
  4956. }
  4957. .width('100%')
  4958. .borderRadius(12)
  4959. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  4960. .backgroundImageSize({ height: '100%', width: '100%' })
  4961. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  4962. .animation({ curve: Curve.Sharp, duration: 300 })
  4963. Checkbox({ name: 'checkbox' + index })
  4964. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  4965. .selectedColor(this.themeColor)
  4966. .shape(CheckBoxShape.CIRCLE)
  4967. .opacity(this.isMultiSelect ? 1 : 0)
  4968. .animation({
  4969. duration: 666,
  4970. curve: 'Smooth' // 可选动画曲线
  4971. })
  4972. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  4973. Visibility.None)
  4974. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  4975. .margin({ left: 20, top: 8, bottom: 8 })
  4976. .width(38)
  4977. .height(38)
  4978. }
  4979. }
  4980. .backgroundColor(Color.Transparent)
  4981. .width('100%')
  4982. .height('auto')
  4983. .padding({top:2})
  4984. .shadow({
  4985. radius: 10,
  4986. type: ShadowType.BLUR,
  4987. color: 'on_primary'
  4988. })
  4989. .reuseId('card_item')
  4990. .onClick(() => {
  4991. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  4992. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4993. this.handleFileSelection(item, !isChecked);
  4994. } else {
  4995. this.doPlay(item, index)
  4996. }
  4997. })
  4998. }
  4999. // Grid布局的开始
  5000. private dragRefOffSetX: number = 0;
  5001. private dragRefOffSetY: number = 0;
  5002. private FIX_VP_X: number = 180;
  5003. private FIX_VP_Y: number = 84;
  5004. isDraggable(index: number): boolean {
  5005. return index >= 0;
  5006. }
  5007. getRowEnd(item: number) {
  5008. if (item.toString() === '0') {
  5009. return 1;
  5010. } else {
  5011. return 0;
  5012. }
  5013. }
  5014. isInLeft(index: number) {
  5015. return index % 2 == 0;
  5016. }
  5017. down(index: number): void {
  5018. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  5019. return;
  5020. }
  5021. this.offsetY -= this.FIX_VP_Y;
  5022. this.dragRefOffSetY += this.FIX_VP_Y;
  5023. this.itemMove(index, index + 1);
  5024. }
  5025. up(index: number): void {
  5026. if (!this.isDraggable(index - 2)) {
  5027. return;
  5028. }
  5029. this.offsetY += this.FIX_VP_Y;
  5030. this.dragRefOffSetY -= this.FIX_VP_Y;
  5031. this.itemMove(index, index - 1);
  5032. }
  5033. left(index: number): void {
  5034. if (this.isInLeft(index)) {
  5035. return;
  5036. }
  5037. if (!this.isDraggable(index - 1)) {
  5038. return;
  5039. }
  5040. this.offsetX += this.FIX_VP_X;
  5041. this.dragRefOffSetX -= this.FIX_VP_X;
  5042. this.itemMove(index, index - 1)
  5043. }
  5044. right(index: number): void {
  5045. if (!this.isInLeft(index)) {
  5046. return;
  5047. }
  5048. if (!this.isDraggable(index + 1)) {
  5049. return;
  5050. }
  5051. this.offsetX -= this.FIX_VP_X;
  5052. this.dragRefOffSetX += this.FIX_VP_X;
  5053. this.itemMove(index, index + 1)
  5054. }
  5055. private scroller: Scroller = new Scroller();
  5056. private waterScroller: Scroller = new Scroller();
  5057. @State startIndex: number = 0
  5058. @State endIndex: number = 0
  5059. @State scaleValue: number = 1
  5060. @State pinchValue: number = 1
  5061. layoutOptionsForHeader: GridLayoutOptions = {
  5062. regularSize: [1, 1], // 只支持[1, 1]
  5063. irregularIndexes: [0], // 索引为0的GridItem占用一行
  5064. };
  5065. @Builder
  5066. getGridView() {
  5067. Grid(this.scroller, this.layoutOptionsForHeader) {
  5068. GridItem() {
  5069. Column(){
  5070. Blank().height(this.topSafeHeight + 45)
  5071. }
  5072. }
  5073. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5074. GridItem() {
  5075. Stack({ alignContent: Alignment.Center }) {
  5076. this.MusicItemGrid(item, index)
  5077. }
  5078. }
  5079. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  5080. {
  5081. preview: MenuPreviewMode.IMAGE,
  5082. previewAnimationOptions: { scale: [0.8, 1.0] },
  5083. })
  5084. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  5085. {
  5086. preview: MenuPreviewMode.IMAGE,
  5087. previewAnimationOptions: { scale: [0.8, 1.0] },
  5088. })
  5089. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  5090. TransitionEffect.scale({ x: 0, y: 0 })))
  5091. .clickEffect({ level: ClickEffectLevel.LIGHT })
  5092. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  5093. .zIndex(this.dragItem === index ? 1 : 0)
  5094. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  5095. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5096. }
  5097. .width('94%')
  5098. .height('100%')
  5099. .editMode(true)
  5100. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  5101. .animation({ duration: 500, curve: Curve.Ease }))
  5102. .padding({bottom:this.bottomBarHeight+this.bottomSafeHeight+10})
  5103. .reuseId('grid_item')
  5104. .layoutWeight(1)
  5105. .scrollBar(BarState.Off)
  5106. .supportAnimation(true)
  5107. .cachedCount(this.twoFingerType==1?5:this.twoFingerType==2?4:3)
  5108. .columnsTemplate(
  5109. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  5110. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  5111. )
  5112. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  5113. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  5114. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5115. .gesture(PinchGesture({ fingers: 2 })
  5116. .onActionEnd((event: GestureEvent) => {
  5117. this.setGridTwoFingers()
  5118. })
  5119. .onActionUpdate(e => {
  5120. this.scaleValue = this.pinchValue * e.scale
  5121. })
  5122. .onActionStart(e => {
  5123. }))
  5124. .enableScrollInteraction(true)
  5125. .onScrollIndex((start: number, end: number) => {
  5126. this.startIndex = start
  5127. this.endIndex = end
  5128. })
  5129. .onScrollFrameBegin((offset: number) => {
  5130. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  5131. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  5132. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  5133. if (this.isScrollHide) {
  5134. this.setBarHeightHide2(offset)
  5135. } else {
  5136. this.setBarHeightNormal()
  5137. }
  5138. } else {
  5139. this.setBarHeightHide(offset)
  5140. }
  5141. return { offsetRemain: offset };
  5142. })
  5143. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  5144. .onDrop((event?: DragEvent) => {
  5145. try {
  5146. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  5147. if (dragData !== undefined) {
  5148. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  5149. if (records.length > 0) {
  5150. for (let i = 0; i < records.length; i++) {
  5151. let types = records[i].getTypes();
  5152. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  5153. const fileUriUds =
  5154. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  5155. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  5156. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  5157. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  5158. this.targetFile = fileUriUds.oriUri;
  5159. this.saveVideoDatas([this.targetFile])
  5160. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  5161. }
  5162. }
  5163. }
  5164. } else {
  5165. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  5166. }
  5167. } else {
  5168. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  5169. }
  5170. } catch (error) {
  5171. const err = error as BusinessError;
  5172. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  5173. }
  5174. })
  5175. }
  5176. @State targetFile: string = '';
  5177. setGridTwoFingers() {
  5178. this.pinchValue = this.scaleValue;
  5179. Logger.info('this.pinchValue = ' + this.pinchValue);
  5180. if (this.pinchValue >= 1) {
  5181. this.twoFingerType++
  5182. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  5183. if(this.twoFingerType >= 4){
  5184. this.twoFingerType = 4//切换成瀑布流
  5185. this.columns = 4
  5186. }
  5187. } else {
  5188. this.twoFingerType--
  5189. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  5190. if (this.twoFingerType < 1) {
  5191. this.twoFingerType = 3
  5192. this.isGridMusic = false
  5193. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5194. }
  5195. }
  5196. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5197. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5198. this.pinchValue = 1;
  5199. this.scaleValue = 1;
  5200. }
  5201. @State longItemFilePath: string = ''
  5202. @State tempLyricContent: string = ''
  5203. @State editingItem: VideoItem | null = null
  5204. @Builder
  5205. private MusicItemGrid(item: VideoItem, index: number) {
  5206. Button({ type: ButtonType.Normal, stateEffect: false }) {
  5207. Stack() {
  5208. Column() {
  5209. Image(item.pixelMapPath)
  5210. .height(this.getGridHeight())
  5211. .width(this.getGridWight())
  5212. .draggable(false)
  5213. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  5214. .autoResize(true) // 重采样,可减少内存占用
  5215. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  5216. .clip(true)
  5217. .borderRadius({
  5218. topLeft: 12,
  5219. topRight: 12,
  5220. bottomLeft: 0,
  5221. bottomRight: 0
  5222. })
  5223. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  5224. height: '99%' ,
  5225. dragBar: true,
  5226. onDisappear: () => {
  5227. this.longItemFilePath = '';
  5228. this.tempLyricContent = ''
  5229. },
  5230. showClose: true,
  5231. preferType: SheetType.CENTER ,
  5232. title: { title: '编辑标签' }
  5233. })
  5234. .draggable(false)
  5235. .opacity(this.opacityItem)// 绑定透明度
  5236. .animation({
  5237. duration: 666,
  5238. curve: 'ease-in-out' // 可选动画曲线
  5239. })
  5240. .margin({
  5241. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5242. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5243. })
  5244. Column() {
  5245. Text(this.isShowFileName&&item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5246. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5247. .maxLines(1)
  5248. .fontWeight(FontWeight.Bold)
  5249. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5250. .animation({
  5251. duration: 555,
  5252. curve: 'Linear',
  5253. })
  5254. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  5255. height: '95%',
  5256. dragBar: true,
  5257. showClose: true,
  5258. onDisappear: () => {
  5259. this.longItemFilePathDetail = '';
  5260. },
  5261. blurStyle:BlurStyle.Thin,
  5262. backgroundColor:Color.Transparent,
  5263. preferType: SheetType.CENTER ,
  5264. title: { title: '详情' }
  5265. })
  5266. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5267. $r('app.color.text_color'))
  5268. Column() {
  5269. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  5270. .fontSize(11)
  5271. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  5272. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5273. .fontColor($r('app.color.text_color'))
  5274. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  5275. .fontSize(11)
  5276. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  5277. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5278. .fontColor($r('app.color.text_color'))
  5279. Row(){
  5280. Column(){
  5281. Text(item.md5Str?.includes('Lossless')?
  5282. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5283. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5284. .padding({ top: 3,right:6,left:6,bottom:3 })
  5285. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5286. $r('app.color.text_color'))
  5287. .fontWeight(500)
  5288. .borderRadius(12)
  5289. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5290. .backgroundColor('#FFC107')
  5291. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  5292. }
  5293. .margin({ top: 2 ,right:6})
  5294. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  5295. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  5296. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  5297. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  5298. .maxLines(1)
  5299. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5300. .margin({ top: 2})
  5301. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  5302. || item.type == CommonConstants.TYPE_IS_ALBUM
  5303. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5304. .fontWeight(FontWeight.Medium)
  5305. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5306. $r('app.color.text_color'))
  5307. }
  5308. }
  5309. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  5310. }
  5311. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  5312. .width(this.getGridWight())
  5313. .justifyContent(FlexAlign.Center)
  5314. .margin({
  5315. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5316. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5317. })
  5318. }
  5319. .width(this.getGridWight())
  5320. .borderRadius(12)
  5321. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?undefined:item.pixelMapPath)
  5322. .backgroundImageSize({ height: '100%', width: '100%' })
  5323. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  5324. .animation({ curve: Curve.Sharp, duration: 300 })
  5325. Checkbox({ name: 'checkbox' + index })
  5326. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  5327. .selectedColor(this.themeColor)
  5328. .shape(CheckBoxShape.CIRCLE)
  5329. .opacity(this.isMultiSelect ? 1 : 0)
  5330. .animation({
  5331. duration: 666,
  5332. curve: 'Smooth' // 可选动画曲线
  5333. })
  5334. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  5335. Visibility.None)
  5336. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5337. .margin({ left: 20, top: 8, bottom: 8 })
  5338. .width(38)
  5339. .height(38)
  5340. }
  5341. }
  5342. .backgroundColor(Color.Transparent)
  5343. .width('100%')
  5344. .padding({ top: 15 })
  5345. .height(this.getGridAllHeight())
  5346. .onClick(() => {
  5347. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5348. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5349. this.handleFileSelection(item, !isChecked);
  5350. } else {
  5351. this.doPlay(item, index)
  5352. }
  5353. })
  5354. }
  5355. getGridAllHeight() {
  5356. let heightG = 222
  5357. switch (this.twoFingerType) {
  5358. case 1:
  5359. heightG = 143
  5360. break;
  5361. case 2:
  5362. heightG = 178
  5363. break;
  5364. case 3:
  5365. heightG = 222
  5366. break;
  5367. }
  5368. return heightG
  5369. }
  5370. getGridHeight() {
  5371. let heightG = 150
  5372. switch (this.twoFingerType) {
  5373. case 1:
  5374. heightG = 80
  5375. break;
  5376. case 2:
  5377. heightG = 110
  5378. break;
  5379. case 3:
  5380. heightG = 150
  5381. break;
  5382. }
  5383. return heightG
  5384. }
  5385. getGridWight() {
  5386. let wightG = 158
  5387. switch (this.twoFingerType) {
  5388. case 1:
  5389. wightG = 80
  5390. break;
  5391. case 2:
  5392. wightG = 110
  5393. break;
  5394. case 3:
  5395. wightG = 158
  5396. break;
  5397. }
  5398. return wightG
  5399. }
  5400. @State isShowDetail:boolean = false
  5401. @State longItemFilePathDetail:string =''
  5402. @Builder
  5403. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  5404. if(
  5405. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  5406. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5407. item.name === LocalMusic.STR_HISTORY_MUSIC)
  5408. ){
  5409. //如果是专辑和艺术家的首页,不能长按
  5410. //如果是我的收藏 最近播放等也不能长按
  5411. }else{
  5412. Scroll() {
  5413. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  5414. Menu() {
  5415. MenuItem({
  5416. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  5417. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  5418. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  5419. })
  5420. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5421. .onClick(() => {
  5422. if (item) {
  5423. this.doFav(item)
  5424. }
  5425. this.longItemFilePath = ''
  5426. })
  5427. MenuItem({
  5428. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  5429. content: '下一首播放'
  5430. })
  5431. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5432. .onClick(() => {
  5433. this.addToNextPlay(item);
  5434. this.longItemFilePath = ''
  5435. })
  5436. MenuItem({
  5437. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  5438. content: '添加到歌单'
  5439. })
  5440. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5441. .onClick(async () => {
  5442. this.longItemFilePath = ''
  5443. await this.openAddToPlaylistDialog(item)
  5444. })
  5445. MenuItem({
  5446. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  5447. content: '编辑标签'
  5448. })
  5449. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  5450. height: '99%',
  5451. dragBar: true,
  5452. showClose: true,
  5453. preferType: SheetType.CENTER ,
  5454. title: { title: '编辑标签' }
  5455. })
  5456. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5457. .onClick(async() => {
  5458. this.initEditFields(item)
  5459. this.tempLyricContent = await this.getLyricContent(item);
  5460. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  5461. this.lyricConStr = this.tempLyricContent
  5462. }
  5463. if(this.isGridMusic||this.twoFingerType==4){
  5464. this.longItemFilePath = item.filePath
  5465. }else{
  5466. this.isShowEdit = !this.isShowEdit;
  5467. }
  5468. })
  5469. MenuItem({
  5470. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  5471. content: $r('app.string.select_all')
  5472. })
  5473. .onClick(() => {
  5474. this.isMultiSelect = !this.isMultiSelect
  5475. this.longItemFilePath = ''
  5476. this.selectedFiles.push(item)
  5477. })
  5478. MenuItem({
  5479. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.cut')),
  5480. content: $r('app.string.edit_audio')
  5481. })
  5482. .bindContentCover($$this.isEditAudio, this.EditAudioBuilder(item), {
  5483. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5484. })
  5485. .onClick(() => {
  5486. this.isEditAudio = !this.isEditAudio
  5487. })
  5488. MenuItem({
  5489. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  5490. content: $r('app.string.extract_accompaniment')
  5491. })
  5492. .bindContentCover($$this.isExtractAcc, this.ExtractAccBuilder(item), {
  5493. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5494. })
  5495. .onClick(() => {
  5496. if (!Utility.isNoble()) {
  5497. this.showVipDialog()
  5498. return
  5499. }
  5500. this.isExtractAcc = !this.isExtractAcc
  5501. })
  5502. MenuItem({
  5503. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.repeat')),
  5504. content: $r('app.string.converter_audio')
  5505. })
  5506. .bindContentCover($$this.isConverter, this.ConverterBuilder(item), {
  5507. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5508. })
  5509. .onClick(() => {
  5510. if (!Utility.isNoble()) {
  5511. this.showVipDialog()
  5512. return
  5513. }
  5514. this.isConverter = !this.isConverter
  5515. })
  5516. MenuItem({
  5517. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.ai_edit')),
  5518. content: $r('app.string.vocal_separation')
  5519. })
  5520. .bindContentCover($$this.isAIVoiceSeparation, this.AiBuilder(item), {
  5521. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5522. })
  5523. .onClick(() => {
  5524. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  5525. })
  5526. MenuItem({
  5527. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_counterclockwise_clock')),
  5528. content: $r('app.string.change_tone')
  5529. })
  5530. .bindContentCover($$this.isChangeTone, this.ChangeToneBuilder(item), {
  5531. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5532. })
  5533. .onClick(() => {
  5534. this.isChangeTone = !this.isChangeTone
  5535. })
  5536. if(Utility.isVideoByExtension(item.filePath)){
  5537. MenuItem({
  5538. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.identify_song')),
  5539. content: $r('app.string.extract_audio')
  5540. })
  5541. .bindContentCover($$this.isExtractAudio, this.extractAudioFromVideoBuilder(item), {
  5542. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5543. })
  5544. .onClick(() => {
  5545. this.isExtractAudio = !this.isExtractAudio
  5546. })
  5547. }
  5548. MenuItem({
  5549. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.phone')),
  5550. content: $r('app.string.set_ring')
  5551. })
  5552. .onClick(async () => {
  5553. await PermissionUtil.activatePermission(item.filePath)
  5554. // if(item.filePath.includes(this.packName)){
  5555. setRingTone(this.context, item.filePath,item.name)
  5556. // }else{
  5557. // ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限设置铃声')
  5558. // }
  5559. this.longItemFilePath = ''
  5560. })
  5561. MenuItem({
  5562. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  5563. content: $r('app.string.rename')
  5564. })
  5565. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  5566. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5567. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  5568. .onClick(() => {
  5569. this.showReNameDialog(item, index + '', filePath)
  5570. this.longItemFilePath = ''
  5571. })
  5572. MenuItem({
  5573. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  5574. content: $r('app.string.delete')
  5575. })
  5576. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  5577. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5578. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  5579. .onClick(() => {
  5580. this.selectedFiles.push(item)
  5581. this.showWarnIsDelete()
  5582. this.longItemFilePath = ''
  5583. })
  5584. MenuItem({
  5585. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  5586. content: $r('app.string.detail')
  5587. })
  5588. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  5589. height:'95%',
  5590. dragBar: true,
  5591. showClose: true,
  5592. blurStyle:BlurStyle.Thin,
  5593. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  5594. backgroundColor:Color.Transparent,
  5595. title: { title: '详情信息' }
  5596. })
  5597. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5598. .onClick(() => {
  5599. if(this.isGridMusic||this.twoFingerType==4){
  5600. this.longItemFilePathDetail = item.filePath
  5601. }else{
  5602. this.isShowDetail = !this.isShowDetail
  5603. }
  5604. })
  5605. MenuItem({
  5606. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  5607. content: $r('app.string.share')
  5608. })
  5609. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5610. .onClick(() => {
  5611. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  5612. this.longItemFilePath = ''
  5613. })
  5614. }
  5615. .font({ size: 14, weight: FontWeight.Normal })
  5616. }
  5617. .width(180)
  5618. }
  5619. .height('auto')
  5620. }
  5621. }
  5622. private listMaxScrollOffsetY: number = 0
  5623. @State selectedIndex: number = -1
  5624. setlistTwoFingers() {
  5625. this.pinchValue = this.scaleValue;
  5626. Logger.info('this.pinchValue = ' + this.pinchValue);
  5627. if (this.pinchValue >= 1) {
  5628. this.twoFingerType++
  5629. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  5630. if (this.twoFingerType > 3) {
  5631. this.twoFingerType = 1
  5632. this.isGridMusic = true
  5633. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5634. }
  5635. } else {
  5636. this.twoFingerType--
  5637. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  5638. if (this.twoFingerType < 1) {
  5639. this.twoFingerType = 4
  5640. this.columns = 1
  5641. }
  5642. }
  5643. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5644. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5645. this.pinchValue = 1;
  5646. this.scaleValue = 1;
  5647. }
  5648. @Builder
  5649. getList(){
  5650. Stack() {
  5651. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  5652. this.getListView()
  5653. }
  5654. .pullDownRatio(this.ratioL)
  5655. .pullToRefresh(true)
  5656. .refreshOffset(0)
  5657. .onOffsetChange((offset: number) => {
  5658. // 越接近最大距离,下拉跟手系数越小。
  5659. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  5660. })
  5661. .onStateChange((refreshStatus: RefreshStatus) => {
  5662. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  5663. })
  5664. .onRefreshing(async () => {
  5665. if(this.modeType==0){
  5666. this.getHistoryList(false)
  5667. this.asyncCurrentPathOnlyFile()
  5668. }else if(this.modeType == 1){
  5669. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  5670. }else if(this.modeType == 2){
  5671. workerInstance.postMessage({ code: 3, data: this.context });
  5672. }else if(this.modeType == 3){
  5673. workerInstance.postMessage({ code: 4, data: this.context });
  5674. }else if(this.modeType == 4){
  5675. this.doSongListTask()
  5676. }
  5677. console.log('onRefreshing test');
  5678. })
  5679. }
  5680. }
  5681. // 扫描当前目录下的文件,不扫描子目录
  5682. asyncCurrentPathOnlyFile(){
  5683. if(this.modeType==0){
  5684. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  5685. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  5686. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  5687. if(this.modeType==0){
  5688. setTimeout(()=>{
  5689. this.isRefreshing =false
  5690. this.deleteCache(this.currentPath)
  5691. this.getSortedFiles(this.currentPath)
  5692. },500)
  5693. }
  5694. }).catch((e:object)=>{
  5695. this.isRefreshing =false
  5696. console.info("onecold task1 catch e: " + e);
  5697. })
  5698. }
  5699. }
  5700. @Builder
  5701. getListView() {
  5702. List({ scroller: this.listScroller }) {
  5703. // ListItemGroup({ header: this.coverHeader() }) {
  5704. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5705. ListItem() {
  5706. Column() {
  5707. if (item.type === CommonConstants.TYPE_IS_DIR
  5708. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  5709. this.DirItem(item, index)
  5710. } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
  5711. } else {
  5712. this.MusicItem(item, index)
  5713. }
  5714. }
  5715. .shadow(this.scaleItem === index ? {
  5716. radius: 70,
  5717. color: '#15000000',
  5718. offsetX: 0,
  5719. offsetY: 0
  5720. } :
  5721. {
  5722. radius: 0,
  5723. color: '#15000000',
  5724. offsetX: 0,
  5725. offsetY: 0
  5726. })
  5727. .animation({ curve: Curve.Sharp, duration: 300 })
  5728. }
  5729. // .transition(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }))
  5730. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.9, y: 0.9 })
  5731. .animation({ duration: 500 }),
  5732. TransitionEffect.scale({ x: 0, y: 0 })))
  5733. .clickEffect({ level: ClickEffectLevel.LIGHT })
  5734. .swipeAction((
  5735. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  5736. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  5737. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  5738. start:null,edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  5739. .onClick(() => {
  5740. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5741. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5742. this.handleFileSelection(item, !isChecked);
  5743. } else {
  5744. this.doPlay(item, index)
  5745. }
  5746. })
  5747. //拖动List关键代码开始
  5748. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  5749. .zIndex(this.dragItem === index ? 1 : 0)
  5750. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  5751. .gesture(
  5752. GestureGroup(GestureMode.Sequence,
  5753. LongPressGesture({ repeat: true })
  5754. .onAction((event?: GestureEvent) => {
  5755. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5756. this.scaleItem = index
  5757. })
  5758. })
  5759. .onActionEnd(() => {
  5760. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5761. this.scaleItem = -1
  5762. })
  5763. }),
  5764. PanGesture({ fingers: 1, direction: null, distance: 0 })
  5765. .onActionStart(() => {
  5766. this.dragItem = index // 记录当前拖动项索引
  5767. this.dragRefOffset = 0 // 重置偏移基准
  5768. })
  5769. .onActionUpdate((event: GestureEvent) => {
  5770. this.offsetY = event.offsetY - this.dragRefOffset;
  5771. this.neighborItem = -1;
  5772. let indexA = this.videoLocalList.indexOf(item);
  5773. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  5774. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  5775. let value: number = 0;
  5776. if (this.offsetY < 0) {
  5777. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  5778. this.neighborItem = indexA - 1;
  5779. this.neighborScale = 1 - value / 20;
  5780. } else if (this.offsetY > 0) {
  5781. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  5782. this.neighborItem = indexA + 1;
  5783. this.neighborScale = 1 - value / 20;
  5784. }
  5785. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  5786. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5787. this.offsetY -= this.ITEM_INTV;
  5788. this.dragRefOffset += this.ITEM_INTV;
  5789. this.itemMove(indexA, indexA + 1);
  5790. });
  5791. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  5792. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5793. this.offsetY += this.ITEM_INTV;
  5794. this.dragRefOffset -= this.ITEM_INTV;
  5795. this.itemMove(indexA, indexA - 1);
  5796. });
  5797. }
  5798. let curListOffset = this.listScroller.currentOffset()
  5799. // 获取手指信息
  5800. let fingerInfo = event.fingerList[0]
  5801. let clickPercentY =
  5802. (fingerInfo.globalY - Number(this.listArea.globalPosition.y)) / Number(this.listArea.height)
  5803. if (clickPercentY > 0.8 && !this.listScroller.isAtEnd()) {
  5804. let scrollVelocity = clickPercentY > 0.9 ? 4 : 2
  5805. if (this.listMaxScrollOffsetY - curListOffset.yOffset > scrollVelocity + 5) {
  5806. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset += scrollVelocity })
  5807. }
  5808. } else if (clickPercentY < 0.2 && curListOffset.yOffset >= 0) {
  5809. let scrollVelocity = clickPercentY < 0.1 ? 4 : 2
  5810. if (curListOffset.yOffset > scrollVelocity + 5) {
  5811. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset -= scrollVelocity })
  5812. }
  5813. }
  5814. })
  5815. .onActionEnd((event: GestureEvent) => {
  5816. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5817. this.dragItem = -1
  5818. this.neighborItem = -1
  5819. })
  5820. animateTo({
  5821. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5822. }, () => {
  5823. this.scaleItem = -1
  5824. })
  5825. })
  5826. )
  5827. .onCancel(() => {
  5828. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5829. this.dragItem = -1
  5830. this.neighborItem = -1
  5831. })
  5832. animateTo({
  5833. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5834. }, () => {
  5835. this.scaleItem = -1
  5836. })
  5837. })
  5838. ) //拖动List关键代码结束
  5839. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5840. // }
  5841. }
  5842. .onScrollStart(() => {
  5843. this.isScrolling = true
  5844. this.isShowAlphaBet = true
  5845. })
  5846. .onScrollIndex((start: number,center:number,end:number) => {
  5847. this.selectedIndex = start
  5848. if(start >= 0 && start < this.videoLocalList.length){
  5849. this.selectAlphaBetIndex = this.findAlphaBetIndex(this.videoLocalList[start])
  5850. }
  5851. })
  5852. .onScrollStop(() => {
  5853. if(this.isScrolling){
  5854. this.isScrolling = false
  5855. }
  5856. this.isShowAlphaBet = false
  5857. })
  5858. .scrollBar(BarState.Off)
  5859. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5860. .gesture(PinchGesture({ fingers: 2 })
  5861. .onActionEnd((event: GestureEvent) => {
  5862. this.setlistTwoFingers()
  5863. })
  5864. .onActionUpdate(e => {
  5865. this.scaleValue = this.pinchValue * e.scale
  5866. })
  5867. .onActionStart(e => {
  5868. }))
  5869. .contentStartOffset(this.topSafeHeight + 55)
  5870. .scrollBar(BarState.Off)
  5871. .contentEndOffset(this.bottomBarHeight+this.bottomSafeHeight)
  5872. .cachedCount(10)
  5873. // .reuseId('list_item')
  5874. .borderRadius(20)
  5875. .layoutWeight(1)
  5876. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  5877. .lanes(
  5878. new BreakpointType<number>({
  5879. sm: 1,
  5880. md: 2,
  5881. lg: 2,
  5882. xl: 3,
  5883. xxl: 4
  5884. }).getValue(this.currentBreakpoint),
  5885. new BreakpointType<number>({
  5886. sm: 0,
  5887. md: 12,
  5888. lg: 12,
  5889. xl: 16,
  5890. xxl: 20
  5891. }).getValue(this.currentBreakpoint)
  5892. )
  5893. .onAreaChange((oldValue: Area, newValue: Area) => {
  5894. this.listArea = newValue
  5895. if (this.twoFingerType == 3) {
  5896. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  5897. } else if (this.twoFingerType == 2) {
  5898. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  5899. } else if (this.twoFingerType == 1) {
  5900. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  5901. }
  5902. })
  5903. .onScrollFrameBegin((offset: number) => {
  5904. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  5905. // if (this.isPhoneLan()) {
  5906. // this.setBarHeightHide(offset)
  5907. // } else
  5908. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  5909. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  5910. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  5911. if (this.isScrollHide) {
  5912. this.setBarHeightHide2(offset)
  5913. } else {
  5914. this.setBarHeightNormal()
  5915. }
  5916. } else {
  5917. this.setBarHeightHide(offset)
  5918. }
  5919. return { offsetRemain: offset };
  5920. })
  5921. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  5922. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  5923. .onDrop((event?: DragEvent) => {
  5924. try {
  5925. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  5926. if (dragData !== undefined) {
  5927. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  5928. if (records.length > 0) {
  5929. for (let i = 0; i < records.length; i++) {
  5930. let types = records[i].getTypes();
  5931. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  5932. const fileUriUds =
  5933. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  5934. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  5935. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  5936. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  5937. this.targetFile = fileUriUds.oriUri;
  5938. this.saveVideoDatas([this.targetFile])
  5939. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  5940. }
  5941. }
  5942. }
  5943. } else {
  5944. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  5945. }
  5946. } else {
  5947. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  5948. }
  5949. } catch (error) {
  5950. const err = error as BusinessError;
  5951. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  5952. }
  5953. })
  5954. }
  5955. setBarHeightNormal() {
  5956. this.hideDone = false;
  5957. this.getUIContext().animateTo({
  5958. duration: 300
  5959. }, () => {
  5960. this.bottomBarHeight = 68 + 0;
  5961. this.topBarHeight = 50 + 0;
  5962. this.barOpacity = 1;
  5963. this.barBottomOpacity = 1
  5964. this.currentYOffset = 0;
  5965. this.isHiding = false;
  5966. });
  5967. }
  5968. setBarHeightHide(offset: number) {
  5969. if (offset > 0 && !this.hideDone) {
  5970. this.currentYOffset += offset;
  5971. if (this.currentYOffset <= 100) {
  5972. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  5973. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  5974. this.barOpacity = 1 - this.currentYOffset / 100;
  5975. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  5976. } else {
  5977. this.topBarHeight = 0;
  5978. this.bottomBarHeight = 0;
  5979. this.barBottomOpacity = 0
  5980. this.barOpacity = 0;
  5981. this.hideDone = true;
  5982. }
  5983. this.isHiding = true;
  5984. }
  5985. if (offset < 0 && this.isHiding) {
  5986. this.hideDone = false;
  5987. this.getUIContext().animateTo({
  5988. duration: 300
  5989. }, () => {
  5990. this.bottomBarHeight = 68 + 0;
  5991. this.topBarHeight = 50 + 0;
  5992. this.barOpacity = 1;
  5993. this.barBottomOpacity = 1
  5994. this.currentYOffset = 0;
  5995. this.isHiding = false;
  5996. });
  5997. }
  5998. }
  5999. //这个方法没隐藏bottomBar,只隐藏topbar
  6000. setBarHeightHide2(offset: number) {
  6001. if (offset > 0 && !this.hideDone) {
  6002. this.currentYOffset += offset;
  6003. if (this.currentYOffset <= 100) {
  6004. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  6005. this.barOpacity = 1 - this.currentYOffset / 100;
  6006. } else {
  6007. this.topBarHeight = 0;
  6008. this.barOpacity = 0;
  6009. this.hideDone = true;
  6010. }
  6011. this.isHiding = true;
  6012. }
  6013. if (offset < 0 && this.isHiding) {
  6014. this.hideDone = false;
  6015. this.getUIContext().animateTo({
  6016. duration: 300
  6017. }, () => {
  6018. this.topBarHeight = 50 + 0;
  6019. this.barOpacity = 1;
  6020. this.currentYOffset = 0;
  6021. this.isHiding = false;
  6022. });
  6023. }
  6024. }
  6025. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  6026. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  6027. switch (item.type) {
  6028. case CommonConstants.TYPE_IS_DIR:
  6029. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  6030. let offsetB = 0
  6031. if(this.twoFingerType==4){
  6032. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6033. let cur = this.waterScroller.currentOffset()
  6034. if (cur && typeof cur.yOffset === 'number') {
  6035. offsetB = cur.yOffset
  6036. }
  6037. }
  6038. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  6039. }else
  6040. if (this.isGridMusic) {
  6041. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6042. let cur = this.scroller.currentOffset()
  6043. if (cur && typeof cur.yOffset === 'number') {
  6044. offsetB = cur.yOffset
  6045. }
  6046. }
  6047. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  6048. } else {
  6049. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6050. let cur = this.listScroller.currentOffset()
  6051. if (cur && typeof cur.yOffset === 'number') {
  6052. offsetB = cur.yOffset
  6053. }
  6054. }
  6055. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  6056. }
  6057. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  6058. this.showVerifyDialog()
  6059. this.currentTitleName = '私密音频'
  6060. this.currentTitleCover = $r('app.media.alt')
  6061. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  6062. this.titleName = '最近播放'
  6063. this.currentTitleCover = $r('app.media.alt')
  6064. this.currentTitleName = '最近播放'
  6065. //加载动画效果
  6066. this.updateListData(this.historyList, true)
  6067. // this.videoLocalList = this.historyList
  6068. if (ArrayUtil.isEmpty(this.historyList)) {
  6069. ToastUtil.showToast('最近播放记录空空如也')
  6070. } else {
  6071. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  6072. }
  6073. this.isHistory = true
  6074. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  6075. this.titleName = '我的收藏'
  6076. this.currentTitleName = '我的收藏'
  6077. this.currentTitleCover = $r('app.media.alt')
  6078. //加载动画效果
  6079. this.updateListData(this.favList)
  6080. if (ArrayUtil.isEmpty(this.favList)) {
  6081. ToastUtil.showToast('无音乐收藏记录')
  6082. } else {
  6083. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  6084. }
  6085. this.isFavMusic = true
  6086. } else {
  6087. this.currentTitleName = item.name
  6088. this.currentPath = item.filePath
  6089. this.currentTitleCover = $r('app.media.alt')
  6090. this.getSortedFiles(this.currentPath)
  6091. }
  6092. //进入歌单的时候的滚动位置在顶部
  6093. if(this.twoFingerType==4){
  6094. setTimeout(() => {
  6095. this.waterScroller.scrollEdge(Edge.Top)
  6096. this.scroller.scrollEdge(Edge.Top)
  6097. }, 380)
  6098. }else{
  6099. if (this.isGridMusic) {
  6100. this.scroller.scrollEdge(Edge.Top)
  6101. }else{
  6102. this.listScroller.scrollEdge(Edge.Top)
  6103. }
  6104. }
  6105. this.rightTopImage = $r('sys.symbol.chevron_left')
  6106. break;
  6107. case CommonConstants.TYPE_IS_ARTIST:
  6108. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  6109. let offsetA = 0
  6110. if(this.twoFingerType==4){
  6111. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6112. let cur = this.waterScroller.currentOffset()
  6113. if (cur && typeof cur.yOffset === 'number') {
  6114. offsetA = cur.yOffset
  6115. }
  6116. }
  6117. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  6118. }else
  6119. if (this.isGridMusic) {
  6120. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6121. let cur = this.scroller.currentOffset()
  6122. if (cur && typeof cur.yOffset === 'number') {
  6123. offsetA = cur.yOffset
  6124. }
  6125. }
  6126. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  6127. } else {
  6128. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6129. let cur = this.listScroller.currentOffset()
  6130. if (cur && typeof cur.yOffset === 'number') {
  6131. offsetA = cur.yOffset
  6132. }
  6133. }
  6134. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  6135. }
  6136. let mList = this.artistMap.get(item.name)
  6137. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  6138. Utility.doSortListAscending(mList)
  6139. this.isCanBack = true
  6140. this.titleName = item.name
  6141. this.currentTitleName = '艺术家:' + item.name
  6142. if (item.pixelMapPath) {
  6143. this.currentTitleCover = item.pixelMapPath
  6144. }
  6145. this.updateListData(mList)
  6146. }
  6147. this.rightTopImage = $r('sys.symbol.chevron_left')
  6148. //进入歌单的时候的滚动位置在顶部
  6149. if(this.twoFingerType==4){
  6150. setTimeout(() => {
  6151. this.waterScroller.scrollEdge(Edge.Top)
  6152. this.scroller.scrollEdge(Edge.Top)
  6153. }, 380)
  6154. }else{
  6155. if (this.isGridMusic) {
  6156. this.scroller.scrollEdge(Edge.Top)
  6157. }else{
  6158. this.listScroller.scrollEdge(Edge.Top)
  6159. }
  6160. }
  6161. break;
  6162. case CommonConstants.TYPE_IS_ALBUM:
  6163. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  6164. let offset = 0
  6165. if(this.twoFingerType==4){
  6166. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6167. let cur = this.waterScroller.currentOffset()
  6168. if (cur && typeof cur.yOffset === 'number') {
  6169. offset = cur.yOffset
  6170. }
  6171. }
  6172. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  6173. }else
  6174. if (this.isGridMusic) {
  6175. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6176. let cur = this.scroller.currentOffset()
  6177. if (cur && typeof cur.yOffset === 'number') {
  6178. offset = cur.yOffset
  6179. }
  6180. }
  6181. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  6182. } else {
  6183. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6184. let cur = this.listScroller.currentOffset()
  6185. if (cur && typeof cur.yOffset === 'number') {
  6186. offset = cur.yOffset
  6187. }
  6188. }
  6189. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  6190. }
  6191. let albumList = this.albumMap.get(item.name)
  6192. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  6193. Utility.doSortListAscending(albumList)
  6194. this.isCanBack = true
  6195. this.titleName = item.name
  6196. this.currentTitleName = '专辑:' + item.name
  6197. if (item.pixelMapPath) {
  6198. this.currentTitleCover = item.pixelMapPath
  6199. }
  6200. this.updateListData(albumList)
  6201. this.mScrollMap.set(item.name, this.selectedIndex)
  6202. this.rightTopImage = $r('sys.symbol.chevron_left')
  6203. }
  6204. //进入歌单的时候的滚动位置在顶部
  6205. if(this.twoFingerType==4){
  6206. setTimeout(() => {
  6207. this.waterScroller.scrollEdge(Edge.Top)
  6208. this.scroller.scrollEdge(Edge.Top)
  6209. }, 380)
  6210. }else{
  6211. if (this.isGridMusic) {
  6212. this.scroller.scrollEdge(Edge.Top)
  6213. }else{
  6214. this.listScroller.scrollEdge(Edge.Top)
  6215. }
  6216. }
  6217. break;
  6218. case CommonConstants.TYPE_IS_CSJAD:
  6219. return
  6220. break;
  6221. case CommonConstants.TYPE_LOCAL:
  6222. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  6223. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  6224. const cueTracks:CueTrack[] = cueinfo.tracks
  6225. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  6226. if(ArrayUtil.isNotEmpty(cueTracks)){
  6227. this.showCueDialog(cueTracks,cueinfo)
  6228. }
  6229. // this.showCueSheet = !this.showCueSheet
  6230. return
  6231. }
  6232. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6233. this.stop();
  6234. }
  6235. if (isOpen) {
  6236. this.currentSong = item
  6237. if (index !== undefined) {
  6238. this.curIndex = index
  6239. }
  6240. this.songList = []
  6241. this.songList.push(item)
  6242. this.sonDataSource.pushArrayData(this.songList)
  6243. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  6244. this.currentSong = item
  6245. if (index !== undefined) {
  6246. this.curIndex = index
  6247. }
  6248. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  6249. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  6250. }else {
  6251. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  6252. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  6253. this.songList = globalVideoList
  6254. this.sonDataSource.pushArrayData(this.songList)
  6255. this.currentSong = globalVideoList[this.curIndex]
  6256. }
  6257. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  6258. this.videoUrl = this.currentSong.filePath
  6259. this.name = this.currentSong.name
  6260. this.cover = this.currentSong.pixelMapPath
  6261. this.artist = this.currentSong.artist
  6262. LogUtil.info('onecold this.currentSong.cover =' + this.currentSong.pixelMapPath)
  6263. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  6264. this.startPlayOrResumePlay()
  6265. break;
  6266. case CommonConstants.TYPE_WEBDAV:
  6267. case CommonConstants.TYPE_SMB:
  6268. case CommonConstants.TYPE_NAVIDROME:
  6269. // 处理网络音频播放(WebDAV/SMB)
  6270. Logger.info(`heanup 处理云端音频播放: ${item.name}, URL: ${item.filePath}`)
  6271. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6272. this.stop();
  6273. }
  6274. if (isOpen) {
  6275. this.currentSong = item
  6276. if (index !== undefined) {
  6277. this.curIndex = index
  6278. }
  6279. this.songList = []
  6280. this.songList.push(item)
  6281. this.sonDataSource.pushArrayData(this.songList)
  6282. } else if (isFromSonPlayList) {
  6283. // 点击来自右下角的播放列表
  6284. this.currentSong = item
  6285. if (index !== undefined) {
  6286. this.curIndex = index
  6287. }
  6288. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  6289. Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  6290. } else {
  6291. // 从全局网络音频列表中查找
  6292. let globalVideoList = this.videoLocalList.filter(video => isRemoteCloudType(video.type)) as VideoItem[];
  6293. this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
  6294. if (this.curIndex === -1 && index !== undefined) {
  6295. this.curIndex = index;
  6296. }
  6297. this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
  6298. this.currentSong = this.songList[this.curIndex];
  6299. this.sonDataSource.pushArrayData(this.songList)
  6300. }
  6301. await this.hydrateRemoteSongFromDb(this.currentSong);
  6302. await this.hydrateRemoteSongFromDb(this.currentSong);
  6303. AppStorage.setOrCreate('currentSong', this.currentSong);
  6304. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  6305. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  6306. context: this.context,
  6307. autoParseMusicName: this.autoParseMusicName
  6308. });
  6309. Logger.info(TAG, `WebDAV URL同步构建完成(分支2): ${this.videoUrl}`);
  6310. this.name = this.currentSong.name
  6311. this.cover = this.currentSong.pixelMapPath
  6312. this.artist = this.currentSong.artist
  6313. Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 完整URL: ${this.videoUrl}`)
  6314. this.startPlayOrResumePlay()
  6315. break;
  6316. }
  6317. }
  6318. private cueComponentId: number = 0
  6319. //显示cue分轨列表对话框
  6320. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  6321. this.getUIContext().getPromptAction().openCustomDialog({
  6322. builder: () => {
  6323. this.cueComptentBuilder(cueTracks,cueinfo)
  6324. },
  6325. isModal:true,
  6326. showInSubWindow:false,
  6327. maskColor: Color.Transparent,
  6328. dialogTransition: // 设置弹窗内容显示的过渡效果
  6329. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  6330. .animation({ duration: 600, curve: Curve.Smooth }),
  6331. maskTransition: // 设置蒙层显示的过渡效果
  6332. TransitionEffect.opacity(0.5)
  6333. .animation({ duration: 600, curve: Curve.Smooth })
  6334. }).then((dialogId: number) => {
  6335. this.cueComponentId = dialogId
  6336. })
  6337. .catch((error: BusinessError) => {
  6338. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  6339. })
  6340. }
  6341. @Builder
  6342. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  6343. CueComptent({
  6344. title:cueinfo.title,
  6345. cueTracks:cueTracks,
  6346. isLongNameRoLL:this.isLongNameRoLL,
  6347. onCancel:()=>{
  6348. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  6349. },
  6350. onDoItemClick: async (item: CueTrack, index: number)=>{
  6351. //获取cueinfo对应的filePath
  6352. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  6353. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  6354. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  6355. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  6356. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  6357. if (this.currentSong){
  6358. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6359. this.stop();//播放之前先停止之前播放。
  6360. }
  6361. this.songList = globalVideoList
  6362. this.sonDataSource.pushArrayData(this.songList)
  6363. if (this.currentSong) {
  6364. try {
  6365. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  6366. context: this.context,
  6367. autoParseMusicName: this.autoParseMusicName
  6368. });
  6369. } catch (error) {
  6370. Logger.error(TAG, `CUE 点播构建播放地址失败: ${(error as Error).message}`);
  6371. this.videoUrl = this.currentSong.filePath;
  6372. }
  6373. }
  6374. this.name = item.title||this.currentSong.name
  6375. this.cover = this.currentSong.pixelMapPath
  6376. this.artist = item.performer||this.currentSong.artist
  6377. this.currentSong.name = this.name
  6378. this.currentSong.artist = this.artist
  6379. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  6380. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  6381. }
  6382. }
  6383. })
  6384. }
  6385. @Builder
  6386. PlayController() {
  6387. Row() {
  6388. if(this.isHiCar()){
  6389. this.playConRigth()
  6390. Column(){
  6391. this.centerName()
  6392. }.layoutWeight(1)
  6393. .onClick(()=>{
  6394. this.showPlayerView()
  6395. })
  6396. this.playConLeft(false)
  6397. }else{
  6398. this.playConLeft()
  6399. this.playConRigth()
  6400. }
  6401. }
  6402. .width('100%')
  6403. .height(this.bottomBarHeight)
  6404. .hitTestBehavior(HitTestMode.Transparent)
  6405. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  6406. modalTransition: ModalTransition.NONE,
  6407. onWillDisappear: () => {
  6408. this.setShowPlayFalse()
  6409. },
  6410. // backgroundColor: 'rgba(0, 0, 0, 0.9)',
  6411. })
  6412. .padding({
  6413. left: 16,
  6414. right: 16
  6415. })
  6416. }
  6417. @State isFrontWhite: boolean = false
  6418. @Builder
  6419. centerName() {
  6420. Column() {
  6421. Text(this.currentSong?.name)
  6422. .fontSize(16)
  6423. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  6424. .maxLines(1)
  6425. .fontColor(Color.White)
  6426. .fontWeight(500);
  6427. Row() {
  6428. Text(this.currentSong?.artist)
  6429. .margin({ top: 2 })
  6430. .fontSize(13)
  6431. .textAlign(TextAlign.Start)
  6432. .maxLines(1)
  6433. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  6434. .fontColor(Color.White)
  6435. }
  6436. .visibility(this.currentSong?.artist? Visibility.Visible:Visibility.None)
  6437. }
  6438. .geometryTransition('name', { follow: true }) // 绑定标识符
  6439. .alignItems(HorizontalAlign.Center)
  6440. }
  6441. @Builder
  6442. playConLeft(isLeft: boolean = true) {
  6443. Row() {
  6444. // RotatingCover({ songLabel: this.currentSong?.pixelMapPath })
  6445. Image( StrUtil.isNotEmpty(this.currentSong?.pixelMapPath)?
  6446. this.currentSong?.pixelMapPath:$r('app.media.music_red'))
  6447. .height(45)
  6448. .objectFit(ImageFit.Contain)
  6449. .alt( $r('app.media.music_red'))
  6450. .fillColor(this.themeColor)
  6451. .borderRadius(8)
  6452. .shadow({
  6453. radius: 10,
  6454. type: ShadowType.BLUR,
  6455. color: 'on_primary'
  6456. })
  6457. .geometryTransition('cover', { follow: true }) // 绑定标识符
  6458. Column() {
  6459. Text(this.currentSong?.name)
  6460. .fontSize(16)
  6461. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  6462. .maxLines(1)
  6463. .fontColor(Color.White)
  6464. .fontWeight(500);
  6465. Row() {
  6466. Text(this.currentSong?.artist)
  6467. .margin({ top: 2 })
  6468. .fontSize(13)
  6469. .textAlign(TextAlign.Start)
  6470. .maxLines(1)
  6471. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  6472. .fontColor(Color.White)
  6473. }
  6474. .visibility(this.currentSong?.artist? Visibility.Visible:Visibility.None)
  6475. }
  6476. .padding({left:8})
  6477. .geometryTransition('name', { follow: true }) // 绑定标识符
  6478. .alignItems(isLeft?HorizontalAlign.Start:HorizontalAlign.End)
  6479. .margin({ right: isLeft?22:10 })
  6480. .visibility(isLeft? Visibility.Visible:Visibility.None)
  6481. }
  6482. .padding({ right: 18 })
  6483. .layoutWeight(isLeft?1:0)
  6484. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  6485. .onClick(() => {
  6486. this.showPlayerView()
  6487. })
  6488. }
  6489. setShowPlayTrue(){
  6490. this.getUIContext()?.animateTo({
  6491. duration: 500,
  6492. curve: Curve.Friction
  6493. }, () => {
  6494. this.isShowPlay = true;
  6495. });
  6496. }
  6497. setShowPlayFalse(){
  6498. this.getUIContext()?.animateTo({
  6499. duration: 500,
  6500. curve: Curve.Friction
  6501. }, () => {
  6502. this.isShowPlay = false;
  6503. });
  6504. }
  6505. //打开播放页
  6506. showPlayerView() {
  6507. if (ArrayUtil.isNotEmpty(this.songList)) {
  6508. this.setShowPlayTrue()
  6509. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  6510. this.initLyric(lyricPath);
  6511. this.startAutoHide();
  6512. } else {
  6513. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  6514. }
  6515. }
  6516. @Builder
  6517. playConRigth() {
  6518. Row() {
  6519. SymbolGlyph($r('sys.symbol.backward_end_fill'))
  6520. .fontSize(28)
  6521. .fontColor([this.themeColor])
  6522. .alignSelf(ItemAlign.Center)
  6523. .visibility(this.isShowPrecious? Visibility.Visible:Visibility.None)
  6524. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  6525. .margin({ left: 8, right: 14 })
  6526. .displayPriority(2)
  6527. .onClick(() => {
  6528. if (ArrayUtil.isNotEmpty(this.songList)) {
  6529. this.playPrevious()
  6530. } else {
  6531. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6532. }
  6533. })
  6534. //播放进度条
  6535. Stack() {
  6536. Progress({
  6537. value: Math.floor(this.progressValue),
  6538. type: ProgressType.Ring,
  6539. })
  6540. .color(this.themeColor)// 进度条前景色为灰色
  6541. .height(38)
  6542. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6543. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ? $r('app.media.hm_pause') : $r('app.media.hm_play2'))
  6544. .height(36)
  6545. .width(36)
  6546. .displayPriority(3)
  6547. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  6548. .fillColor(this.themeColor)
  6549. .onClick(() => {
  6550. if (ArrayUtil.isNotEmpty(this.songList)) {
  6551. console.info('onecold playOrPause 4642')
  6552. this.playOrPause()
  6553. } else {
  6554. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6555. }
  6556. })
  6557. }
  6558. SymbolGlyph($r('sys.symbol.forward_end_fill'))
  6559. .fontSize(28)
  6560. .fontColor([this.themeColor])
  6561. .alignSelf(ItemAlign.Center)
  6562. .margin({
  6563. right: 14,
  6564. left: 14
  6565. })
  6566. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  6567. .displayPriority(2)
  6568. .onClick(() => {
  6569. if (ArrayUtil.isNotEmpty(this.songList)) {
  6570. this.playNext()
  6571. } else {
  6572. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6573. }
  6574. })
  6575. Image($r('app.media.hm_playlist'))
  6576. .height(26)
  6577. .width(26)
  6578. .displayPriority(1)
  6579. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  6580. .fillColor(this.themeColor)
  6581. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  6582. height: '95%',
  6583. dragBar: true,
  6584. showClose: true,
  6585. blurStyle: BlurStyle.Thin,
  6586. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6587. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  6588. title: {
  6589. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  6590. + `(${this.songList.length}首)`
  6591. }
  6592. })
  6593. .onClick(() => {
  6594. if (ArrayUtil.isNotEmpty(this.songList)) {
  6595. this.isShowSheet = !this.isShowSheet;
  6596. this.isFrontWhite = false
  6597. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  6598. this.scrollIndex()
  6599. } else {
  6600. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6601. }
  6602. })
  6603. }
  6604. }
  6605. scrollIndex(){
  6606. try {
  6607. setTimeout(() => {
  6608. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  6609. if(this.curIndex>60){
  6610. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  6611. }else{
  6612. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  6613. }
  6614. })
  6615. }, 123)
  6616. }catch (error) {
  6617. console.error(`onecold scrollIndex出错: ${error}`);
  6618. }
  6619. }
  6620. //播放列表布局
  6621. @Builder
  6622. PlayListSheet() {
  6623. Column() {
  6624. this.PlayList()
  6625. }
  6626. .width('100%')
  6627. .height('100%')
  6628. }
  6629. @State titleStr: string = ''
  6630. @State ablumStr: string = ''
  6631. @State artistStr: string = ''
  6632. @State lyricConStr: string = ''
  6633. @State currentEditItem: string = ''
  6634. @State yearStr: string = ''
  6635. @State trackStr: string = ''
  6636. @State genreStr: string = ''
  6637. @State imagePathStr: string = ''
  6638. @State albumArtistStr: string = ''
  6639. @State composerStr: string = ''
  6640. @State lyricistStr: string = ''
  6641. @State commentStr: string = ''
  6642. @State discStr: string = ''
  6643. doUpdateData() {
  6644. setTimeout(() => {
  6645. if (this.modeType === 0) {
  6646. this.deleteCache(this.currentPath)
  6647. this.getSortedFiles(this.currentPath)
  6648. }else if (this.modeType === 1){
  6649. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6650. }
  6651. }, 500)
  6652. }
  6653. doAllUpdateData() {
  6654. setTimeout(() => {
  6655. if (this.modeType === 0) {
  6656. this.deleteCache(this.currentPath)
  6657. this.getSortedFiles(this.currentPath)
  6658. }
  6659. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6660. workerInstance.postMessage({ code: 3, data: this.context });
  6661. workerInstance.postMessage({ code: 4, data: this.context });
  6662. }, 999)
  6663. }
  6664. //编辑信息
  6665. async doEdit(item: VideoItem) {
  6666. if (!item) {
  6667. return
  6668. }
  6669. if (StrUtil.isEmpty(this.titleStr)) {
  6670. ToastUtil.showToast('标题不能为空')
  6671. return
  6672. }
  6673. //内嵌音乐标签不能开启监听
  6674. // this.deletionWatcher?.stop();
  6675. DialogHelper.showLoadingDialog()
  6676. await PermissionUtil.activatePermission(item.filePath)
  6677. let tempOutPath = ''
  6678. // 如果不是 packName 包下的文件,则直接路径用this.currentPath
  6679. if(!item.filePath.toLowerCase().includes(this.packName)){
  6680. tempOutPath = this.currentPath + '/' + item.fileName
  6681. }
  6682. console.info('onecold tempOutPath ='+tempOutPath)
  6683. //用户更改了封面,那就内嵌下封面
  6684. if(StrUtil.isNotEmpty(this.imagePathStr)){
  6685. const resultCover:boolean = await changeMusicCover(this.context,
  6686. item.filePath,this.imagePathStr,true,tempOutPath);
  6687. this.imagePathStr = ''
  6688. if(resultCover){
  6689. ToastUtil.showToast('内嵌封面成功')
  6690. }
  6691. }
  6692. const metadata:FFMpegTags = {
  6693. title: this.titleStr,
  6694. artist: this.artistStr,
  6695. album: this.ablumStr,
  6696. TYER:this.yearStr,
  6697. genre:this.genreStr,
  6698. track:this.trackStr,
  6699. album_artist:this.albumArtistStr,
  6700. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  6701. COMPOSER:this.composerStr,
  6702. lyricist:this.lyricistStr,
  6703. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  6704. comment:this.commentStr,
  6705. disc:this.discStr,
  6706. };
  6707. let newInput = item.filePath
  6708. //内嵌标签歌路径如果不是包含包名,输入newInput要赋值tempOutPath,然后tempOutPath为空
  6709. if(!item.filePath.toLowerCase().includes(this.packName)&&FileUtil.accessSync(tempOutPath)){
  6710. newInput = tempOutPath
  6711. tempOutPath = ''
  6712. }
  6713. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  6714. const result:boolean = await repairAudioMetadata(
  6715. newInput,
  6716. this.lyricConStr,
  6717. metadata,
  6718. true,
  6719. tempOutPath
  6720. );
  6721. if (result) {
  6722. if(!item.filePath.includes(this.packName)){
  6723. //内嵌成功的歌路径如果不是包含包名,则要入库
  6724. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newInput,
  6725. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  6726. this.table.insert(newItem, (id: number) => {
  6727. //加入数据库
  6728. if(this.modeType==0){
  6729. this.deleteCache(this.currentPath)
  6730. this.getSortedFiles(this.currentPath)
  6731. }
  6732. });
  6733. }
  6734. const task = new taskpool.Task(
  6735. updateInfoDb,
  6736. this.context,
  6737. item.filePath,
  6738. this.titleStr,
  6739. this.artistStr,
  6740. this.ablumStr,
  6741. this.lyricConStr,
  6742. this.yearStr,this.genreStr,
  6743. this.trackStr,this.albumArtistStr,
  6744. this.composerStr, this.lyricistStr,
  6745. this.commentStr,this.discStr
  6746. );
  6747. taskpool.execute(task, taskpool.Priority.HIGH).then((result) => {
  6748. if (result) {
  6749. console.log(" onecold 编辑信息成功,数据库已同步");
  6750. ToastUtil.showToast('内嵌音乐标签成功')
  6751. this.isShowMoreView = false
  6752. this.name = this.titleStr
  6753. this.syncEditedFields(item)
  6754. if (item.filePath == this.currentSong?.filePath) {
  6755. this.currentSong.name = this.titleStr
  6756. this.artist = this.artistStr
  6757. this.currentSong.artist = this.artistStr
  6758. this.currentSong.album = this.ablumStr
  6759. this.currentSong.year = this.yearStr
  6760. this.currentSong.genre = this.genreStr
  6761. this.currentSong.track = this.trackStr
  6762. this.currentSong.lyricContent = this.lyricConStr
  6763. this.currentSong.ALBUMARTIST = this.albumArtistStr
  6764. this.currentSong.COMPOSER = this.composerStr
  6765. this.currentSong.LYRICIST = this.lyricistStr
  6766. this.currentSong.COMMENT = this.commentStr
  6767. }
  6768. this.syncListsAfterEdit(item.filePath)
  6769. this.doUpateEditedFields(item)
  6770. //this.doUpdateData()
  6771. } else {
  6772. // ToastUtil.showToast('保存失败' + error?.toString())
  6773. console.error(" onecold 编辑信息数据库失败 ");
  6774. }
  6775. // 关闭进度条
  6776. DialogHelper.closeLoading();
  6777. }).catch((error: Error) => {
  6778. // 关闭进度条
  6779. DialogHelper.closeLoading();
  6780. console.error('onecold Subtitle sync failed:', error);
  6781. });
  6782. console.log(' onecold 元数据标签更新成功,');
  6783. } else {
  6784. // 关闭进度条
  6785. DialogHelper.closeLoading();
  6786. ToastUtil.showToast('内嵌音乐标签失败')
  6787. console.log('onecold 内嵌音乐标签失败');
  6788. }
  6789. this.longItemFilePath = ''
  6790. this.tempLyricContent = ''
  6791. this.isShowEdit = false
  6792. }
  6793. // 内嵌标签更新当前内嵌的Item
  6794. async doUpateEditedFields(item: VideoItem) {
  6795. // 找到当前项在 videoLocalList 中的索引
  6796. const index = this.videoLocalList.findIndex(video => video.filePath === item.filePath);
  6797. if (index !== -1) {
  6798. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  6799. const updatedItem = await this.table.queryVideoByFilePath(item.filePath)
  6800. // 只有当查询结果不为 null 时才更新列表
  6801. if (updatedItem !== null) {
  6802. // 更新 videoLocalList 中的项(通过创建新数组触发响应式更新)
  6803. this.videoLocalList = [
  6804. ...this.videoLocalList.slice(0, index),
  6805. updatedItem,
  6806. ...this.videoLocalList.slice(index + 1)
  6807. ];
  6808. // 同步更新 LazyDataSource
  6809. this.dataSource.pushArrayData(this.videoLocalList)
  6810. } else {
  6811. ToastUtil.showToast('未找到更新的数据');
  6812. }
  6813. }
  6814. DialogHelper.closeLoading();
  6815. }
  6816. @Builder
  6817. editSheet(item: VideoItem) {
  6818. Scroll() {
  6819. Column() {
  6820. this.editDetail(item)
  6821. }
  6822. }
  6823. .width('100%')
  6824. .height('100%')
  6825. }
  6826. @Builder
  6827. editDetail(item: VideoItem) {
  6828. Column() {
  6829. if (item) {
  6830. Row() {
  6831. Stack() {
  6832. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  6833. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  6834. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  6835. item.pixelMapPath)
  6836. .fillColor(this.themeColor)
  6837. .height(88)
  6838. .width(88)
  6839. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  6840. .borderRadius(12)
  6841. .clip(true)
  6842. .opacity(this.opacityItem)// 绑定透明度
  6843. .margin({ left: 25 })
  6844. }
  6845. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  6846. .onClick(async () => {
  6847. const imagePath:string | undefined = await this.goSelectImage(item);
  6848. if (imagePath) {
  6849. //用户更改过图片
  6850. this.imagePathStr = imagePath
  6851. }
  6852. })
  6853. .width('28%')
  6854. Row() {
  6855. Column() {
  6856. Text(item.name)
  6857. .fontSize(17)
  6858. .maxLines(1)
  6859. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6860. .animation({
  6861. duration: 555,
  6862. curve: 'Linear',
  6863. })
  6864. .fontColor(this.themeColor)
  6865. .margin({ left: 8 })
  6866. Row() {
  6867. Text(item.artist)
  6868. .fontSize(14)
  6869. .maxLines(1)
  6870. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6871. .padding({ top: 8 })
  6872. .fontColor(this.themeColor)
  6873. .margin({ left: 8 })
  6874. }
  6875. }
  6876. .height('100%')
  6877. .width(100)
  6878. .layoutWeight(1)
  6879. .justifyContent(FlexAlign.Center)
  6880. .alignItems(HorizontalAlign.Start)
  6881. Column() {
  6882. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6883. Row(){
  6884. SymbolGlyph($r('sys.symbol.picture'))
  6885. .fontSize(18)
  6886. .fontColor([Color.White])
  6887. Text('获取封面')
  6888. .margin({ left: 4 })
  6889. .fontSize(11)
  6890. .fontColor(Color.White)
  6891. .fontWeight(480)
  6892. .textAlign(TextAlign.Center)
  6893. }
  6894. .justifyContent(FlexAlign.Center)
  6895. }
  6896. .height(38)
  6897. .width(100)
  6898. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6899. .backgroundColor(this.themeColor)
  6900. .stateEffect(true)
  6901. .margin({ right: 35 })
  6902. .onClick(async () => {
  6903. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  6904. this.showTipsDialog();
  6905. return; // Return empty string when no API is configured
  6906. }
  6907. const imagePath:string | undefined = await this.doSearchCover(item,
  6908. this.titleStr,this.artistStr);
  6909. console.info('onecold imagePath = '+imagePath)
  6910. if (StrUtil.isNotEmpty(imagePath)) {
  6911. //用户更改过图片
  6912. this.imagePathStr = imagePath
  6913. ToastUtil.showToast('获取封面成功')
  6914. }else{
  6915. ToastUtil.showToast('获取封面失败,请重试')
  6916. }
  6917. })
  6918. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6919. Row(){
  6920. SymbolGlyph($r('sys.symbol.input_mode'))
  6921. .fontSize(18)
  6922. .fontColor([Color.White])
  6923. Text('获取歌词')
  6924. .margin({ left: 4 })
  6925. .fontSize(11)
  6926. .fontColor(Color.White)
  6927. .fontWeight(480)
  6928. .textAlign(TextAlign.Center)
  6929. }
  6930. .justifyContent(FlexAlign.Center)
  6931. }
  6932. .height(38)
  6933. .width(100)
  6934. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6935. .backgroundColor(this.themeColor)
  6936. .stateEffect(true)
  6937. .margin({ top: 9, right: 35 })
  6938. .onClick(async () => {
  6939. //判断有没有设置api
  6940. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  6941. if (StrUtil.isEmpty(apiUrl)) {
  6942. this.isLyricSetting = false
  6943. this.showTipsDialog()
  6944. return
  6945. }
  6946. let res: string | undefined = await getApiLyric(apiUrl,
  6947. this.titleStr, this.artistStr, false);
  6948. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  6949. this.lyricConStr = res;
  6950. ToastUtil.showToast('获取歌词成功')
  6951. }else{
  6952. ToastUtil.showToast('获取歌词失败,请重试')
  6953. }
  6954. })
  6955. }
  6956. .justifyContent(FlexAlign.Start)
  6957. }
  6958. .height('100%')
  6959. .justifyContent(FlexAlign.Start)
  6960. .layoutWeight(1)
  6961. }
  6962. .width('100%')
  6963. .height(98)
  6964. Row() {
  6965. Text('标题:')
  6966. .fontSize(14)
  6967. .fontColor($r('app.color.text_color'))
  6968. .margin({ left: 22 })
  6969. TextInput({ text: item.name })
  6970. .height(40)
  6971. .maxLines(1)
  6972. .fontSize(14)
  6973. .layoutWeight(1)
  6974. .fontColor($r('app.color.text_color'))
  6975. .margin({ right: 20, left: 10 })
  6976. .onChange((val: string) => {
  6977. this.titleStr = val
  6978. })
  6979. }
  6980. .width('100%')
  6981. .margin({ top: 10, bottom: 10 })
  6982. .justifyContent(FlexAlign.Start)
  6983. Row() {
  6984. Text('艺术家:')
  6985. .fontSize(14)
  6986. .fontColor($r('app.color.text_color'))
  6987. .margin({ left: 22 })
  6988. TextInput({ text: item.artist })
  6989. .height(40)
  6990. .maxLines(1)
  6991. .fontSize(14)
  6992. .layoutWeight(1)
  6993. .fontColor($r('app.color.text_color'))
  6994. .margin({ right: 20, left: 10 })
  6995. .onChange((val: string) => {
  6996. this.artistStr = val
  6997. })
  6998. }
  6999. .width('100%')
  7000. .margin({ top: 10, bottom: 10 })
  7001. .justifyContent(FlexAlign.Start)
  7002. Row() {
  7003. Text('专辑名:')
  7004. .fontSize(14)
  7005. .fontColor($r('app.color.text_color'))
  7006. .margin({ left: 22 })
  7007. TextInput({ text: item.album })
  7008. .height(40)
  7009. .maxLines(1)
  7010. .fontSize(14)
  7011. .layoutWeight(1)
  7012. .fontColor($r('app.color.text_color'))
  7013. .margin({ right: 20, left: 10 })
  7014. .onChange((val: string) => {
  7015. this.ablumStr = val
  7016. })
  7017. }
  7018. .width('100%')
  7019. .margin({ top: 10, bottom: 10 })
  7020. .justifyContent(FlexAlign.Start)
  7021. Row() {
  7022. Column(){
  7023. Column(){
  7024. Text('歌词:')
  7025. .fontSize(14)
  7026. .fontColor($r('app.color.text_color'))
  7027. .margin({ top:9,left: 22 })
  7028. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7029. SymbolGlyph($r('sys.symbol.trash_fill'))
  7030. .fontSize(25)
  7031. .alignSelf(ItemAlign.Center)
  7032. .margin({ left: 22,top:25})
  7033. }
  7034. .backgroundColor(Color.Transparent)
  7035. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7036. Visibility.None:Visibility.Visible)
  7037. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7038. .onClick(()=>{
  7039. this.lyricConStr = ''
  7040. this.lyricContent = ''
  7041. this.tempLyricContent = ''
  7042. })
  7043. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7044. SymbolGlyph($r('sys.symbol.plus'))
  7045. .fontSize(25)
  7046. .alignSelf(ItemAlign.Center)
  7047. .margin({ left: 22,top:25})
  7048. }
  7049. .backgroundColor(Color.Transparent)
  7050. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7051. .onClick( ()=>{
  7052. this.callFilePickerSelectFileForLyric()
  7053. })
  7054. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7055. SymbolGlyph($r('sys.symbol.traditional_square'))
  7056. .fontSize(25)
  7057. .alignSelf(ItemAlign.Center)
  7058. .margin({ left: 22,top:25})
  7059. }
  7060. .backgroundColor(Color.Transparent)
  7061. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7062. Visibility.None:Visibility.Visible)
  7063. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7064. .onClick( ()=>{
  7065. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  7066. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  7067. })
  7068. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7069. Image($r('app.media.jianti'))
  7070. .height(25)
  7071. .fillColor($r('app.color.text_color'))
  7072. .alignSelf(ItemAlign.Center)
  7073. .margin({ left: 22,top:25})
  7074. }
  7075. .backgroundColor(Color.Transparent)
  7076. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7077. Visibility.None:Visibility.Visible)
  7078. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7079. .onClick( ()=>{
  7080. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  7081. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  7082. })
  7083. }
  7084. .layoutWeight(1)
  7085. }
  7086. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  7087. this.tempLyricContent })
  7088. .type(TextAreaType.NORMAL)
  7089. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  7090. .fontSize(14)
  7091. .layoutWeight(1)
  7092. .fontColor($r('app.color.text_color'))
  7093. .margin({ right: 20, left: 10 })
  7094. .onChange((val: string) => {
  7095. this.lyricConStr = val
  7096. })
  7097. }
  7098. .width('100%')
  7099. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  7100. .margin({ top: 10, bottom: 10 })
  7101. .justifyContent(FlexAlign.Start)
  7102. Row() {
  7103. Text('年份:')
  7104. .fontSize(14)
  7105. .fontColor($r('app.color.text_color'))
  7106. .margin({ left: 22 })
  7107. TextInput({ text: item.year })
  7108. .height(40)
  7109. .maxLines(1)
  7110. .fontSize(14)
  7111. .type(InputType.Number)
  7112. .layoutWeight(1)
  7113. .fontColor($r('app.color.text_color'))
  7114. .margin({ right: 20, left: 10 })
  7115. .onChange((val: string) => {
  7116. this.yearStr = val
  7117. })
  7118. }
  7119. .width('100%')
  7120. .margin({ top: 10, bottom: 10 })
  7121. .justifyContent(FlexAlign.Start)
  7122. Row() {
  7123. Text('音轨号:')
  7124. .fontSize(14)
  7125. .fontColor($r('app.color.text_color'))
  7126. .margin({ left: 22 })
  7127. TextInput({ text:item.track=='未知'?'': item.track })
  7128. .height(40)
  7129. .maxLines(1)
  7130. .fontSize(14)
  7131. .type(InputType.Number)
  7132. .layoutWeight(1)
  7133. .fontColor($r('app.color.text_color'))
  7134. .margin({ right: 20, left: 10 })
  7135. .onChange((val: string) => {
  7136. this.trackStr = val
  7137. })
  7138. }
  7139. .width('100%')
  7140. .margin({ top: 10, bottom: 10 })
  7141. .justifyContent(FlexAlign.Start)
  7142. Row() {
  7143. Text('碟号:')
  7144. .fontSize(14)
  7145. .fontColor($r('app.color.text_color'))
  7146. .margin({ left: 22 })
  7147. TextInput({ text:item.disc })
  7148. .height(40)
  7149. .maxLines(1)
  7150. .fontSize(14)
  7151. .type(InputType.Number)
  7152. .layoutWeight(1)
  7153. .fontColor($r('app.color.text_color'))
  7154. .margin({ right: 20, left: 10 })
  7155. .onChange((val: string) => {
  7156. this.discStr = val
  7157. })
  7158. }
  7159. .width('100%')
  7160. .margin({ top: 10, bottom: 10 })
  7161. .justifyContent(FlexAlign.Start)
  7162. Row() {
  7163. Text('风格:')
  7164. .fontSize(14)
  7165. .fontColor($r('app.color.text_color'))
  7166. .margin({ left: 22 })
  7167. TextInput({ text: item.genre })
  7168. .height(40)
  7169. .maxLines(1)
  7170. .fontSize(14)
  7171. .layoutWeight(1)
  7172. .fontColor($r('app.color.text_color'))
  7173. .margin({ right: 20, left: 10 })
  7174. .onChange((val: string) => {
  7175. this.genreStr = val
  7176. })
  7177. }
  7178. .width('100%')
  7179. .margin({ top: 10, bottom: 10 })
  7180. .justifyContent(FlexAlign.Start)
  7181. Row() {
  7182. Text('专辑艺术家:')
  7183. .fontSize(14)
  7184. .fontColor($r('app.color.text_color'))
  7185. .margin({ left: 22 })
  7186. TextInput({ text: item.ALBUMARTIST })
  7187. .height(40)
  7188. .maxLines(1)
  7189. .fontSize(14)
  7190. .layoutWeight(1)
  7191. .fontColor($r('app.color.text_color'))
  7192. .margin({ right: 20, left: 10 })
  7193. .onChange((val: string) => {
  7194. this.albumArtistStr = val
  7195. })
  7196. }
  7197. .width('100%')
  7198. .margin({ top: 10, bottom: 10 })
  7199. .justifyContent(FlexAlign.Start)
  7200. Row() {
  7201. Text('作曲:')
  7202. .fontSize(14)
  7203. .fontColor($r('app.color.text_color'))
  7204. .margin({ left: 22 })
  7205. TextInput({ text: item.COMPOSER })
  7206. .height(40)
  7207. .maxLines(1)
  7208. .fontSize(14)
  7209. .layoutWeight(1)
  7210. .fontColor($r('app.color.text_color'))
  7211. .margin({ right: 20, left: 10 })
  7212. .onChange((val: string) => {
  7213. this.composerStr = val
  7214. })
  7215. }
  7216. .width('100%')
  7217. .margin({ top: 10, bottom: 10 })
  7218. .justifyContent(FlexAlign.Start)
  7219. Row() {
  7220. Text('作词:')
  7221. .fontSize(14)
  7222. .fontColor($r('app.color.text_color'))
  7223. .margin({ left: 22 })
  7224. TextInput({ text: item.LYRICIST })
  7225. .height(40)
  7226. .maxLines(1)
  7227. .fontSize(14)
  7228. .layoutWeight(1)
  7229. .fontColor($r('app.color.text_color'))
  7230. .margin({ right: 20, left: 10 })
  7231. .onChange((val: string) => {
  7232. this.lyricistStr = val
  7233. })
  7234. }
  7235. .width('100%')
  7236. .margin({ top: 10, bottom: 10 })
  7237. .justifyContent(FlexAlign.Start)
  7238. Row() {
  7239. Text('注释:')
  7240. .fontSize(14)
  7241. .fontColor($r('app.color.text_color'))
  7242. .margin({ left: 22 })
  7243. TextInput({ text: item.COMMENT })
  7244. .height(40)
  7245. .maxLines(1)
  7246. .fontSize(14)
  7247. .layoutWeight(1)
  7248. .fontColor($r('app.color.text_color'))
  7249. .margin({ right: 20, left: 10 })
  7250. .onChange((val: string) => {
  7251. this.commentStr = val
  7252. })
  7253. }
  7254. .width('100%')
  7255. .margin({ top: 10, bottom: 10 })
  7256. .justifyContent(FlexAlign.Start)
  7257. Row() {
  7258. Button('保存')
  7259. .fontColor(Color.White)
  7260. .layoutWeight(1)
  7261. .height(50)
  7262. .width(100)
  7263. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7264. .backgroundColor(this.themeColor)
  7265. .stateEffect(true)
  7266. .margin({ right: 20, bottom: 20 })
  7267. .onClick(async () => {
  7268. this.doEdit(item)
  7269. })
  7270. Button('取消')
  7271. .fontColor(Color.White)
  7272. .layoutWeight(1)
  7273. .height(50)
  7274. .width(100)
  7275. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7276. .backgroundColor(this.themeColor)
  7277. .stateEffect(true)
  7278. .margin({ left: 20, bottom: 20 })
  7279. .onClick(async () => {
  7280. if(this.isGridMusic){
  7281. this.longItemFilePath =''
  7282. }else{
  7283. this.isShowEdit = false
  7284. }
  7285. this.setEditStrEmpty()
  7286. if(this.isShowPlay){
  7287. this.isShowEdit = false
  7288. }
  7289. })
  7290. }
  7291. .margin({
  7292. left: 38,
  7293. right: 38,
  7294. top: 10,
  7295. bottom: 10
  7296. })
  7297. .width(250)
  7298. .height(60)
  7299. }
  7300. }
  7301. .margin({ bottom: 20 })
  7302. }
  7303. setEditStrEmpty(){
  7304. this.imagePathStr = ''
  7305. this.lyricConStr = ''
  7306. this.artistStr = ''
  7307. this.titleStr = ''
  7308. this.ablumStr = ''
  7309. this.genreStr = ''
  7310. this.yearStr = ''
  7311. this.trackStr = ''
  7312. this.albumArtistStr = ''
  7313. this.composerStr = ''
  7314. this.lyricistStr = ''
  7315. this.commentStr = ''
  7316. this.discStr = ''
  7317. }
  7318. initEditFields(item?: VideoItem) {
  7319. if (!item) {
  7320. this.setEditStrEmpty()
  7321. return
  7322. }
  7323. this.imagePathStr = ''
  7324. this.titleStr = item.name ?? ''
  7325. this.artistStr = item.artist ?? ''
  7326. this.ablumStr = item.album ?? ''
  7327. this.genreStr = item.genre ?? ''
  7328. this.yearStr = item.year ?? ''
  7329. this.trackStr = item.track ?? ''
  7330. this.albumArtistStr = item.ALBUMARTIST ?? ''
  7331. this.composerStr = item.COMPOSER ?? ''
  7332. this.lyricistStr = item.LYRICIST ?? ''
  7333. this.commentStr = item.COMMENT ?? ''
  7334. this.discStr = item.disc ?? ''
  7335. this.lyricConStr = item.lyricContent ?? ''
  7336. }
  7337. private syncEditedFields(target?: VideoItem) {
  7338. if (!target) {
  7339. return
  7340. }
  7341. target.name = this.titleStr
  7342. target.artist = this.artistStr
  7343. target.album = this.ablumStr
  7344. target.lyricContent = this.lyricConStr
  7345. target.year = this.yearStr
  7346. target.genre = this.genreStr
  7347. target.track = this.trackStr
  7348. target.ALBUMARTIST = this.albumArtistStr
  7349. target.COMPOSER = this.composerStr
  7350. target.LYRICIST = this.lyricistStr
  7351. target.COMMENT = this.commentStr
  7352. target.disc = this.discStr
  7353. }
  7354. private replaceItemInList(list: Array<VideoItem> | undefined, filePath: string,
  7355. apply?: (next: Array<VideoItem>) => void) {
  7356. if (!list || ArrayUtil.isEmpty(list)) {
  7357. return
  7358. }
  7359. const index = list.findIndex((video: VideoItem) => video.filePath === filePath)
  7360. if (index < 0) {
  7361. return
  7362. }
  7363. const nextList = [...list]
  7364. this.syncEditedFields(nextList[index])
  7365. apply?.(nextList)
  7366. }
  7367. private syncListsAfterEdit(filePath: string) {
  7368. this.replaceItemInList(this.videoLocalList, filePath, (next: Array<VideoItem>) => {
  7369. this.videoLocalList = next
  7370. this.dataSource.pushArrayData(next)
  7371. })
  7372. this.replaceItemInList(this.songList, filePath, (next: Array<VideoItem>) => {
  7373. this.songList = next
  7374. this.sonDataSource.pushArrayData(next)
  7375. })
  7376. this.replaceItemInList(this.favList, filePath, (next: Array<VideoItem>) => {
  7377. this.favList = next
  7378. })
  7379. this.replaceItemInList(this.historyList, filePath, (next: Array<VideoItem>) => {
  7380. this.historyList = next
  7381. })
  7382. this.replaceItemInList(this.currentSongList, filePath, (next: Array<VideoItem>) => {
  7383. this.currentSongList = next
  7384. })
  7385. this.replaceItemInList(this.mediaKuList, filePath, (next: Array<VideoItem>) => {
  7386. this.mediaKuList = next
  7387. })
  7388. this.replaceItemInList(this.filteredList, filePath, (next: Array<VideoItem>) => {
  7389. this.filteredList = next
  7390. })
  7391. this.replaceItemInList(this.artistList, filePath, (next: Array<VideoItem>) => {
  7392. this.artistList = next
  7393. })
  7394. this.replaceItemInList(this.albumList, filePath, (next: Array<VideoItem>) => {
  7395. this.albumList = next
  7396. })
  7397. this.listRefreshKey++
  7398. }
  7399. @Builder
  7400. detailSheet(item:VideoItem) {
  7401. Scroll() {
  7402. Column() {
  7403. this.songDetail(item)
  7404. }
  7405. }
  7406. .width('100%')
  7407. .height('100%')
  7408. }
  7409. @Builder
  7410. songDetail(currentItem:VideoItem) {
  7411. Column() {
  7412. if (currentItem) {
  7413. Row() {
  7414. Stack() {
  7415. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.music_red') :
  7416. currentItem.pixelMapPath)
  7417. .fillColor(this.themeColor)
  7418. .height(80)
  7419. .width(80)
  7420. .borderRadius(10)
  7421. .opacity(this.opacityItem)// 绑定透明度
  7422. .margin({ left: 22 })
  7423. }
  7424. Column() {
  7425. Column() {
  7426. Text(currentItem.name)
  7427. .fontSize(16)
  7428. .maxLines(1)
  7429. .animation({
  7430. duration: 555,
  7431. curve: 'Linear',
  7432. })
  7433. .fontColor($r('app.color.text_color'))
  7434. .margin({ left: 15 })
  7435. }
  7436. .height('100%')
  7437. .width('100%')
  7438. .justifyContent(FlexAlign.Center)
  7439. .alignItems(HorizontalAlign.Start)
  7440. }
  7441. .height('100%')
  7442. }
  7443. .width('100%')
  7444. .height(90)
  7445. .justifyContent(FlexAlign.SpaceBetween)
  7446. Row() {
  7447. Text('艺术家:')
  7448. .fontSize(14)
  7449. .fontColor($r('app.color.text_color'))
  7450. .margin({ left: 22 })
  7451. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  7452. .fontSize(14)
  7453. .fontColor($r('app.color.text_color'))
  7454. .margin({ left: 10 })
  7455. .layoutWeight(1)
  7456. }
  7457. .width('100%')
  7458. .margin({ top: 10, bottom: 10 })
  7459. .justifyContent(FlexAlign.Start)
  7460. Row() {
  7461. Text('专辑名:')
  7462. .fontSize(14)
  7463. .fontColor($r('app.color.text_color'))
  7464. .margin({ left: 22 })
  7465. Text(currentItem?.album ?currentItem.album : '未知专辑')
  7466. .fontSize(14)
  7467. .margin({ left: 10 })
  7468. .fontColor($r('app.color.text_color'))
  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(StrUtil.isEmpty(currentItem.duration)?
  7480. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  7481. .fontSize(14)
  7482. .margin({ left: 10 })
  7483. .fontColor($r('app.color.text_color'))
  7484. .layoutWeight(1)
  7485. }
  7486. .width('100%')
  7487. .margin({ top: 10, bottom: 10 })
  7488. .justifyContent(FlexAlign.Start)
  7489. Row() {
  7490. Text('采样率:')
  7491. .fontSize(14)
  7492. .fontColor($r('app.color.text_color'))
  7493. .margin({ left: 22 })
  7494. Text(Utility.convertToKHz(currentItem.sampleRate))
  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(currentItem.bit_rate)
  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.bits_per_raw_sample} bits`)
  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.channels}`)
  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.channel_layout}`)
  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.start_time}`)
  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.genre)
  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.year)
  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.probe_score+"")
  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.track)
  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.disc)
  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.ALBUMARTIST)
  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.COMPOSER)
  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.LYRICIST)
  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.COMMENT)
  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(Utility.formatMimeType(currentItem.mimeType))
  7705. .fontSize(14)
  7706. .margin({ left: 10 })
  7707. .fontColor($r('app.color.text_color'))
  7708. .layoutWeight(1)
  7709. }
  7710. .width('100%')
  7711. .margin({ top: 10, bottom: 10 })
  7712. .justifyContent(FlexAlign.Start)
  7713. Row() {
  7714. Text('播放次数:')
  7715. .fontSize(14)
  7716. .fontColor($r('app.color.text_color'))
  7717. .margin({ left: 22 })
  7718. Text(currentItem.playCount?.toString())
  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.nb_streams?.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.size)
  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.fileName)
  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.cTime)
  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.filePath)
  7789. .fontSize(12)
  7790. .margin({ left: 10 })
  7791. .fontColor($r('app.color.text_color'))
  7792. .layoutWeight(1)
  7793. }
  7794. .margin({ top: 10, bottom: 10 })
  7795. .width('100%')
  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.lyricContent)
  7803. .fontSize(12)
  7804. .copyOption(CopyOptions.InApp)
  7805. .margin({ left: 10 })
  7806. .fontColor($r('app.color.text_color'))
  7807. .layoutWeight(1)
  7808. }
  7809. .margin({ top: 10, bottom: 10 })
  7810. .width('100%')
  7811. .justifyContent(FlexAlign.Start)
  7812. }
  7813. }
  7814. .margin({ bottom: 20 })
  7815. }
  7816. //定时关闭布局
  7817. @Builder
  7818. TimeCloseSheet() {
  7819. Scroll() {
  7820. Column() {
  7821. this.TimeClose()
  7822. }
  7823. }
  7824. .width('100%')
  7825. .height('100%')
  7826. }
  7827. //倒计时关闭音乐,退出App功能实现。
  7828. @State selectedMinutes: number = 0 // 0表示未开启
  7829. @State remainingSeconds: number = 0
  7830. // 预设时间选项
  7831. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  7832. private formatTime(seconds: number): string {
  7833. const mins = Math.floor(seconds / 60)
  7834. const secs = seconds % 60
  7835. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  7836. }
  7837. // 开始倒计时
  7838. private handleTimeSelect(minutes: number) {
  7839. if (minutes === this.selectedMinutes) {
  7840. this.stopCountdown();
  7841. this.selectedMinutes = 0;
  7842. return;
  7843. }
  7844. this.selectedMinutes = minutes;
  7845. this.remainingSeconds = minutes * 60;
  7846. this.startCountdown(); // 新增调用
  7847. }
  7848. @Builder
  7849. TimeClose() {
  7850. Column() {
  7851. // 倒计时显示区域
  7852. Text(this.selectedMinutes > 0 ?
  7853. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  7854. "定时关闭未开启")
  7855. .fontSize(17)
  7856. .fontColor($r('app.color.text_color'))
  7857. .margin({ top: 2, bottom: 8 });
  7858. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  7859. ForEach(this.presetTimes, (minutes: number, index: number) => {
  7860. // 单行时间选项容器
  7861. Row() {
  7862. // 文字描述区域
  7863. Text(this.getDisplayText(minutes))
  7864. .fontSize(15)
  7865. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  7866. $r('app.color.text_color'))// 选中态颜色变化
  7867. .textAlign(TextAlign.Start)
  7868. .layoutWeight(1); // 占据剩余空间
  7869. // 复选框样式的选择器
  7870. Row() {
  7871. if (minutes === this.selectedMinutes) {
  7872. // 选中状态 - 带勾号的圆形复选框
  7873. Row() {
  7874. // 使用系统内置的勾号图标
  7875. Image($r('sys.media.ohos_ic_public_ok'))
  7876. .width(14)
  7877. .height(14)
  7878. .fillColor(Color.White)
  7879. }
  7880. .width(24)
  7881. .height(24)
  7882. .borderRadius(12)
  7883. .backgroundColor(this.themeColor)
  7884. .justifyContent(FlexAlign.Center)
  7885. .alignItems(VerticalAlign.Center)
  7886. } else {
  7887. // 未选中状态的圆形边框
  7888. Row()
  7889. .width(24)
  7890. .height(24)
  7891. .borderRadius(12)
  7892. .border({
  7893. width: 2,
  7894. color: $r('app.color.text_color'),
  7895. style: BorderStyle.Solid
  7896. })
  7897. .backgroundColor(Color.Transparent)
  7898. }
  7899. }
  7900. .width(24)
  7901. .height(24)
  7902. .margin({ left: 20 })
  7903. .justifyContent(FlexAlign.Center)
  7904. .alignItems(VerticalAlign.Center)
  7905. }
  7906. .width('100%')
  7907. .padding({
  7908. top: 18,
  7909. bottom: 18,
  7910. left: 18,
  7911. right: 18
  7912. })
  7913. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  7914. $r('app.color.bottom_control_background')) // 选中背景高亮
  7915. .borderRadius(12)
  7916. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7917. .margin({ bottom: 18 })
  7918. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  7919. });
  7920. }
  7921. .width('100%')
  7922. .padding(16)
  7923. }
  7924. }
  7925. // 获取显示文本
  7926. private getDisplayText(minutes: number): string {
  7927. if (minutes === -1) {
  7928. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  7929. }
  7930. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  7931. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  7932. }
  7933. // 处理选择事件
  7934. private handleSelect(minutes: number): void {
  7935. if (minutes === -1) { // 自定义
  7936. // 弹出自定义时间对话框
  7937. DialogHelper.showTextInputDialog({
  7938. title: '自定义时间',
  7939. maskColor: Color.Transparent,
  7940. inputType: InputType.Number,
  7941. text: '',
  7942. onChange: (text) => {
  7943. console.error("onChange: " + text);
  7944. },
  7945. onAction: (action, dialogId, content) => {
  7946. if (action == DialogAction.TWO) {
  7947. const customMinutes = Number(content);
  7948. if (customMinutes > 0) {
  7949. this.handleTimeSelect(customMinutes); // 设置自定义时间
  7950. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  7951. }
  7952. }
  7953. }
  7954. });
  7955. } else {
  7956. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  7957. }
  7958. }
  7959. // 添加定时器引用
  7960. private timerId: number = -1;
  7961. // 启动/重置倒计时
  7962. private startCountdown() {
  7963. // 清除旧定时器
  7964. if (this.timerId !== -1) {
  7965. clearInterval(this.timerId);
  7966. }
  7967. // 创建新定时器
  7968. if (this.selectedMinutes > 0) {
  7969. this.timerId = setInterval(() => {
  7970. if (this.remainingSeconds === 15) {
  7971. this.showConfirmationDialog();
  7972. }
  7973. if (this.remainingSeconds > 0) {
  7974. this.remainingSeconds -= 1;
  7975. } else {
  7976. this.stopCountdown();
  7977. this.handleTimeout();
  7978. }
  7979. }, 1000);
  7980. }
  7981. }
  7982. // 15倒计时后再次提示显示确认是否关闭App对话框
  7983. private showConfirmationDialog() {
  7984. DialogHelper.showAlertDialog({
  7985. backgroundColor: $r('app.color.btn_green'),
  7986. title: '确认关闭',
  7987. maskColor: Color.Transparent,
  7988. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  7989. borderStyle: BorderStyle.Dashed,
  7990. primaryButton: '暂不关闭',
  7991. secondaryButton: '确定',
  7992. onAction: (action) => {
  7993. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  7994. this.stopCountdown();
  7995. this.selectedMinutes = 0
  7996. } else if (action == DialogAction.TWO) {
  7997. }
  7998. }
  7999. })
  8000. }
  8001. // 停止倒计时
  8002. private stopCountdown() {
  8003. if (this.timerId !== -1) {
  8004. clearInterval(this.timerId);
  8005. this.timerId = -1;
  8006. }
  8007. }
  8008. // 超时处理
  8009. private handleTimeout() {
  8010. // 执行播放器关闭逻辑
  8011. this.selectedMinutes = 0;
  8012. ToastUtil.showToast(" 定时关闭已完成");
  8013. this.stop(); // 假设存在的播放器实例
  8014. //退出APP
  8015. const mContext = getContext(this) as common.UIAbilityContext
  8016. mContext.terminateSelf();
  8017. AvSessionController.getInstance(true).unregisterSessionListener()
  8018. }
  8019. //倒计时关闭音乐,退出App功能实现结束。
  8020. //播放列表的拖动List 重新排序
  8021. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  8022. //左滑操作 移动文件 重命名 删除等操作
  8023. @Builder
  8024. sonButton(item: VideoItem, index: number, filePath: string) {
  8025. Row() {
  8026. //加入下一首播放
  8027. Button() {
  8028. Image($r('app.media.next_to_play'))
  8029. .fillColor(Color.White)
  8030. .width(20)
  8031. }
  8032. .width(40)
  8033. .height(40)
  8034. .type(ButtonType.Circle)
  8035. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8036. .backgroundColor(this.themeColor)
  8037. .margin(5)
  8038. .onClick(() => {
  8039. this.addToNextPlay(item);
  8040. })
  8041. Button() {
  8042. Image($r('app.media.close'))
  8043. .fillColor(Color.White)
  8044. .width(20)
  8045. }
  8046. .width(40)
  8047. .height(40)
  8048. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8049. .type(ButtonType.Circle)
  8050. .backgroundColor(this.themeColor)
  8051. .margin(5)
  8052. .onClick(() => {
  8053. this.songList.splice(Number(index), 1)
  8054. this.sonDataSource.pushArrayData(this.songList)
  8055. })
  8056. Button() {
  8057. Image($r('app.media.share2'))
  8058. .fillColor(Color.White)
  8059. .width(20)
  8060. }
  8061. .width(40)
  8062. .height(40)
  8063. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8064. .type(ButtonType.Circle)
  8065. .backgroundColor(this.themeColor)
  8066. .margin(5)
  8067. .onClick(() => {
  8068. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  8069. })
  8070. }
  8071. }
  8072. itemMoveSon(index: number, newIndex: number): void {
  8073. if (newIndex < 0 || newIndex >= this.songList.length) {
  8074. return;
  8075. }
  8076. let tmp = this.songList.splice(index, 1);
  8077. this.songList.splice(newIndex, 0, tmp[0]);
  8078. this.sonDataSource.pushArrayData(this.songList)
  8079. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  8080. if(this.modeType==4&&this.playlistTable){
  8081. updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
  8082. }
  8083. }
  8084. @Builder
  8085. PlayList() {
  8086. List({ scroller: this.playListScroller }) {
  8087. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  8088. ListItem() {
  8089. this.MusicItemSon(item, index)
  8090. }
  8091. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  8092. .animation({
  8093. duration: 666,
  8094. curve: 'ease-in-out' // 可选动画曲线
  8095. })
  8096. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  8097. TransitionEffect.scale({ x: 0, y: 0 })))
  8098. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  8099. //拖动List关键代码开始
  8100. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  8101. .zIndex(this.dragItem === index ? 1 : 0)
  8102. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  8103. .gesture(
  8104. GestureGroup(GestureMode.Sequence,
  8105. LongPressGesture({ repeat: true })
  8106. .onAction((event?: GestureEvent) => {
  8107. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  8108. this.scaleItem = index
  8109. })
  8110. })
  8111. .onActionEnd(() => {
  8112. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  8113. this.scaleItem = -1
  8114. })
  8115. }),
  8116. PanGesture({ fingers: 1, direction: null, distance: 0 })
  8117. .onActionStart(() => {
  8118. this.dragItem = index // 记录当前拖动项索引
  8119. this.dragRefOffset = 0 // 重置偏移基准
  8120. })
  8121. .onActionUpdate((event: GestureEvent) => {
  8122. this.offsetY = event.offsetY - this.dragRefOffset;
  8123. this.neighborItem = -1;
  8124. let indexA = this.songList.indexOf(item);
  8125. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  8126. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  8127. let value: number = 0;
  8128. if (this.offsetY < 0) {
  8129. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  8130. this.neighborItem = indexA - 1;
  8131. this.neighborScale = 1 - value / 20;
  8132. } else if (this.offsetY > 0) {
  8133. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  8134. this.neighborItem = indexA + 1;
  8135. this.neighborScale = 1 - value / 20;
  8136. }
  8137. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  8138. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8139. this.offsetY -= this.ITEM_INTV;
  8140. this.dragRefOffset += this.ITEM_INTV;
  8141. this.itemMoveSon(indexA, indexA + 1);
  8142. });
  8143. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  8144. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8145. this.offsetY += this.ITEM_INTV;
  8146. this.dragRefOffset -= this.ITEM_INTV;
  8147. this.itemMoveSon(indexA, indexA - 1);
  8148. });
  8149. }
  8150. })
  8151. .onActionEnd((event: GestureEvent) => {
  8152. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8153. this.dragItem = -1
  8154. this.neighborItem = -1
  8155. })
  8156. animateTo({
  8157. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  8158. }, () => {
  8159. this.scaleItem = -1
  8160. })
  8161. })
  8162. )
  8163. .onCancel(() => {
  8164. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8165. this.dragItem = -1
  8166. this.neighborItem = -1
  8167. })
  8168. animateTo({
  8169. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  8170. }, () => {
  8171. this.scaleItem = -1
  8172. })
  8173. })
  8174. ) //拖动List关键代码结束
  8175. .onClick(() => {
  8176. this.doPlay(item, index, true)
  8177. })
  8178. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  8179. }
  8180. .width('100%')
  8181. .height('100%')
  8182. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  8183. // .animation({ duration: 500, curve: Curve.Ease }))
  8184. .cachedCount(10)
  8185. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  8186. .gesture(PinchGesture({ fingers: 2 })
  8187. .onActionEnd((event: GestureEvent) => {
  8188. this.setSonListTwoFingers()
  8189. })
  8190. .onActionUpdate(e => {
  8191. this.scaleValue = this.pinchValue * e.scale
  8192. })
  8193. .onActionStart(e => {
  8194. }))
  8195. .padding({
  8196. bottom: 0
  8197. })
  8198. }
  8199. setSonListTwoFingers() {
  8200. this.pinchValue = this.scaleValue;
  8201. Logger.info('this.pinchValue = ' + this.pinchValue);
  8202. if (this.pinchValue >= 1) {
  8203. this.sonTwoFingerType++
  8204. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  8205. if (this.sonTwoFingerType > 3) {
  8206. this.sonTwoFingerType = 1
  8207. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  8208. }
  8209. } else {
  8210. this.sonTwoFingerType--
  8211. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  8212. if (this.sonTwoFingerType < 1) {
  8213. this.sonTwoFingerType = 1
  8214. }
  8215. }
  8216. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  8217. this.pinchValue = 1;
  8218. this.scaleValue = 1;
  8219. }
  8220. @State sonTwoFingerType:number = 3
  8221. @Builder
  8222. private MusicItemSon(item: VideoItem, index?: number) {
  8223. Button({ type: ButtonType.Normal, stateEffect: true }) {
  8224. Row() {
  8225. Stack() {
  8226. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  8227. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  8228. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  8229. .alt($r('app.media.music_red'))
  8230. .fillColor(this.themeColor)
  8231. .borderRadius('100%')
  8232. .clip(true)
  8233. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  8234. .draggable(false)// 禁止长按手势拖动
  8235. .autoResize(true) // 重采样,可减少内存占用
  8236. .margin({ left: 20 })
  8237. }
  8238. .width('15%')
  8239. Column() {
  8240. Column() {
  8241. Text(this.isShowFileName?item.fileName :item.name)
  8242. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  8243. .fontColor(this.curIndex === index ? this.themeColor :
  8244. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  8245. .maxLines(1)
  8246. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  8247. Row() {
  8248. Column(){
  8249. Text(item.md5Str?.includes('Lossless')?
  8250. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  8251. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  8252. .padding({ top: 3,right:6,left:6,bottom:3 })
  8253. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  8254. $r('app.color.text_color'))
  8255. .fontWeight(500)
  8256. .borderRadius(12)
  8257. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  8258. .backgroundColor('#FFC107')
  8259. }
  8260. .padding({ top: 8 })
  8261. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  8262. item.artist + ' ' + item?.duration)
  8263. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  8264. .padding({ top: 8 })
  8265. .maxLines(1)
  8266. .fontColor(this.curIndex === index ? this.themeColor :
  8267. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  8268. .margin({ left: this.sonTwoFingerType == 3 ? 5 : 3 })
  8269. Blank()
  8270. Text(item.size)
  8271. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  8272. .padding({ top: 8 })
  8273. .maxLines(1)
  8274. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  8275. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  8276. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  8277. .margin({ left: 10 })
  8278. }
  8279. }
  8280. .height('100%')
  8281. .width('100%')
  8282. .justifyContent(FlexAlign.Center)
  8283. .alignItems(HorizontalAlign.Start)
  8284. }
  8285. .height('100%')
  8286. .width('65%')
  8287. Column() {
  8288. ImageAnimator()
  8289. .images(this.imagesF)// 动画数组
  8290. .duration(1000)// 持续
  8291. .state(this.animationState)// 动画状态
  8292. .fillMode(FillMode.Forwards)
  8293. .width(18)
  8294. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  8295. Visibility.None)
  8296. .height(18)
  8297. .iterations(-1) // 播放次数
  8298. }
  8299. .width('20%')
  8300. }
  8301. }
  8302. .backgroundColor(Color.Transparent)
  8303. .width('100%')
  8304. .reuseId('son_item')
  8305. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  8306. .shadow(this.scaleItem === index ? {
  8307. radius: 70,
  8308. color: '#15000000',
  8309. offsetX: 0,
  8310. offsetY: 0
  8311. } :
  8312. {
  8313. radius: 0,
  8314. color: '#15000000',
  8315. offsetX: 0,
  8316. offsetY: 0
  8317. })
  8318. .animation({ curve: Curve.Sharp, duration: 300 })
  8319. }
  8320. @Builder
  8321. MusicPlayBuilder() {
  8322. Column() {
  8323. this.IjkMusicPlayerView()
  8324. }
  8325. .transition(TransitionEffect.asymmetric(
  8326. TransitionEffect.opacity(1),
  8327. TransitionEffect.OPACITY
  8328. ))
  8329. .visualEffect(deviceInfo.sdkApiVersion>=20&&this.bgController?
  8330. new hdsEffect.HdsEffectBuilder()
  8331. .shaderEffect({
  8332. effectType: hdsEffect.EffectType.UV_BACKGROUND_FLOW_LIGHT,
  8333. animation: {
  8334. duration: 10000,
  8335. iterations: -1,
  8336. autoPlay: true,
  8337. onFinish: ()=> {
  8338. console.info('Succeeded in finishing');
  8339. }
  8340. },
  8341. controller: this.bgController,
  8342. })
  8343. .buildEffect():null)
  8344. .height('100%')
  8345. .width('100%')
  8346. .onDisAppear(() => {
  8347. this.translateY = 0;
  8348. })
  8349. .translate({ y: this.translateY })
  8350. .gesture(
  8351. PanGesture(this.panOption)
  8352. .onActionUpdate((event?: GestureEvent) => {
  8353. if (event) {
  8354. // 只允许向下滑动,向上滑动时限制为0
  8355. this.translateY = Math.max(0, event.offsetY);
  8356. this.getUIContext().animateTo({
  8357. duration: 500,
  8358. curve: Curve.Sharp
  8359. }, () => {
  8360. this.scaleValueImage = Math.min(1, Math.max(0.3, 1 - event.offsetY / 350));
  8361. console.info('onecold scaleValueImage:', this.scaleValueImage)
  8362. this.scaleValueText =Math.min(1, Math.max(0.6, 1 - event.offsetY / 400));
  8363. })
  8364. }
  8365. })
  8366. .onActionEnd((event?: GestureEvent) => {
  8367. // 使用更低的阈值和滑动速度判断
  8368. const minDistance = 300; // 最小滑动距离 100vp
  8369. const minVelocity = 500; // 最小滑动速度
  8370. // 获取滑动速度(如果可用)
  8371. const velocity = event?.velocityY || 0;
  8372. // 判断是否应该关闭:距离足够 或者 速度足够快
  8373. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  8374. if (shouldClose) {
  8375. // 添加关闭动画
  8376. this.getUIContext().animateTo({
  8377. duration: 600,
  8378. curve: Curve.Friction
  8379. }, () => {
  8380. this.isShowPlay = false;
  8381. this.scaleValueImage = 1
  8382. this.scaleValueText = 1
  8383. this.translateY = 0;
  8384. })
  8385. } else {
  8386. // 回弹动画
  8387. this.getUIContext().animateTo({
  8388. duration: 600,
  8389. curve: Curve.Friction
  8390. }, () => {
  8391. this.scaleValueImage = 1
  8392. this.scaleValueText = 1
  8393. this.translateY = 0;
  8394. })
  8395. }
  8396. })
  8397. )
  8398. }
  8399. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  8400. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  8401. HeightBreakpoint.HEIGHT_LG;
  8402. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  8403. @State topBarHeight: number = 50
  8404. @State barOpacity: number = 1
  8405. @State barBottomOpacity: number = 1
  8406. private hideDone: boolean = false;
  8407. @State currentYOffset: number = 0;
  8408. @State bottomBarHeight: number = 68;
  8409. private isHiding: boolean = false;
  8410. //是否是Pura X外屏,或者小屏幕
  8411. isPuraWP() {
  8412. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  8413. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  8414. }
  8415. //是否是Pura X外屏,或者小屏幕,手机横屏
  8416. /**
  8417. * 是否是Pura X外屏,或者小屏幕,手机横屏
  8418. * @returns
  8419. */
  8420. isCoverOpacity() {
  8421. if (this.isPuraWP()) {
  8422. return true
  8423. }
  8424. if (this.isPhoneLan()) {
  8425. return true
  8426. }
  8427. if (deviceInfo.marketName.includes('Pura X')
  8428. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  8429. return true
  8430. }
  8431. return false
  8432. }
  8433. //是不是手机横屏
  8434. isPhoneLan() {
  8435. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  8436. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  8437. LogUtil.info('hicar isPhoneLan width= ' + this.windowWidth);
  8438. LogUtil.info('hicar isPhoneLan height= ' + this.windowHeight);
  8439. LogUtil.info(`twocold hicarWindow size: ${this.windowWidth}x${this.windowHeight}, this.isHiCarStatus: ${this.isHiCarStatus}`);
  8440. LogUtil.info(`twocold hicar Window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall: ${this.isHiCarSmall()}`);
  8441. if (this.isHiCarKuanBianPing()) {
  8442. return true
  8443. }
  8444. if (this.isHiCar()) {
  8445. return false
  8446. }
  8447. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8448. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  8449. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  8450. return true
  8451. }
  8452. return false
  8453. }
  8454. //是不是1920x720的hicar的屏幕分辨率
  8455. isHiCarKuanBianPing(){
  8456. if(!this.isHiCar()){
  8457. return false
  8458. }
  8459. const hiCarAspectRatios: HiCarAspectRatio[] = [
  8460. { ratio: 1920 / 720, name: "1920x720" },
  8461. ];
  8462. const currentRatio: number = this.windowWidth / this.windowHeight;
  8463. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  8464. LogUtil.info('twocold isHiCarKuanBianPing currentRatio = ' + currentRatio)
  8465. for (const hiCarRatio of hiCarAspectRatios) {
  8466. LogUtil.info('twocold isHiCarKuanBianPing hiCarRatio= ' + hiCarRatio.ratio)
  8467. LogUtil.info('twocold isHiCarKuanBianPing Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  8468. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  8469. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  8470. //宽扁平的尺寸设置列表展示
  8471. this.twoFingerType ==3
  8472. this.isGridMusic = false
  8473. return true;
  8474. }
  8475. }
  8476. return false;
  8477. }
  8478. //是不是hicar的屏幕分辨率
  8479. isHiCarSmall() {
  8480. if(!this.isHiCar()){
  8481. return false
  8482. }
  8483. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  8484. {
  8485. this.columns = 6
  8486. return false
  8487. }
  8488. const hiCarAspectRatios: HiCarAspectRatio[] = [
  8489. { ratio: 800 / 480, name: "800x480" },
  8490. { ratio: 1280 / 720, name: "1280x720" },
  8491. { ratio: 1920 / 1080, name: "1920x1080" },
  8492. ];
  8493. const currentRatio: number = this.windowWidth / this.windowHeight;
  8494. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  8495. LogUtil.info('twocold isHiCarSmall currentRatio = ' + currentRatio)
  8496. for (const hiCarRatio of hiCarAspectRatios) {
  8497. LogUtil.info('twocold isHiCarSmall hiCarRatio= ' + hiCarRatio.ratio)
  8498. LogUtil.info('twocold isHiCarSmall Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  8499. LogUtil.info('twocold isHiCarSmall isHiCarStatus= ' + this.isHiCarStatus);
  8500. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  8501. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  8502. //宽扁平的尺寸设置列表展示
  8503. return true;
  8504. }
  8505. }
  8506. return false;
  8507. }
  8508. isHiCar() {
  8509. return this.isHiCarStatus&&this.curDisplayIsHiCar;
  8510. }
  8511. //是不是正常的手机竖屏
  8512. isPhonePortrait() {
  8513. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  8514. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  8515. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  8516. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8517. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  8518. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  8519. return true
  8520. }
  8521. return false
  8522. }
  8523. @State showSpeedDialog: boolean = false
  8524. @State longPressSpeed: number = 3 //长按默认倍数
  8525. @Builder
  8526. SpeedDialog() {
  8527. Stack() {
  8528. Column() {
  8529. Text('已切换至' + this.longPressSpeed + '倍速播放')
  8530. .fontColor(Color.White)
  8531. .visibility(Visibility.Hidden)
  8532. }
  8533. .backgroundColor(Color.Black)
  8534. .borderRadius(20)
  8535. .padding({
  8536. top: 10,
  8537. right: 20,
  8538. left: 15,
  8539. bottom: 20
  8540. })
  8541. .opacity(0.6)
  8542. Text('已切换至' + this.longPressSpeed + '倍速播放')
  8543. .fontColor(Color.White)
  8544. }
  8545. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  8546. .zIndex(5)
  8547. .margin({ top: 80 })
  8548. }
  8549. @Builder
  8550. IjkMusicPlayerView() {
  8551. Stack() {
  8552. if(canIUse("SystemCapability.UIDesign.HDSComponent.Core")
  8553. &&deviceInfo.sdkApiVersion>=20&&this.sceneBgController){
  8554. HdsVisualComponent()
  8555. .scene(HdsSceneType.DUAL_EDGE_FLOW_LIGHT_WITH_BACKGROUND_MASK, this.sceneBgController, () => {
  8556. console.info('Succeeded in finishing');
  8557. })
  8558. .width('100%')
  8559. .height('100%')
  8560. .visibility(this.isShowBgLiuGUANG?Visibility.Visible:Visibility.None)
  8561. }
  8562. Column() {
  8563. Column() {
  8564. //播放标题
  8565. Column() {
  8566. this.PlayTitle()
  8567. }
  8568. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  8569. .width('100%')
  8570. .margin({ top: 0 })
  8571. .height(PlayConstants.HEIGHT)
  8572. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  8573. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  8574. if (this.showSpeedDialog) {
  8575. this.SpeedDialog()
  8576. }
  8577. Stack() {
  8578. //手势拖动快进
  8579. Column()
  8580. .width(CommonConstants.FULL_PERCENT)
  8581. .height('100%')
  8582. .gesture(
  8583. GestureGroup(GestureMode.Parallel,
  8584. // 长按屏幕倍数播放
  8585. LongPressGesture({ repeat: true })
  8586. .onAction(() => {
  8587. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8588. this.showSpeedDialog = true;
  8589. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  8590. }
  8591. })
  8592. .onActionEnd(() => {
  8593. this.showSpeedDialog = false;
  8594. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  8595. }),
  8596. //双击屏幕暂停或者播放
  8597. TapGesture({ count: 2 })
  8598. .onAction((event: GestureEvent) => {
  8599. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8600. ToastUtil.showToast('已暂停')
  8601. }
  8602. console.info('onecold playOrPause 6693')
  8603. this.playOrPause()
  8604. })
  8605. )
  8606. )
  8607. }
  8608. .height('65%')
  8609. Swiper() {
  8610. this.CoverInfo()
  8611. this.PlayerLyrics()
  8612. }
  8613. .onChange((index: number) => {
  8614. this.currentSwiperIndex = index
  8615. })
  8616. .indicator(false)
  8617. .displayCount(new BreakpointType({
  8618. sm: 1,
  8619. md: 2,
  8620. lg: 2,
  8621. xl: 2,
  8622. xxl: 2
  8623. }).getValue(this.currentBreakpoint))
  8624. .clip(false)
  8625. .loop(false)
  8626. .autoPlay(false)
  8627. // .interval(8000)
  8628. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  8629. .height('100%')
  8630. .hitTestBehavior(HitTestMode.Transparent)
  8631. Image($r('app.media.icon_replay'))
  8632. .objectFit(ImageFit.Auto)
  8633. .width('120px')
  8634. .height('120px')
  8635. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  8636. .border({ width: 0 })
  8637. .visibility(Visibility.None)
  8638. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  8639. .onClick(() => {
  8640. console.info('onecold startPlayOrResumePlay 6744')
  8641. this.startPlayOrResumePlay();
  8642. })
  8643. }
  8644. .width(CommonConstants.FULL_PERCENT)
  8645. .height(CommonConstants.FULL_PERCENT)
  8646. .justifyContent(FlexAlign.End)
  8647. }
  8648. .justifyContent(FlexAlign.End)
  8649. .margin({ bottom: 8 })
  8650. }
  8651. .backgroundImage(!this.isMusicBGCover||StrUtil.isEmpty(this.cover)?null: this.cover)
  8652. .backgroundImageSize(this.isPuraWP()||!this.isMusicBGCover ? { width: '100%' } : { height: '150%', width: '100%' })
  8653. .animation({
  8654. duration: 666,
  8655. curve: 'ease-in-out' // 可选动画曲线
  8656. })
  8657. .backgroundBlurStyle((this.isPuraWP() && this.currentSwiperIndex === 0) ||!this.isMusicBGCover
  8658. ? BlurStyle.NONE :
  8659. BlurStyle.BACKGROUND_ULTRA_THICK)
  8660. .hitTestBehavior(HitTestMode.Transparent)
  8661. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  8662. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  8663. .onClick(() => {
  8664. if(this.isHiCar())
  8665. return
  8666. if(this.is_auto_hide_progress){
  8667. this.is_auto_hide_progress = false
  8668. }
  8669. this.startAutoHide()
  8670. })
  8671. }
  8672. @State progressValue: number = 0;
  8673. @State currentTime: string = "00:00";
  8674. @State totalTime: string = "00:00";
  8675. @State loadingVisible: Visibility = Visibility.None;
  8676. @State replayVisible: Visibility = Visibility.None;
  8677. @State slideEnable: boolean = false;
  8678. @State aspRatio: number = 0.5;
  8679. @State mContext: object | undefined = undefined;
  8680. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  8681. @State mFirst: boolean = true;
  8682. @State mDestroyPage: boolean = false;
  8683. @State playSpeed: number = 1;
  8684. @State oldSeconds: number = 0;
  8685. @State isSeekTo: boolean = false;
  8686. @State isCurrentTime: boolean = false;
  8687. @State videoWidth: string = '100%';
  8688. @State videoHeight: string = '100%';
  8689. @State initAspectRatio: number = 1;
  8690. @State videoAspectRatio: number = this.initAspectRatio;
  8691. @State videoUrl: string = '';
  8692. private last: number = 0;
  8693. @State videoParentAspectRatio: number = this.initAspectRatio;
  8694. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  8695. @State CONTROL_PlayStatus: number = PlayStatus.INIT;
  8696. @State PROGRESS_MAX_VALUE: number = 100;
  8697. @State updateProgressTimer: number = 0;
  8698. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  8699. @State name: string = '';
  8700. // @State loop: boolean = false;
  8701. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  8702. @State multiple: string = '1.0X';
  8703. xcomponentController: XComponentController = new XComponentController()
  8704. private panOptionBright: PanGestureOptions =
  8705. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  8706. private panOptionVolume: PanGestureOptions =
  8707. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  8708. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  8709. //手势的音量控制和亮度控制
  8710. private positionX: number = PlayConstants.POSITION_X;
  8711. private positionY: number = PlayConstants.POSITION_Y;
  8712. private windowClass: window.Window = globalThis.windowClass
  8713. @State volume: number = 0.5;
  8714. @State volumeSmall: boolean = false
  8715. @State autoParseMusicName: boolean = true
  8716. @State isShowFileName: boolean = false
  8717. @State isLongNameRoLL: boolean = true//长歌名滚动
  8718. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  8719. @State bright: number = PlayConstants.BRIGHT;
  8720. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  8721. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  8722. @State screenWidth: number = 0
  8723. @State screenHeight: number = 0
  8724. @State statusBarHeight: number = 0
  8725. @State isYesFull: boolean = false
  8726. private seekValue: number = 0
  8727. @State isVideoLock: boolean = false; // Whether the video playback is locked
  8728. eventHub = getContext().eventHub;
  8729. //投播组件
  8730. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  8731. private castController: avSession.AVCastController | undefined = undefined;
  8732. @State isCastPlaying: boolean = false;
  8733. @State currentTime2: number = 0;
  8734. @State currentStringTime: string = '00:00';
  8735. @State duration: number = 0;
  8736. @State isReady: boolean = false;
  8737. @State durationTime: number = 0;
  8738. @State durationStringTime: string = '00:00';
  8739. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  8740. // @State isPlaying: boolean = false;
  8741. private castSeek: boolean = false;
  8742. private castItem: avSession.AVQueueItem | undefined = undefined;
  8743. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  8744. @State rotateAngle2: number = -9
  8745. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  8746. @State cover: string | undefined = '';
  8747. @State artist: string | undefined = ''
  8748. // 1.初始化controller
  8749. private lyricController: LyricController = new LyricController()
  8750. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  8751. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  8752. private parser = new LyricParser()
  8753. @State randomColor: string = 'rgb(0,0,0)'
  8754. @State randomShakenX: number = 0
  8755. @State randomShakenY: number = 0
  8756. @State lyricTextSize: number = 24
  8757. @State lyricContent: string = ''
  8758. @State isDebug: boolean = false
  8759. @State isHightLightCenter: boolean = true
  8760. /**
  8761. * 初始化歌词加载与展示逻辑
  8762. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  8763. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  8764. * @param isApi2 是否使用API2获取歌词(可选)
  8765. *
  8766. * 主要流程:
  8767. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  8768. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  8769. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  8770. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  8771. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  8772. * 6. 解析失败或读取失败时,清空歌词显示。
  8773. *
  8774. * 注意事项:
  8775. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  8776. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  8777. * - 歌词内容解析后通过lyricController驱动UI渲染。
  8778. */
  8779. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  8780. if (StrUtil.isEmpty(lyricPath)) {
  8781. return
  8782. }
  8783. this.initPipLyricSetting()
  8784. this.lyricControllerSingle
  8785. .setTextSize(15)
  8786. .setCacheSize(4)
  8787. .setTextColor("#FFFFFF")
  8788. .setHighlightColor("#FFFFFF")
  8789. .setHighlightScale(1.2)
  8790. .setEmptyHint("")
  8791. .setAlignMode('center')
  8792. .setAnimationDuration(500)
  8793. .setSingleLine(true)
  8794. this.lyricContent = ''
  8795. this.lyricController
  8796. .setTextSize(this.currentLyricSize)
  8797. .setCacheSize(4)
  8798. .setTextColor("#DDDDDD")
  8799. .setHighlightColor("#FFFFFF")
  8800. .setEmptyHint("")
  8801. .setAnimationDuration(1000)
  8802. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  8803. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  8804. this.setBlurDegree(this.blurDegree, false)
  8805. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  8806. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  8807. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  8808. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  8809. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  8810. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  8811. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  8812. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  8813. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  8814. this.lyricController.setTextWeight(this.lyricTextWeight)
  8815. this.showSingleLyric = false
  8816. this.timeOffset = 0
  8817. this.lyricController.setLyric(null)
  8818. this.lyricControllerSingle.setLyric(null)
  8819. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  8820. console.log("onecold lyricPath =" + lyricPath)
  8821. let neiqianLrc = ''
  8822. let lyContent = this.currentSong?.lyricContent
  8823. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  8824. neiqianLrc = lyContent
  8825. }
  8826. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast&&!isLocal&&!isLocal) {
  8827. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  8828. //赋值给this.lyricContent,播控中心才可以显示歌词
  8829. this.lyricContent = neiqianLrc
  8830. // 将文件内容按行分割成字符串数组
  8831. let lines = neiqianLrc.split('\n').map(line => line.trim());
  8832. // 3.解析歌词
  8833. let lyric = this.parser.parse(lines);
  8834. // 4.设置歌词
  8835. this.lyricController.setLyric(lyric);
  8836. this.lyricControllerXF.setLyric(lyric)
  8837. this.lyricControllerSingle.setLyric(lyric)
  8838. return
  8839. }
  8840. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  8841. && !Utility.isVideoByExtension(this.videoUrl))) {
  8842. if (this.currentSong !== undefined) {
  8843. // ToastUtil.showShort('正在为你搜索在线歌词!')
  8844. //判断是不是赞助会员,是会员的话才开启歌词功能
  8845. // if (!this.isDebug) {
  8846. // if (!Utility.isNoble()) {
  8847. // LogUtil.debug("onecold 不是赞助会员")
  8848. // return
  8849. // }
  8850. // if(!Utility.isPassInstallTime(33)){
  8851. // LogUtil.debug("onecold not pass time")
  8852. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  8853. // return
  8854. // }
  8855. // }
  8856. let artist = this.currentSong?.artist
  8857. if (artist === undefined) {
  8858. artist = ''
  8859. }
  8860. if (isApi2 === undefined) {
  8861. isApi2 = false
  8862. }
  8863. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  8864. // LogUtil.debug("onecold res =" + res)
  8865. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  8866. if (StrUtil.isNotEmpty(res)) {
  8867. this.lyricContent = res
  8868. let lines = res.split('\n').map(line => line.trim());
  8869. // 3.解析歌词
  8870. let lyric = this.parser.parse(lines);
  8871. // 4.设置歌词
  8872. this.lyricController.setLyric(lyric);
  8873. this.lyricControllerXF.setLyric(lyric)
  8874. this.lyricControllerSingle.setLyric(lyric)
  8875. this.showSingleLyric = true
  8876. // 4.保存歌词文件lyric到本地
  8877. //2025年8月28日歌词不再加密下载
  8878. this.saveDataToFile(res, lyricPath, false)
  8879. } else {
  8880. this.lyricController.setLyric(null)
  8881. this.lyricControllerXF.setLyric(null)
  8882. this.lyricControllerSingle.setLyric(null)
  8883. if (isOnLineAndToast) {
  8884. ToastUtil.showShort('未获取到歌词!')
  8885. }
  8886. }
  8887. } else {
  8888. this.lyricController.setLyric(null)
  8889. this.lyricControllerXF.setLyric(null)
  8890. this.lyricControllerSingle.setLyric(null)
  8891. if (isOnLineAndToast) {
  8892. ToastUtil.showShort('未获取到歌词!')
  8893. }
  8894. }
  8895. })
  8896. } else {
  8897. this.lyricController.setLyric(null)
  8898. this.lyricControllerXF.setLyric(null)
  8899. this.lyricControllerSingle.setLyric(null)
  8900. if (isOnLineAndToast) {
  8901. ToastUtil.showShort('未获取到歌词!')
  8902. }
  8903. }
  8904. return
  8905. }
  8906. try {
  8907. let isJiaMi = false;
  8908. let realLyricPath = lyricPath
  8909. if (FileUtil.accessSync(jiaMilyricPath)) {
  8910. isJiaMi = true
  8911. realLyricPath = jiaMilyricPath
  8912. console.info("onecold 找到加密本地歌词 ");
  8913. } else {
  8914. isJiaMi = false
  8915. realLyricPath = lyricPath
  8916. console.info("onecold 找到本地歌词 ");
  8917. }
  8918. // 3.读取文件内容并指定编码为 UTF-8
  8919. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  8920. const stat = await fileIo.stat(file.fd);
  8921. const arrayBuffer = new ArrayBuffer(stat.size);
  8922. fs.read(file.fd, arrayBuffer)
  8923. .then((readLen: number) => {
  8924. console.info("read file data succeed");
  8925. // let buf = buffer.from(arrayBuffer, 0, readLen);
  8926. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  8927. // 检查 buf 是否为空
  8928. if (buf.length === 0) {
  8929. throw new Error("Buffer is empty after reading the file");
  8930. }
  8931. try {
  8932. // 检测文件编码
  8933. // let detectedEncoding = chardet.detect(buf);
  8934. // console.info("onecoldT Detected encoding: " + detectedEncoding);
  8935. let detectedEncoding = this.detect(arrayBuffer)
  8936. console.info("onecoldT Detected encoding: " + detectedEncoding);
  8937. // 使用检测到的编码解码,解决中文乱码问题
  8938. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  8939. console.info("onecoldT Detected textDecoder: " + textDecoder);
  8940. let fileContent = textDecoder.decode(buf);
  8941. console.info(`onecoldT The content of file1: ${fileContent}`);
  8942. //解密
  8943. if (isJiaMi) {
  8944. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  8945. }
  8946. console.info(`onecold The content of file2: ${fileContent}`);
  8947. this.lyricContent = fileContent
  8948. if(isLocal){//编辑标签选择本地歌词需要赋值给this.lyricConStr
  8949. this.lyricConStr = fileContent
  8950. }
  8951. // 将文件内容按行分割成字符串数组
  8952. let lines = fileContent.split('\n').map(line => line.trim());
  8953. console.info(`onecold The content of file: ${fileContent}`);
  8954. // 3.解析歌词
  8955. let lyric = this.parser.parse(lines);
  8956. // 4.设置歌词
  8957. this.lyricController.setLyric(lyric);
  8958. this.lyricControllerXF.setLyric(lyric)
  8959. this.lyricControllerSingle.setLyric(lyric)
  8960. this.showSingleLyric = true
  8961. console.info(`The content of file: ${fileContent}`);
  8962. } catch (chardetError) {
  8963. console.error("chardet.detect failed with error: " + chardetError.message);
  8964. this.lyricController.setLyric(null);
  8965. this.lyricControllerXF.setLyric(null)
  8966. this.lyricControllerSingle.setLyric(null)
  8967. }
  8968. })
  8969. .catch((err: BusinessError) => {
  8970. this.lyricController.setLyric(null)
  8971. this.lyricControllerXF.setLyric(null)
  8972. this.lyricControllerSingle.setLyric(null)
  8973. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  8974. })
  8975. .catch((err: Error) => {
  8976. this.lyricController.setLyric(null)
  8977. this.lyricControllerXF.setLyric(null)
  8978. this.lyricControllerSingle.setLyric(null)
  8979. console.error("read file 2 data failed with error message: " + err.message);
  8980. })
  8981. .finally(() => {
  8982. fs.closeSync(file);
  8983. });
  8984. } catch (error) {
  8985. this.lyricController.setLyric(null)
  8986. this.lyricControllerSingle.setLyric(null)
  8987. this.lyricControllerXF.setLyric(null)
  8988. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  8989. }
  8990. }
  8991. detect(data: ArrayBuffer): string {
  8992. //创建检测对象
  8993. let detector: UniversalDetector = new UniversalDetector();
  8994. // 传入检测数据并实时判断编码格式
  8995. detector.handleData(data, 0, data.byteLength);
  8996. // 标记检测数据 读取结束
  8997. detector.dataEnd();
  8998. // 获取检测结果
  8999. let detected: string = detector.getDetectedCharset();
  9000. // 释放资源
  9001. detector.reset();
  9002. return detected;
  9003. }
  9004. //初始化悬浮歌词的自定义设置
  9005. initPipLyricSetting() {
  9006. this.lyricControllerXF
  9007. .setTextSize(this.currentLyricSize)
  9008. .setCacheSize(4)
  9009. .setTextColor("#DDDDDD")
  9010. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  9011. .setEmptyHint("")
  9012. .setAnimationDuration(1000)
  9013. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  9014. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  9015. this.setBlurDegree(this.blurDegreePip, true)
  9016. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  9017. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  9018. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  9019. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  9020. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  9021. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  9022. this.lyricControllerXF.setHightLightCenter(true)
  9023. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  9024. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  9025. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  9026. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  9027. if (this.pipBgIndex === 0) {
  9028. if (this.cover) {
  9029. this.pipBg = this.cover
  9030. } else {
  9031. this.pipBg = this.imageColor
  9032. }
  9033. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  9034. }
  9035. }
  9036. //根据item返回歌词内容
  9037. async getLyricContent(item: VideoItem): Promise<string> {
  9038. let neiqianLrc = ''
  9039. let lyContent = item?.lyricContent
  9040. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  9041. neiqianLrc = lyContent
  9042. return neiqianLrc
  9043. }
  9044. try {
  9045. //取数据库里面的歌词lyContent
  9046. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  9047. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  9048. console.log("onecold Lyrics:", lyricContent);
  9049. neiqianLrc = lyricContent
  9050. return neiqianLrc
  9051. }
  9052. } catch (error) {
  9053. console.error("Error fetching lyrics:", error);
  9054. }
  9055. try {
  9056. let filePath = item.filePath;
  9057. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  9058. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  9059. let isJiaMi = false;
  9060. let realLyricPath = lyricPath;
  9061. if (FileUtil.accessSync(jiaMilyricPath)) {
  9062. isJiaMi = true;
  9063. realLyricPath = jiaMilyricPath;
  9064. console.info("onecold 找到加密本地歌词");
  9065. } else {
  9066. console.info("onecold 找到本地歌词");
  9067. }
  9068. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  9069. const stat = await fileIo.stat(file.fd);
  9070. const arrayBuffer = new ArrayBuffer(stat.size);
  9071. const readLen = await fs.read(file.fd, arrayBuffer);
  9072. console.info("read file data succeed");
  9073. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  9074. if (buf.length === 0) {
  9075. throw new Error("Buffer is empty after reading the file");
  9076. }
  9077. // let detectedEncoding = chardet.detect(buf);
  9078. let detectedEncoding = this.detect(arrayBuffer)
  9079. console.info("Detected encoding: " + detectedEncoding);
  9080. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  9081. let fileContent = textDecoder.decode(buf);
  9082. console.info(`onecold The content of file1: ${fileContent}`);
  9083. if (isJiaMi) {
  9084. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  9085. }
  9086. console.info(`onecold The content of file2: ${fileContent}`);
  9087. fs.closeSync(file);
  9088. return fileContent;
  9089. } catch (error) {
  9090. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  9091. return '';
  9092. }
  9093. }
  9094. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  9095. if (StrUtil.isEmpty(filePath)) {
  9096. return
  9097. }
  9098. try {
  9099. //将content进行加密
  9100. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  9101. let lyricContent = ''
  9102. if (isJiaMi) {
  9103. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  9104. } else {
  9105. lyricContent = content
  9106. }
  9107. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  9108. // 清空文件内容
  9109. await fileIo.truncate(file.fd, 0);
  9110. await fileIo.write(file.fd, lyricContent);
  9111. await fileIo.close(file);
  9112. console.log('onecold lyric file Data saved successfully.');
  9113. } catch (error) {
  9114. console.error('onecold lyric file Failed to save data:', error);
  9115. }
  9116. }
  9117. // 定义开始旋转的方法
  9118. // 定时器用于一百毫秒执行一次旋转角度
  9119. @State timer: number = 0
  9120. @State rotateAngle: number = 0
  9121. //封面旋转动画
  9122. animationRoFun() {
  9123. if (this.isPlaying && !this.isCoverRectangle) {
  9124. this.timer = setInterval(() => {
  9125. this.rotateAngle += 1
  9126. }, 100)
  9127. this.startRotation()
  9128. } else {
  9129. clearInterval(this.timer)
  9130. this.stopRotation()
  9131. }
  9132. }
  9133. // 定义开始旋转的方法
  9134. startRotation() {
  9135. if (this.isPlaying) {
  9136. animateTo({
  9137. duration: 777,
  9138. iterations: 1,
  9139. curve: Curve.Linear
  9140. }, () => {
  9141. this.rotateAngle2 = -9
  9142. })
  9143. }
  9144. }
  9145. // 回调,暂停和播放按钮回调,下一首和上一首
  9146. playChange() {
  9147. // if(this.isCoverRectangle){
  9148. // return
  9149. // }
  9150. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  9151. this.setIsPlaying(true)
  9152. this.animationState = AnimationStatus.Running
  9153. } else {
  9154. this.setIsPlaying(false)
  9155. this.animationState = AnimationStatus.Paused
  9156. }
  9157. AppStorage.setOrCreate('animationState', this.animationState);
  9158. }
  9159. // 定义停止旋转的方法
  9160. stopRotation() {
  9161. if (this.isCoverRectangle) {
  9162. this.rotateAngle = 0
  9163. } else {
  9164. //唱针以左上角为点选择逆时针40度
  9165. animateTo({
  9166. duration: 1000,
  9167. curve: Curve.Linear,
  9168. iterations: 1,
  9169. }, () => {
  9170. this.rotateAngle2 = -45;
  9171. });
  9172. }
  9173. }
  9174. @Builder
  9175. private LyricsTopItem() {
  9176. Row() {
  9177. Stack() {
  9178. Image(this.cover)
  9179. .height(58)
  9180. .width(58)
  9181. .alt($r('app.media.alt'))
  9182. .borderRadius(8)
  9183. .clickEffect({ level: ClickEffectLevel.HEAVY })
  9184. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  9185. .shadow({
  9186. radius: 22,
  9187. type: ShadowType.BLUR,
  9188. color: 'on_primary'
  9189. })
  9190. }
  9191. .width('18%')
  9192. Column() {
  9193. Column() {
  9194. Text(this.name)
  9195. .fontSize(16)
  9196. .maxLines(1)
  9197. .fontWeight(FontWeight.Bolder)
  9198. .fontColor(this.currentLyricColor)
  9199. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  9200. Row() {
  9201. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  9202. .fontSize(13)
  9203. .fontWeight(FontWeight.Bold)
  9204. .padding({ top: 8 })
  9205. .fontColor(this.currentLyricColor)
  9206. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  9207. Blank()
  9208. }
  9209. }
  9210. .height('100%')
  9211. .width('100%')
  9212. .justifyContent(FlexAlign.Center)
  9213. .alignItems(HorizontalAlign.Start)
  9214. }
  9215. .height('100%')
  9216. .width('65%')
  9217. Column() {
  9218. Image($r('app.media.lyric'))
  9219. .width(28)
  9220. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9221. .margin({ right: 30 })
  9222. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9223. .onClick(() => {
  9224. this.isLyricSetting = !this.isLyricSetting;
  9225. })
  9226. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  9227. height: '95%',
  9228. dragBar: true,
  9229. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9230. showClose: true,
  9231. blurStyle: BlurStyle.Thin,
  9232. backgroundColor: Color.Transparent,
  9233. // title: { title: $r('app.string.lyric_setting') }
  9234. })
  9235. }
  9236. .width('18%')
  9237. }
  9238. .width('82%')
  9239. .height(58)
  9240. .justifyContent(FlexAlign.SpaceBetween)
  9241. }
  9242. //歌词显示
  9243. @Builder
  9244. PlayerLyrics() {
  9245. Column() {
  9246. Column() {
  9247. this.LyricsTopItem()
  9248. }
  9249. .height(this.isPuraWP() ? 15 : 58)
  9250. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  9251. Visibility.None : Visibility.Visible)
  9252. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  9253. .width("100%")
  9254. Column() {
  9255. LyricView2({
  9256. controller: this.lyricController,
  9257. enableSeek: true,
  9258. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  9259. seekLineColor: "#80ffffff", // 滑动定位线颜色
  9260. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  9261. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  9262. if (!this.isPlaying) {
  9263. console.info('onecold startPlayOrResumePlay 7527')
  9264. this.startPlayOrResumePlay()
  9265. }
  9266. else {
  9267. this.isSeekTo = true;
  9268. this.mDestroyPage = false;
  9269. this.showLoadIng();
  9270. this.seekTo(position + "");
  9271. this.isSeekTo = false;
  9272. }
  9273. return true
  9274. }
  9275. })
  9276. .width("100%")
  9277. .layoutWeight(1)
  9278. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  9279. if (this.isPhoneLan()) {
  9280. Column() {
  9281. this.playProgressView()
  9282. // this.playCenterView()
  9283. }
  9284. .margin({ bottom: 30, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  9285. }
  9286. }
  9287. .position({
  9288. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  9289. (this.isPuraWP() ? 58 : 99)
  9290. })
  9291. .justifyContent(FlexAlign.Center)
  9292. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  9293. }
  9294. }
  9295. @Builder
  9296. SingleLyricView() {
  9297. Column() {
  9298. Column() {
  9299. LyricView2({
  9300. controller: this.lyricControllerSingle,
  9301. enableSeek: false,
  9302. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  9303. seekLineColor: "#80ffffff", // 滑动定位线颜色
  9304. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  9305. })
  9306. }
  9307. .height(66)
  9308. .margin({ bottom: 20 })
  9309. }
  9310. }
  9311. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  9312. @Builder
  9313. BottomControl() {
  9314. Column() {
  9315. this.TopPlayProgressView()
  9316. //播放 暂停,下一首,上一首
  9317. this.playCenterView()
  9318. //播放进度条
  9319. this.BottomView()
  9320. }
  9321. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  9322. }
  9323. //播放控制上一首 下一首 暂停和播放
  9324. @Builder
  9325. playCenterView(){
  9326. Row() {
  9327. Button({type:ButtonType.Circle,stateEffect:true}){
  9328. //更多功能
  9329. Image($r('app.media.menu'))
  9330. .width(24)
  9331. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9332. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  9333. height: '99%',
  9334. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  9335. dragBar: true,
  9336. showClose: true,
  9337. blurStyle: BlurStyle.Thin,
  9338. backgroundColor: Color.Transparent,
  9339. })
  9340. }
  9341. .height(45)
  9342. .width(45)
  9343. .margin({ left: 5 })
  9344. .backgroundColor(Color.Transparent)
  9345. .onClick(() => {
  9346. this.isShowMoreView = !this.isShowMoreView;
  9347. })
  9348. Button({type:ButtonType.Circle,stateEffect:true}){
  9349. Image($r('app.media.ic_previous'))
  9350. .width(33)
  9351. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9352. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9353. }
  9354. .height(45)
  9355. .width(45)
  9356. .onClick(async () => {
  9357. await this.playPrevious()
  9358. })
  9359. .backgroundColor(Color.Transparent)
  9360. Button({type:ButtonType.Circle,stateEffect:true}){
  9361. Column() {
  9362. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  9363. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  9364. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  9365. .width(this.isPhoneLan()?45:55)
  9366. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9367. .fillColor(Color.White)
  9368. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9369. }
  9370. }
  9371. .onClick(async () => {
  9372. this.playOrPause()
  9373. })
  9374. .backgroundColor(Color.Transparent)
  9375. .layoutWeight(1)
  9376. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9377. Image($r('app.media.ic_next'))
  9378. .width(33)
  9379. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9380. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9381. }
  9382. .height(45)
  9383. .width(45)
  9384. .backgroundColor(Color.Transparent)
  9385. .onClick(async () => {
  9386. await this.playNext();
  9387. })
  9388. this.fullButton()
  9389. }
  9390. .width('95%')
  9391. .margin({ bottom:this.isCoverOpacity()?0:15 })
  9392. .justifyContent(FlexAlign.SpaceEvenly)
  9393. }
  9394. @Builder
  9395. TopPlayProgressView(){
  9396. Row() {
  9397. Column(){
  9398. Row(){
  9399. Stack(){
  9400. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  9401. .fontColor([Color.White])
  9402. .fontSize(21)
  9403. .effectStrategy(1)
  9404. Text(this.fastForwardSeconds)
  9405. .fontColor(Color.White)
  9406. .fontSize(10)
  9407. .fontWeight(FontWeight.Bold)
  9408. }
  9409. .margin({left:12,bottom:6})
  9410. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  9411. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9412. .onClick(()=>{
  9413. this.backForward()
  9414. })
  9415. Slider({
  9416. value: this.progressValue,
  9417. min: 0,
  9418. max: this.PROGRESS_MAX_VALUE,
  9419. step: 1,
  9420. style: SliderStyle.InSet
  9421. })
  9422. .height(20)
  9423. .blockColor('rgba(255,255,255,1)')
  9424. .trackColor('rgba(255,255,255,0.3)')
  9425. .selectedColor(Color.White)
  9426. .trackThickness(4)
  9427. .layoutWeight(1)
  9428. .showSteps(false)
  9429. .showTips(true)
  9430. .alignSelf(ItemAlign.Center)
  9431. .enabled(this.slideEnable)
  9432. .onChange((value: number, mode: SliderChangeMode) => {
  9433. // if (mode == 2) {
  9434. this.isSeekTo = true;
  9435. this.mDestroyPage = false;
  9436. this.showLoadIng();
  9437. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  9438. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  9439. this.seekTo(seekValue + "");
  9440. // this.setProgress()
  9441. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  9442. this.isSeekTo = false;
  9443. // }
  9444. })
  9445. Stack(){
  9446. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  9447. .fontColor([Color.White])
  9448. .fontSize(21)
  9449. .effectStrategy(1)
  9450. Text(this.fastForwardSeconds)
  9451. .fontColor(Color.White)
  9452. .fontSize(10)
  9453. .fontWeight(FontWeight.Bold)
  9454. }
  9455. .margin({right:10,bottom:6})
  9456. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  9457. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9458. .onClick(()=>{
  9459. this.fastForward()
  9460. })
  9461. }
  9462. .padding({ right: 7,left:22 })
  9463. Row(){
  9464. Text(this.currentTime)
  9465. .fontSize(10)
  9466. .fontColor(Color.White)
  9467. Blank()
  9468. .layoutWeight(1)
  9469. Text(this.totalTime)
  9470. .fontSize(10)
  9471. .fontColor(Color.White)
  9472. }
  9473. .justifyContent(FlexAlign.Start)
  9474. .padding({ right: 18,left:36 })
  9475. }
  9476. }
  9477. //x5的竖屏模式需要99%
  9478. .width(this.isLandscape?'80%':'93%')
  9479. .justifyContent(FlexAlign.Center)
  9480. .margin({bottom:3})
  9481. .animation({
  9482. duration: 666,
  9483. curve: 'ease-in-out' // 可选动画曲线
  9484. })
  9485. }
  9486. //播放进度条
  9487. @Builder
  9488. BottomView(){
  9489. Row() {
  9490. Button({type:ButtonType.Circle,stateEffect:true}){
  9491. Column() {
  9492. if (this.playType === 0) {
  9493. Image($r('app.media.loop'))
  9494. .width(27)
  9495. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9496. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9497. } else if (this.playType === 1) {
  9498. Image($r('app.media.single'))
  9499. .width(27)
  9500. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9501. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9502. } else if (this.playType === 2) {
  9503. Image($r('app.media.normal_play'))
  9504. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9505. .width(27)
  9506. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9507. } else if (this.playType === 3) {
  9508. Image($r('app.media.random'))
  9509. .width(27)
  9510. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9511. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9512. }
  9513. }
  9514. }
  9515. .layoutWeight(1)
  9516. .margin({ left: 5 })
  9517. .height(45)
  9518. .width(45)
  9519. .backgroundColor(Color.Transparent)
  9520. .onClick(async () => {
  9521. this.setLoopMode()
  9522. })
  9523. if(this.currentSong){
  9524. Button({type:ButtonType.Circle,stateEffect:true}){
  9525. Column() {
  9526. Image($r('app.media.rename2'))
  9527. .width(21)
  9528. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9529. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9530. }
  9531. }
  9532. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  9533. height: '99%',
  9534. dragBar: true,
  9535. showClose: true,
  9536. preferType: SheetType.BOTTOM,
  9537. title: { title: '编辑标签' }
  9538. })
  9539. .height(45)
  9540. .width(45)
  9541. .layoutWeight(1)
  9542. .backgroundColor(Color.Transparent)
  9543. .onClick(async () => {
  9544. this.initEditFields(this.currentSong)
  9545. this.tempLyricContent = this.lyricContent
  9546. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  9547. this.lyricConStr = this.tempLyricContent
  9548. }
  9549. this.isShowEdit = !this.isShowEdit;
  9550. })
  9551. }
  9552. Button({type:ButtonType.Circle,stateEffect:true}){
  9553. Column() {
  9554. Image($r('app.media.lyric'))
  9555. .width(26)
  9556. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9557. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9558. }
  9559. }
  9560. .height(45)
  9561. .width(45)
  9562. .layoutWeight(1)
  9563. .backgroundColor(Color.Transparent)
  9564. .onClick(async () => {
  9565. this.isLyricSetting = !this.isLyricSetting;
  9566. })
  9567. //播放列表
  9568. Button({type:ButtonType.Circle,stateEffect:true}){
  9569. Image($r('app.media.hm_playlist'))
  9570. .width(24)
  9571. .fillColor(Color.White)
  9572. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9573. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9574. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  9575. height: '95%',
  9576. dragBar: true,
  9577. showClose: true,
  9578. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9579. blurStyle: BlurStyle.Thin,
  9580. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  9581. title: {
  9582. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  9583. + `(${this.songList.length}首)`
  9584. }
  9585. })
  9586. }
  9587. .layoutWeight(1)
  9588. .height(45)
  9589. .width(45)
  9590. .backgroundColor(Color.Transparent)
  9591. .onClick(() => {
  9592. this.isShowSheetView = !this.isShowSheetView;
  9593. if(this.isPlayListBgGrass){
  9594. this.isFrontWhite = true
  9595. }else{
  9596. this.isFrontWhite = false
  9597. }
  9598. this.scrollIndex()
  9599. })
  9600. }
  9601. .width(this.isLandscape?'88%':'95%')
  9602. .justifyContent(FlexAlign.SpaceAround)
  9603. .height(30)
  9604. .animation({
  9605. duration: 666,
  9606. curve: 'ease-in-out' // 可选动画曲线
  9607. })
  9608. }
  9609. @Builder
  9610. fullButton(){
  9611. Button({type:ButtonType.Circle,stateEffect:true}){
  9612. Column() {
  9613. Image($r('app.media.full_4'))
  9614. .width(25)
  9615. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9616. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9617. }
  9618. }
  9619. .layoutWeight(1)
  9620. .backgroundColor(Color.Transparent)
  9621. .height(45)
  9622. .width(45)
  9623. .onClick(async () => {
  9624. if (this.isLandscape) {
  9625. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  9626. } else {
  9627. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  9628. }
  9629. })
  9630. }
  9631. //旧版本播放进度条
  9632. @Builder
  9633. playProgressView() {
  9634. Row() {
  9635. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9636. Column() {
  9637. if (this.playType === 0) {
  9638. Image($r('app.media.loop'))
  9639. .width($r('app.float.control_image_width'))
  9640. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9641. } else if (this.playType === 1) {
  9642. Image($r('app.media.single'))
  9643. .width($r('app.float.control_image_width'))
  9644. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9645. } else if (this.playType === 2) {
  9646. Image($r('app.media.normal_play'))
  9647. .width($r('app.float.control_image_width'))
  9648. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9649. } else if (this.playType === 3) {
  9650. Image($r('app.media.random'))
  9651. .width($r('app.float.control_image_width'))
  9652. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9653. }
  9654. }
  9655. }
  9656. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  9657. .animation({
  9658. duration: 666,
  9659. curve: 'ease-in-out' // 可选动画曲线
  9660. })
  9661. .backgroundColor(Color.Transparent)
  9662. .margin({ right: 10 })
  9663. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9664. .onClick(async () => {
  9665. this.setLoopMode()
  9666. })
  9667. Text(this.currentTime)
  9668. .fontSize($r('app.float.slider_font_size'))
  9669. .fontColor(Color.White)
  9670. .margin(3)
  9671. Slider({
  9672. value: this.progressValue,
  9673. min: 0,
  9674. max: this.PROGRESS_MAX_VALUE,
  9675. step: 1,
  9676. style: SliderStyle.OutSet
  9677. })
  9678. .width('600px')
  9679. .blockColor('rgba(255,255,255,1)')
  9680. .trackColor('rgba(255,255,255,0.3)')
  9681. .selectedColor(Color.White)
  9682. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  9683. .layoutWeight(1)
  9684. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  9685. .showSteps(false)
  9686. .showTips(true)
  9687. .enabled(this.slideEnable)
  9688. .onChange((value: number, mode: SliderChangeMode) => {
  9689. // if (mode == 2) {
  9690. this.isSeekTo = true;
  9691. this.mDestroyPage = false;
  9692. this.showLoadIng();
  9693. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  9694. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  9695. this.seekTo(seekValue + "");
  9696. // this.setProgress()
  9697. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  9698. this.isSeekTo = false;
  9699. // }
  9700. })
  9701. Text(this.totalTime)
  9702. .fontSize($r('app.float.slider_font_size'))
  9703. .fontColor(Color.White)
  9704. .margin(3)
  9705. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  9706. //播放列表
  9707. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9708. Image($r('app.media.hm_playlist'))
  9709. .width($r('app.float.control_image_width'))
  9710. .fillColor(Color.White)
  9711. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9712. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  9713. height: '95%',
  9714. dragBar: true,
  9715. showClose: true,
  9716. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9717. blurStyle: BlurStyle.Thin,
  9718. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  9719. title: {
  9720. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  9721. + `(${this.songList.length}首)`
  9722. }
  9723. })
  9724. }
  9725. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  9726. .animation({
  9727. duration: 666,
  9728. curve: 'ease-in-out' // 可选动画曲线
  9729. })
  9730. .backgroundColor(Color.Transparent)
  9731. .margin({ right: 20, left: 10 })
  9732. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9733. .onClick(() => {
  9734. this.isShowSheetView = !this.isShowSheetView;
  9735. if (this.isPlayListBgGrass) {
  9736. this.isFrontWhite = true
  9737. } else {
  9738. this.isFrontWhite = false
  9739. }
  9740. this.scrollIndex()
  9741. })
  9742. }
  9743. //x5的竖屏模式需要99%
  9744. .width(this.isPhonePortrait() ? '93.4%'
  9745. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  9746. .height(this.isPhoneLan() ? 25 : 33)
  9747. .animation({
  9748. duration: 666,
  9749. curve: 'ease-in-out' // 可选动画曲线
  9750. })
  9751. }
  9752. isBigScreen() {
  9753. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  9754. return true
  9755. }
  9756. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  9757. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  9758. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  9759. return false
  9760. } else {
  9761. return true
  9762. }
  9763. return false
  9764. }
  9765. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  9766. @State isCoverRectangle: boolean = false
  9767. @State isCoverTop: boolean = true
  9768. // 添加控制缩放的状态变量
  9769. @State scaleValueImage: number = 1
  9770. @State scaleValueText: number = 1
  9771. @Builder
  9772. CoverInfo() {
  9773. Column() {
  9774. //如果是方形,判断是不是封面在顶部,如果不是顶部,显示musicNameInfo, 如果是圆形显示musicNameInfo
  9775. if (this.isCoverRectangle) {
  9776. if (!this.isCoverTop) {
  9777. this.musicNameInfo(false)
  9778. }
  9779. } else {
  9780. this.musicNameInfo(false)
  9781. }
  9782. Stack() {
  9783. // 唱片旋转效果
  9784. Image($r('app.media.ic_music_disc'))
  9785. .width(245)
  9786. .height(245)
  9787. .margin({ right: 20, left: 20 ,top:this.isCoverRectangle||this.isLandscape?0:43})
  9788. .aspectRatio(1)
  9789. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  9790. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  9791. .borderRadius('100%')
  9792. .align(Alignment.Center)
  9793. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  9794. .rotate({
  9795. angle: this.rotateAngle,
  9796. centerX: "50%",
  9797. centerY: "50%",
  9798. })
  9799. .animation({
  9800. duration: 100,
  9801. curve: Curve.Linear
  9802. })
  9803. .shadow({
  9804. radius: 22,
  9805. type: ShadowType.BLUR,
  9806. color: 'on_primary'
  9807. })
  9808. Column() {
  9809. if (this.isCoverTop && this.isCoverRectangle) {
  9810. Image(this.cover)
  9811. .height(this.isHiCar()?(px2vp(this.windowHeight)*0.46):
  9812. this.isCoverOpacity()?(px2vp(this.windowHeight)*0.6):'auto')
  9813. .width(this.isHiCar()||this.isCoverOpacity()?'auto':this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '88%')
  9814. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  9815. .alt($r('app.media.alt'))
  9816. .margin({ right: 8, left: 8, top: 8 })
  9817. .aspectRatio(1)
  9818. .geometryTransition('cover') // 绑定标识符
  9819. .opacity(this.opacityValueImage)
  9820. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  9821. // 设置左下角为缩放中心点
  9822. centerX: '0%',
  9823. centerY: '100%' })
  9824. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  9825. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  9826. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  9827. .clip(true)
  9828. .rotate({
  9829. x: 0,
  9830. y: 0,
  9831. z: 1,
  9832. angle: this.rotateAngle
  9833. })
  9834. .shadow({
  9835. radius: 22,
  9836. type: ShadowType.BLUR,
  9837. color: 'on_primary'
  9838. })
  9839. .onClick(() => {
  9840. })
  9841. // .visualEffect(new hdsEffect.HdsEffectBuilder()
  9842. // .shaderEffect({
  9843. // effectType: hdsEffect.EffectType.DUAL_EDGE_FLOW_LIGHT,
  9844. // animation: {
  9845. // duration: 4000,
  9846. // iterations: -1,
  9847. // autoPlay: true,
  9848. // onFinish: () => {
  9849. // console.info('Succeeded in finishing');
  9850. // }
  9851. // },
  9852. // controller: this.controller,
  9853. // params: {
  9854. // firstEdgeFlowLight: {
  9855. // startPos: 0,
  9856. // endPos: 1.0,
  9857. // color: '#1AD0F1',
  9858. // },
  9859. // secondEdgeFlowLight: {
  9860. // startPos: 0.5,
  9861. // endPos: 1.5,
  9862. // color: '#FFA4E5',
  9863. // }
  9864. // }
  9865. // })
  9866. // .buildEffect())
  9867. this.musicNameInfo(false)
  9868. } else {
  9869. Image(this.cover)
  9870. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  9871. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 162))
  9872. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  9873. .alt($r('app.media.alt'))
  9874. .geometryTransition('cover') // 绑定标识符
  9875. .margin({ right: 20, left: 20,top:this.isCoverRectangle||this.isLandscape?0:43 })
  9876. .aspectRatio(1)
  9877. .opacity(this.opacityValueImage)
  9878. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  9879. // 设置左下角为缩放中心点
  9880. centerX: '0%',
  9881. centerY: '100%' })
  9882. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  9883. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  9884. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  9885. .align(Alignment.Center)//
  9886. .clip(true)
  9887. .shadow({
  9888. radius: 22,
  9889. type: ShadowType.BLUR,
  9890. color: 'on_primary'
  9891. })
  9892. .rotate({
  9893. x: 0,
  9894. y: 0,
  9895. z: 1,
  9896. angle: this.rotateAngle
  9897. })
  9898. .onClick(() => {
  9899. })
  9900. }
  9901. if (this.isPhoneLan()) {
  9902. Text(this.name)
  9903. .fontSize(18)
  9904. .fontWeight(FontWeight.Bold)
  9905. .margin({ top: 13 })
  9906. .textOverflow({ overflow: TextOverflow.Ellipsis })
  9907. .maxLines(1)
  9908. .width('99%')
  9909. .textAlign(TextAlign.Center)
  9910. .fontColor(Color.White)
  9911. }
  9912. }
  9913. // 唱针以左上角为点选择逆时针40度
  9914. Image($r('app.media.ic_music_cover_hand'))
  9915. .height(130)
  9916. .margin({ bottom: 220, top: 0 })
  9917. .align(Alignment.Top)
  9918. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  9919. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  9920. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  9921. Column({ space: 8 }) {
  9922. Text(this.name)
  9923. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  9924. .fontWeight(FontWeight.Bold)
  9925. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9926. .maxLines(1)
  9927. .width('48%')
  9928. .textAlign(TextAlign.Center)
  9929. .fontColor(Color.White)
  9930. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  9931. Text(this.artist)
  9932. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  9933. .fontColor(Color.White)
  9934. .fontWeight(FontWeight.Bold)
  9935. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  9936. }
  9937. .justifyContent(FlexAlign.Start)
  9938. .zIndex(1)
  9939. .geometryTransition('name')
  9940. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  9941. }
  9942. .margin({
  9943. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  9944. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  9945. top: this.isCoverOpacity() ? 0 : 20
  9946. })
  9947. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  9948. this.SingleLyricView()
  9949. }
  9950. if (this.isPhoneLan()) {
  9951. Column() {
  9952. this.playCenterView()
  9953. // this.playProgressView()
  9954. }
  9955. .position({ left: 28, bottom: 38 })
  9956. } else {
  9957. this.BottomControl()
  9958. }
  9959. }
  9960. .width(CommonConstants.FULL_PERCENT)
  9961. .clip(true)
  9962. }
  9963. @Builder
  9964. private musicNameInfo(isHidden: boolean) {
  9965. Row(){
  9966. Column({ space: 8 }) {
  9967. Text(this.name)
  9968. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 20)
  9969. .fontWeight(FontWeight.Bold)
  9970. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9971. .maxLines(1)
  9972. .width('99%')
  9973. .textAlign(TextAlign.Start)
  9974. .fontColor(Color.White)
  9975. Text(this.artist + ' ' + this.currentSong?.album)
  9976. .fontSize(this.isCoverOpacity() ? 12 : 15)
  9977. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9978. .fontColor(Color.White)
  9979. .textAlign(TextAlign.Start)
  9980. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  9981. .width('99%')
  9982. .maxLines(1)
  9983. }
  9984. .zIndex(1)
  9985. .geometryTransition('name') // 绑定标识符
  9986. .layoutWeight(1)
  9987. .margin({ left: 15 })
  9988. Blank()
  9989. Row(){
  9990. Button({type:ButtonType.Circle,stateEffect:true}){
  9991. //添加或取消收藏
  9992. SymbolGlyph(Utility.getIsFav(this.favList,this.currentSong)?
  9993. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'))
  9994. .fontSize(22)
  9995. .fontColor([Color.White])
  9996. .alignSelf(ItemAlign.Center)
  9997. // .width(24)
  9998. .clickEffect({level:ClickEffectLevel.MIDDLE})
  9999. .aspectRatio(CommonConstants.ASPECT_RATIO)
  10000. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  10001. .onClick(async () => {
  10002. if(this.currentSong){
  10003. this.doFav(this.currentSong)
  10004. }
  10005. })
  10006. }
  10007. .margin({ left: 15,right:3 })
  10008. .backgroundColor(Color.Transparent)
  10009. .width(45)
  10010. .height(45)
  10011. }
  10012. }
  10013. .width('90%')
  10014. .scale({ x: this.scaleValueText, y: this.scaleValueText }) // 添加缩放效果
  10015. .margin({ top: this.isCoverOpacity() ? 10 : isHidden ? 20 : 10 })
  10016. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  10017. }
  10018. @Builder
  10019. private PlayTitle() {
  10020. Row() {
  10021. Row() {
  10022. Image($r('app.media.ic_back_down'))
  10023. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  10024. .hitTestBehavior(HitTestMode.Transparent)
  10025. Text(this.name + ' ' + this.artist)
  10026. .fontColor(Color.White)
  10027. .fontSize($r('app.float.title_font_size'))
  10028. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  10029. .maxLines(1)
  10030. .visibility(Visibility.None)
  10031. .margin({ left: 2, right: 30 })
  10032. }
  10033. .layoutWeight(1)
  10034. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10035. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  10036. .onClick(() => {
  10037. this.setShowPlayFalse()
  10038. })
  10039. Column() {
  10040. AVCastPicker({
  10041. normalColor: Color.White,
  10042. onStateChange: this.onStateVastChange
  10043. })
  10044. .width(24)
  10045. .height(24)
  10046. }
  10047. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  10048. }
  10049. .width(PlayConstants.ROW_WIDTH)
  10050. }
  10051. @Builder
  10052. lyricSettingSheet(isPip: boolean) {
  10053. Scroll() {
  10054. this.lyricSetting(isPip)
  10055. }
  10056. .width('100%')
  10057. .height('100%')
  10058. }
  10059. @Builder
  10060. lyricSetting(isPip: boolean) {
  10061. Column() {
  10062. // 时间调节模块
  10063. if (!isPip) {
  10064. this.BuildTimeControls()
  10065. }
  10066. // 字号控制模块
  10067. this.BuildFontControls(isPip)
  10068. }
  10069. }
  10070. // 歌词时间偏移状态
  10071. @State timeOffset: number = 0.0
  10072. @State currentLyricColor: string = '#FFFFFF'
  10073. @State currentLyricColorPip: string = '#FFFFFF'
  10074. @State currentHighLightLyricColor: string = '#FF4081'
  10075. @State currentHighLightLyricColorPip: string = '#FF4081'
  10076. // 歌词字号状态
  10077. @State currentLyricSize: number = 20
  10078. @State currentLyricSizePip: number = 20
  10079. // 高亮歌词放大倍数
  10080. @State currentHightLyricSize: number = 1.2
  10081. @State currentHightLyricSizePip: number = 1.2
  10082. @State currentLyricLineSpace: number = 10
  10083. @State currentLyricLineSpacePip: number = 10
  10084. @State currentLyricAlignMode: number = 1
  10085. @State currentLyricAlignModePip: number = 1
  10086. @State blurDegree: number = 2
  10087. @State blurDegreePip: number = 2
  10088. @State isShowSelectColor: boolean = false
  10089. @State isShowHLSelectColor: boolean = false
  10090. @State isShowPipBgSelectColor: boolean = false
  10091. @State pipLyWidth: number = 330
  10092. @State pipLyHeight: number = 120
  10093. // 构建颜色选择器
  10094. @Builder
  10095. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  10096. Row({ space: 10 }) {
  10097. HSBColorPicker({
  10098. color: '#FFFFFF',
  10099. radius: 8,
  10100. layout: HSBColorPickerLayout.COLUMN,
  10101. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  10102. '#fa7105'],
  10103. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  10104. this.changeLyricColor(value, isPip, isBGPip)
  10105. })
  10106. .height(250)
  10107. .layoutWeight(1)
  10108. .padding(25)
  10109. }
  10110. .width('66%')
  10111. }
  10112. @State isOpenPip: boolean = false
  10113. @State pipBgIndex: number = 0
  10114. // 构建字号控制器
  10115. @Builder
  10116. BuildFontControls(isPip: boolean) {
  10117. Column() {
  10118. if (isPip) {
  10119. Column() {
  10120. Row() {
  10121. Text('悬浮歌词')
  10122. .margin({ left: 18 })
  10123. .fontSize(15)
  10124. .fontColor(Color.White)
  10125. .fontWeight(480)
  10126. .layoutWeight(1)
  10127. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  10128. .selectedColor(this.themeColor)
  10129. .switchPointColor(Color.White)
  10130. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10131. .margin({ right: 18 })
  10132. .onChange((checked: boolean) => {
  10133. this.isOpenPip = checked;
  10134. if (this.isOpenPip) {
  10135. this.startPip()
  10136. } else {
  10137. this.stopPip()
  10138. }
  10139. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  10140. })
  10141. .width(50)
  10142. .height(30);
  10143. }
  10144. .height(55)
  10145. }
  10146. .backgroundColor(Color.Transparent)
  10147. .borderRadius(15)
  10148. .margin({
  10149. left: 30,
  10150. right: 30,
  10151. top: 0,
  10152. bottom: 20
  10153. })
  10154. .padding(0)
  10155. .border({
  10156. color: Color.White,
  10157. width: 1.8
  10158. })
  10159. }else{
  10160. Column() {
  10161. Row() {
  10162. Text('单行歌词')
  10163. .margin({ left: 18 })
  10164. .fontSize(15)
  10165. .fontColor(Color.White)
  10166. .fontWeight(480)
  10167. .layoutWeight(1)
  10168. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  10169. .selectedColor(this.themeColor)
  10170. .switchPointColor(Color.White)
  10171. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10172. .margin({ right: 18 })
  10173. .onChange((checked: boolean) => {
  10174. this.isShowSingleLineLyric = checked;
  10175. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  10176. })
  10177. .width(50)
  10178. .height(30);
  10179. }
  10180. .height(55)
  10181. }
  10182. .backgroundColor(Color.Transparent)
  10183. .borderRadius(15)
  10184. .margin({
  10185. left: 30,
  10186. right: 30,
  10187. top: 10,
  10188. bottom: 10
  10189. })
  10190. .padding(0)
  10191. .border({
  10192. color: Color.White,
  10193. width: 1.8
  10194. })
  10195. }
  10196. Row() {
  10197. Text(`歌词居中:`)
  10198. .fontSize(14)
  10199. .fontColor(Color.White)
  10200. .margin({ left: 2 })
  10201. Row() {
  10202. ForEach(['居中', '居左'], (size: string, index: number) => {
  10203. Button(size)
  10204. .width(60)
  10205. .height(28)
  10206. .fontSize(12)
  10207. .fontColor('#FFFFFF')
  10208. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  10209. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  10210. .border({
  10211. color: (!isPip && this.currentLyricAlignMode === index) ||
  10212. (isPip && this.currentLyricAlignModePip === index) ?
  10213. '#007DFF' : '#DDDDDD',
  10214. width: 1.8
  10215. })
  10216. .onClick(() => {
  10217. this.setLyricAlignMode(index, isPip)
  10218. })
  10219. .margin({ left: 10, right: 8 })
  10220. })
  10221. }
  10222. .width('76%')
  10223. Blank()
  10224. }
  10225. .margin({
  10226. top: 10,
  10227. bottom: 10,
  10228. right: 20,
  10229. left: 20
  10230. })
  10231. if (isPip) {
  10232. Row() {
  10233. Text(`悬浮背景:`)
  10234. .fontSize(14)
  10235. .fontColor(Color.White)
  10236. Select([
  10237. { value: CommonConstants.PIP_LYRIC_BG[0] },
  10238. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  10239. .font({ size: 13, weight: FontWeight.Medium })
  10240. .fontColor(Color.White)
  10241. .margin({ left: 10 })
  10242. .selected(this.pipBgIndex)
  10243. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  10244. .onSelect(async (_index: number, text?: string | undefined) => {
  10245. this.pipBgIndex = _index
  10246. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  10247. if (this.pipBgIndex === 0) {
  10248. if (this.cover) {
  10249. this.pipBg = this.cover
  10250. } else {
  10251. this.pipBg = this.imageColor
  10252. }
  10253. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  10254. } else {
  10255. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  10256. }
  10257. })
  10258. Column() {
  10259. }
  10260. .backgroundColor(this.pipBg)
  10261. .margin({ left: 10, right: 10 })
  10262. .borderRadius(20)
  10263. .height(28)
  10264. .width(28)
  10265. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10266. Row() {
  10267. SymbolGlyph($r('sys.symbol.paintbrush'))
  10268. .fontColor([Color.White])
  10269. .effectStrategy(1)
  10270. Text(`选择颜色`)
  10271. .fontSize(13)
  10272. .margin({ left: 10 })
  10273. .fontColor(Color.White)
  10274. }
  10275. }
  10276. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  10277. .backgroundColor(Color.Transparent)
  10278. .border({
  10279. color: '#FFFFFF',
  10280. radius: 20,
  10281. width: 1.8
  10282. })
  10283. .height(36)
  10284. .width(110)
  10285. .onClick(() => {
  10286. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  10287. })
  10288. .bindPopup(this.isShowPipBgSelectColor, {
  10289. builder: this.SelectColor(false, isPip, true),
  10290. placement: Placement.Top,
  10291. mask: { color: '#33000000' },
  10292. enableArrow: false, //是否显示箭头
  10293. showInSubWindow: false,
  10294. onStateChange: (e) => {
  10295. if (!e.isVisible) {
  10296. this.isShowPipBgSelectColor = false
  10297. }
  10298. }
  10299. })
  10300. }
  10301. .width('76%')
  10302. .margin({ bottom: 5, right: 45, left: 20 })
  10303. }
  10304. if (!isPip) {
  10305. Row() {
  10306. Text(`高亮居中:`)
  10307. .fontSize(14)
  10308. .fontColor(Color.White)
  10309. Column() {
  10310. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  10311. .selectedColor(this.themeColor)
  10312. .switchPointColor(Color.White)
  10313. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10314. .onChange((checked: boolean) => {
  10315. this.isHightLightCenter = checked;
  10316. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  10317. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  10318. })
  10319. .width(50)
  10320. .height(30)
  10321. .alignSelf(ItemAlign.Start)
  10322. .margin({ left: 12 })
  10323. Blank()
  10324. }
  10325. .width('76%')
  10326. }
  10327. .margin({
  10328. left: 20,
  10329. right: 15,
  10330. top: 10,
  10331. bottom: 10
  10332. })
  10333. }
  10334. Row() {
  10335. Text(`歌词颜色:`)
  10336. .fontSize(14)
  10337. .fontColor(Color.White)
  10338. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  10339. .fontSize(15)
  10340. .fontColor(Color.White)
  10341. .margin({ left: 12, right: 12 })
  10342. Column() {
  10343. }
  10344. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  10345. .margin({ right: 12 })
  10346. .borderRadius(20)
  10347. .height(28)
  10348. .width(28)
  10349. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10350. Row() {
  10351. SymbolGlyph($r('sys.symbol.paintbrush'))
  10352. .fontColor([Color.White])
  10353. .effectStrategy(1)
  10354. Text(`选择颜色`)
  10355. .fontSize(13)
  10356. .margin({ left: 10 })
  10357. .fontColor(Color.White)
  10358. }
  10359. }
  10360. .backgroundColor(Color.Transparent)
  10361. .border({
  10362. color: '#FFFFFF',
  10363. radius: 20,
  10364. width: 1.8
  10365. })
  10366. .height(36)
  10367. .width(110)
  10368. .onClick(() => {
  10369. this.isShowSelectColor = !this.isShowSelectColor
  10370. })
  10371. .bindPopup(this.isShowSelectColor, {
  10372. builder: this.SelectColor(false, isPip),
  10373. placement: Placement.Top,
  10374. mask: { color: '#33000000' },
  10375. enableArrow: false, //是否显示箭头
  10376. showInSubWindow: false,
  10377. onStateChange: (e) => {
  10378. if (!e.isVisible) {
  10379. this.isShowSelectColor = false
  10380. }
  10381. }
  10382. })
  10383. }
  10384. .width('76%')
  10385. .margin({
  10386. top: 10,
  10387. bottom: 10,
  10388. right: 45,
  10389. left: 20
  10390. })
  10391. Row() {
  10392. Text(`高亮颜色:`)
  10393. .fontSize(14)
  10394. .fontColor(Color.White)
  10395. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  10396. .fontSize(15)
  10397. .fontColor(Color.White)
  10398. .margin({ left: 12, right: 12 })
  10399. Column() {
  10400. }
  10401. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  10402. .margin({ right: 12 })
  10403. .borderRadius(20)
  10404. .height(28)
  10405. .width(28)
  10406. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10407. Row() {
  10408. SymbolGlyph($r('sys.symbol.paintbrush'))
  10409. .fontColor([Color.White])
  10410. .effectStrategy(1)
  10411. Text(`选择颜色`)
  10412. .fontSize(13)
  10413. .margin({ left: 10 })
  10414. .fontColor(Color.White)
  10415. }
  10416. }
  10417. .backgroundColor(Color.Transparent)
  10418. .border({
  10419. color: '#FFFFFF',
  10420. radius: 20,
  10421. width: 1.8
  10422. })
  10423. .height(36)
  10424. .width(110)
  10425. .onClick(() => {
  10426. this.isShowHLSelectColor = !this.isShowHLSelectColor
  10427. })
  10428. .bindPopup(this.isShowHLSelectColor, {
  10429. builder: this.SelectColor(true, isPip),
  10430. placement: Placement.Top,
  10431. mask: { color: '#33000000' },
  10432. enableArrow: false, //是否显示箭头
  10433. showInSubWindow: false,
  10434. onStateChange: (e) => {
  10435. if (!e.isVisible) {
  10436. this.isShowHLSelectColor = false
  10437. }
  10438. }
  10439. })
  10440. }
  10441. .width('76%')
  10442. .margin({
  10443. top: 10,
  10444. bottom: 10,
  10445. right: 45,
  10446. left: 20
  10447. })
  10448. if (isPip) {
  10449. Row() {
  10450. Text(`显示宽度:`)
  10451. .fontSize(14)
  10452. .fontColor(Color.White)
  10453. Slider({
  10454. value: this.pipLyWidth,
  10455. min: 10,
  10456. max: 800,
  10457. step: 1,
  10458. style: SliderStyle.OutSet
  10459. })
  10460. .blockColor(this.themeColor)
  10461. .trackColor($r('app.color.speed_text_color'))
  10462. .selectedColor(Color.White)
  10463. .trackThickness(6)
  10464. .onChange((value: number) => {
  10465. this.pipLyWidth = value
  10466. if (this.pipController) {
  10467. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10468. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  10469. }
  10470. })
  10471. .width('76%')
  10472. }
  10473. .margin({
  10474. left: 20,
  10475. right: 15,
  10476. top: 5,
  10477. bottom: 5
  10478. })
  10479. Row() {
  10480. Text(`显示高度:`)
  10481. .fontSize(14)
  10482. .fontColor(Color.White)
  10483. Slider({
  10484. value: this.pipLyHeight,
  10485. min: 10,
  10486. max: 1000,
  10487. step: 1,
  10488. style: SliderStyle.OutSet
  10489. })
  10490. .blockColor(this.themeColor)
  10491. .trackColor($r('app.color.speed_text_color'))
  10492. .selectedColor(Color.White)
  10493. .trackThickness(6)
  10494. .onChange((value: number) => {
  10495. this.pipLyHeight = value
  10496. if (this.pipController) {
  10497. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10498. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  10499. }
  10500. })
  10501. .width('76%')
  10502. }
  10503. .margin({
  10504. left: 20,
  10505. right: 15,
  10506. top: 5,
  10507. bottom: 5
  10508. })
  10509. }
  10510. Row() {
  10511. Text(`歌词字号:`)
  10512. .fontSize(14)
  10513. .fontColor(Color.White)
  10514. Slider({
  10515. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  10516. min: 12,
  10517. max: 30,
  10518. step: 0.1,
  10519. style: SliderStyle.OutSet
  10520. })
  10521. .blockColor(this.themeColor)
  10522. .trackColor($r('app.color.speed_text_color'))
  10523. .selectedColor(Color.White)
  10524. .trackThickness(6)
  10525. .onChange((value: number) => {
  10526. this.setLyricTextSize(value, isPip)
  10527. })
  10528. .width('76%')
  10529. }
  10530. .margin({
  10531. left: 20,
  10532. right: 15,
  10533. top: 5,
  10534. bottom: 5
  10535. })
  10536. Row() {
  10537. Text(`高亮倍数:`)
  10538. .fontSize(14)
  10539. .fontColor(Color.White)
  10540. Slider({
  10541. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  10542. min: 1,
  10543. max: 2,
  10544. step: 0.1,
  10545. style: SliderStyle.OutSet
  10546. })
  10547. .blockColor(this.themeColor)
  10548. .trackColor($r('app.color.speed_text_color'))
  10549. .selectedColor(Color.White)
  10550. .trackThickness(6)
  10551. .onChange((value: number) => {
  10552. this.setHighLyricTextSize(value, isPip)
  10553. })
  10554. .width('76%')
  10555. }
  10556. .margin({
  10557. left: 20,
  10558. right: 15,
  10559. top: 5,
  10560. bottom: 5
  10561. })
  10562. Row() {
  10563. Text(`歌词间隙:`)
  10564. .fontSize(14)
  10565. .fontColor(Color.White)
  10566. Slider({
  10567. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  10568. min: 0,
  10569. max: 100,
  10570. step: 1,
  10571. style: SliderStyle.OutSet
  10572. })
  10573. .blockColor(this.themeColor)
  10574. .trackColor($r('app.color.speed_text_color'))
  10575. .selectedColor(Color.White)
  10576. .trackThickness(6)
  10577. .onChange((value: number) => {
  10578. this.setLyricLineSpace(value, isPip)
  10579. })
  10580. .width('76%')
  10581. }
  10582. .margin({
  10583. left: 20,
  10584. right: 15,
  10585. top: 5,
  10586. bottom: 5
  10587. })
  10588. //取值间隔为100,默认为400,取值越大,字体越粗
  10589. Row() {
  10590. Text(`歌词字重:`)
  10591. .fontSize(14)
  10592. .fontColor(Color.White)
  10593. Slider({
  10594. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  10595. min: 100,
  10596. max: 900,
  10597. step: 100,
  10598. style: SliderStyle.OutSet
  10599. })
  10600. .blockColor(this.themeColor)
  10601. .trackColor($r('app.color.speed_text_color'))
  10602. .selectedColor(Color.White)
  10603. .trackThickness(6)
  10604. .onChange((value: number) => {
  10605. if (isPip) {
  10606. this.lyricTextWeightPip = value
  10607. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  10608. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  10609. } else {
  10610. this.lyricTextWeight = value
  10611. this.lyricController.setTextWeight(this.lyricTextWeight)
  10612. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  10613. }
  10614. })
  10615. .width('76%')
  10616. }
  10617. .margin({
  10618. left: 20,
  10619. right: 15,
  10620. top: 5,
  10621. bottom: 5
  10622. })
  10623. if (!isPip) {
  10624. Row() {
  10625. Text(`歌词模糊:`)
  10626. .fontSize(14)
  10627. .fontColor(Color.White)
  10628. Slider({
  10629. value: isPip ? this.blurDegreePip : this.blurDegree,
  10630. min: 0,
  10631. max: 5,
  10632. step: 0.1,
  10633. style: SliderStyle.OutSet
  10634. })
  10635. .blockColor(this.themeColor)
  10636. .trackColor($r('app.color.speed_text_color'))
  10637. .selectedColor(Color.White)
  10638. .trackThickness(6)
  10639. .onChange((value: number) => {
  10640. this.setBlurDegree(value, isPip)
  10641. })
  10642. .width('76%')
  10643. }
  10644. .margin({
  10645. left: 20,
  10646. right: 15,
  10647. top: 5,
  10648. bottom: 15
  10649. })
  10650. }
  10651. Row() {
  10652. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  10653. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  10654. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  10655. }
  10656. .justifyContent(FlexAlign.Center)
  10657. .margin({ top: 3, bottom: 10 })
  10658. }
  10659. }
  10660. private setBlurDegree(index: number, isPip: boolean) {
  10661. if (isPip) {
  10662. this.blurDegreePip = index
  10663. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  10664. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  10665. } else {
  10666. this.blurDegree = index
  10667. this.lyricController.setBlurDegree(this.blurDegree)
  10668. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  10669. }
  10670. }
  10671. private setLyricAlignMode(index: number, isPip: boolean) {
  10672. if (isPip) {
  10673. this.currentLyricAlignModePip = index
  10674. if (this.currentLyricAlignModePip === 1) {
  10675. this.lyricControllerXF.setAlignMode("left")
  10676. } else {
  10677. this.lyricControllerXF.setAlignMode("center")
  10678. }
  10679. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  10680. } else {
  10681. this.currentLyricAlignMode = index
  10682. if (this.currentLyricAlignMode === 1) {
  10683. this.lyricController.setAlignMode("left")
  10684. } else {
  10685. this.lyricController.setAlignMode("center")
  10686. }
  10687. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  10688. }
  10689. }
  10690. private setLyricTextSize(index: number, isPip: boolean) {
  10691. if (isPip) {
  10692. this.currentLyricSizePip = index
  10693. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  10694. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  10695. } else {
  10696. this.currentLyricSize = index
  10697. this.lyricController.setTextSize(this.currentLyricSize)
  10698. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  10699. }
  10700. }
  10701. private setHighLyricTextSize(scale: number, isPip: boolean) {
  10702. if (isPip) {
  10703. this.currentHightLyricSizePip = scale
  10704. this.lyricControllerXF
  10705. .setHighlightScale(this.currentHightLyricSizePip)
  10706. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  10707. } else {
  10708. this.currentHightLyricSize = scale
  10709. this.lyricController
  10710. .setHighlightScale(this.currentHightLyricSize)
  10711. PreferencesUtil.putSync('HighLyricTextSize', scale)
  10712. }
  10713. }
  10714. private setLyricLineSpace(index: number, isPip: boolean) {
  10715. if (isPip) {
  10716. this.currentLyricLineSpacePip = index
  10717. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  10718. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  10719. } else {
  10720. this.currentLyricLineSpace = index
  10721. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  10722. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  10723. }
  10724. }
  10725. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  10726. LogUtil.info('onecold isBG = ' + isBG)
  10727. if (isBG) { //如果是设置悬浮背景
  10728. this.pipBg = color
  10729. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  10730. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  10731. return
  10732. }
  10733. if (isPip) {
  10734. this.currentLyricColorPip = color
  10735. this.lyricControllerXF
  10736. .setTextColor(this.currentLyricColorPip)
  10737. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  10738. } else {
  10739. this.currentLyricColor = color
  10740. this.lyricController
  10741. .setTextColor(this.currentLyricColor)
  10742. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  10743. }
  10744. }
  10745. private changeLyricHightLightColor(color: string, isPip: boolean) {
  10746. if (isPip) {
  10747. this.currentHighLightLyricColorPip = color
  10748. this.lyricControllerXF
  10749. .setHighlightColor(this.currentHighLightLyricColorPip)
  10750. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  10751. } else {
  10752. this.currentHighLightLyricColor = color
  10753. this.lyricController
  10754. .setHighlightColor(this.currentHighLightLyricColor)
  10755. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  10756. }
  10757. }
  10758. // 构建时间控制器
  10759. @Builder
  10760. BuildTimeControls() {
  10761. Column() {
  10762. // 时间显示
  10763. Text(this.getTimeText())
  10764. .fontSize(18)
  10765. .fontColor(Color.White)
  10766. .margin({ bottom: 10 })
  10767. Row() {
  10768. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  10769. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  10770. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  10771. }
  10772. .justifyContent(FlexAlign.Center)
  10773. }
  10774. .margin({ top: 12, bottom: 8 })
  10775. }
  10776. // 精度按钮组件
  10777. @Builder
  10778. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  10779. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10780. Column() {
  10781. Image(icon)
  10782. .width(28)
  10783. .margin({ bottom: 5 })
  10784. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  10785. Text(label)
  10786. .fontSize(12)
  10787. .fontColor('#FFFFFF')
  10788. }
  10789. }
  10790. .backgroundColor(Color.Transparent)
  10791. .enabled(!this.isButtonDisabled(step))
  10792. .onClick(() => this.handlePrecisionAdjust(step))
  10793. .padding(5)
  10794. .width(66)
  10795. .height(66)
  10796. .margin({ left: 18, right: 18 })
  10797. .border({
  10798. color: '#FFFFFF',
  10799. width: 1.8
  10800. })
  10801. }
  10802. private handlePrecisionAdjust(step: number) {
  10803. if (step === 0) {
  10804. this.timeOffset = 0
  10805. return
  10806. }
  10807. // 精度处理:保留1位小数
  10808. const newOffset = Number((this.timeOffset + step).toFixed(5))
  10809. // 边界保护(±15.0秒)
  10810. if (newOffset < -30.0 || newOffset > 30.0) {
  10811. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  10812. return
  10813. }
  10814. // 状态更新
  10815. this.timeOffset = newOffset
  10816. }
  10817. // 按钮禁用逻辑
  10818. private isButtonDisabled(step: number): boolean {
  10819. const futureOffset = this.timeOffset + step
  10820. return (futureOffset < -30.0) || (futureOffset > 30.0)
  10821. }
  10822. // 时间显示文本升级
  10823. private getTimeText(): string {
  10824. const absValue = Math.abs(this.timeOffset)
  10825. return this.timeOffset === 0
  10826. ? '歌词时间已重置'
  10827. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  10828. }
  10829. // 导入 本地歌词 搜索歌词
  10830. @Builder
  10831. pushLyricButton(icon: Resource, step: number, label: string) {
  10832. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10833. Row() {
  10834. Image(icon)
  10835. .width(14)
  10836. .margin({ left: 13 })
  10837. Text(label)
  10838. .fontSize(12)
  10839. .margin({ left: 6 })
  10840. .fontColor('#FFFFFF')
  10841. }
  10842. }
  10843. .onClick(() => {
  10844. switch (step) {
  10845. case 0:
  10846. this.callFilePickerSelectFileForLyric()
  10847. break;
  10848. case 1:
  10849. //判断有没有设置api
  10850. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  10851. this.isLyricSetting = false
  10852. this.showTipsDialog()
  10853. return
  10854. }
  10855. if (StrUtil.isNotEmpty(this.videoUrl)) {
  10856. ToastUtil.showToast('正在获取')
  10857. this.isLyricSetting = false
  10858. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  10859. this.initLyric(lyricPath, true);
  10860. }
  10861. break;
  10862. }
  10863. })
  10864. .padding(5)
  10865. .width(110)
  10866. .backgroundColor(Color.Transparent)
  10867. .height(40)
  10868. .margin({ left: 6, right: 6 })
  10869. .border({
  10870. color: '#FFFFFF',
  10871. radius: 20,
  10872. width: 1.8
  10873. })
  10874. }
  10875. showVipDialog() {
  10876. DialogHelper.showCustomContentDialog({
  10877. dialogId: 'vip',
  10878. title: "友情提示",
  10879. autoCancel: false, //点击遮障层时,不关闭弹窗
  10880. backCancel: true, //点击返回键,不关闭弹窗
  10881. contentBuilder: () => {
  10882. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  10883. },
  10884. buttons: [],
  10885. })
  10886. }
  10887. //去赞助的自定义内容
  10888. @Builder
  10889. customVipBuilder(content: string) {
  10890. Column() {
  10891. Text(content)
  10892. .fontColor(Color.Gray)
  10893. .fontSize(16)
  10894. .alignSelf(ItemAlign.Start)
  10895. .margin({ bottom: 15 })
  10896. .fontSize(16)
  10897. Row() {
  10898. Button('取消')
  10899. .fontColor(Color.White)
  10900. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  10901. .height(50)
  10902. .layoutWeight(1)
  10903. .stateEffect(true)
  10904. .margin({ right: 6 })
  10905. .onClick(() => {
  10906. DialogHelper.closeDialog('vip'); //关闭弹框
  10907. })
  10908. Button('开通')
  10909. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  10910. .layoutWeight(1)
  10911. .height(50)
  10912. .backgroundColor(this.themeColor)
  10913. .stateEffect(true)
  10914. .margin({ left: 6 })
  10915. .onClick(() => {
  10916. DialogHelper.closeDialog('vip'); //关闭弹框
  10917. this.isShowPlay = false
  10918. this.mType = 1 //跳转到用户中心
  10919. // router.pushUrl({
  10920. // url: 'pages/VipPage'
  10921. // }, router.RouterMode.Single);
  10922. })
  10923. }
  10924. }
  10925. .width("100%")
  10926. .padding(10)
  10927. }
  10928. showTipsDialog() {
  10929. DialogHelper.showCustomContentDialog({
  10930. dialogId: 'tips',
  10931. title: "友情提示",
  10932. autoCancel: false, //点击遮障层时,不关闭弹窗
  10933. backCancel: true, //点击返回键,不关闭弹窗
  10934. contentBuilder: () => {
  10935. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  10936. },
  10937. buttons: [],
  10938. })
  10939. }
  10940. @Builder
  10941. customTipsBuilder(content: string) {
  10942. Column() {
  10943. Text(content)
  10944. .fontColor(Color.Gray)
  10945. .fontSize(16)
  10946. .alignSelf(ItemAlign.Start)
  10947. .margin({ bottom: 15 })
  10948. .fontSize(16)
  10949. Row() {
  10950. Button('取消')
  10951. .fontColor(Color.White)
  10952. .backgroundColor(this.themeColor)
  10953. .height(50)
  10954. .layoutWeight(1)
  10955. .stateEffect(true)
  10956. .margin({ right: 6 })
  10957. .onClick(() => {
  10958. DialogHelper.closeDialog('tips'); //关闭弹框
  10959. })
  10960. Button('跳转')
  10961. .fontColor(Color.White)//
  10962. .layoutWeight(1)
  10963. .height(50)
  10964. .backgroundColor(this.themeColor)
  10965. .stateEffect(true)
  10966. .margin({ left: 6 })
  10967. .onClick(() => {
  10968. DialogHelper.closeDialog('tips'); //关闭弹框
  10969. this.isShowEdit = false
  10970. this.longItemFilePath = ''
  10971. // if(this.isGridMusic&&!this.isShowPlay){
  10972. // this.longItemFilePath== ''
  10973. // }else{
  10974. // this.isShowEdit = false
  10975. // }
  10976. this.isShowMoreView = false;
  10977. this.isShowPlay = false
  10978. this.mType = 4
  10979. // router.pushUrl({
  10980. // url: 'pages/SettingPage'
  10981. // }, router.RouterMode.Single);
  10982. })
  10983. }
  10984. }
  10985. .width("100%")
  10986. .padding(10)
  10987. }
  10988. @Builder
  10989. PlayMoreSheet() {
  10990. Column() {
  10991. this.MoreList()
  10992. }
  10993. .width('100%')
  10994. .height('100%')
  10995. }
  10996. @Builder
  10997. MoreList() {
  10998. Scroll() {
  10999. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  11000. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  11001. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  11002. Row() {
  11003. if (more.id === 3&&this.currentSong) {
  11004. Image(more.image)
  11005. .width(24)
  11006. .height(24)
  11007. .margin({ left: 10, right: 10 })
  11008. Text(more.title)
  11009. .fontSize(16)
  11010. .fontColor(Color.White)
  11011. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  11012. height: this.isCoverOpacity() ? '95%' : '95%',
  11013. dragBar: true,
  11014. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11015. showClose: true,
  11016. blurStyle: BlurStyle.Thin,
  11017. backgroundColor: Color.Transparent,
  11018. title: { title: '歌曲信息' }
  11019. })
  11020. } else if (more.id === 15 && this.currentSong) { //编辑标签
  11021. Image(more.image)
  11022. .width(24)
  11023. .height(24)
  11024. .margin({ left: 10, right: 10 })
  11025. Text(more.title)
  11026. .fontSize(16)
  11027. .fontColor(Color.White)
  11028. } else if (more.id === 5) { //定时关闭
  11029. Image(more.image)
  11030. .width(24)
  11031. .height(24)
  11032. .margin({ left: 10, right: 10 })
  11033. Text(more.title)
  11034. .fontSize(16)
  11035. .fontColor(Color.White)
  11036. .onClick(() => {
  11037. this.doMore(more.id)
  11038. })
  11039. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  11040. height: this.isCoverOpacity() ? '95%' : '95%',
  11041. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11042. dragBar: true,
  11043. showClose: true,
  11044. title: { title: $r('app.string.time_close') }
  11045. })
  11046. } else if (more.id === 2) { //歌词设置
  11047. Image(more.image)
  11048. .width(24)
  11049. .height(24)
  11050. .margin({ left: 10, right: 10 })
  11051. Text(more.title)
  11052. .fontSize(16)
  11053. .fontColor(Color.White)
  11054. } else if (more.id === 16) { //悬浮歌词设置
  11055. Image(more.image)
  11056. .width(24)
  11057. .height(24)
  11058. .margin({ left: 10, right: 10 })
  11059. Text(more.title)
  11060. .fontSize(16)
  11061. .fontColor(Color.White)
  11062. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  11063. height: this.isCoverOpacity() ? '95%' : '95%',
  11064. dragBar: true,
  11065. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11066. showClose: true,
  11067. blurStyle: BlurStyle.Thin,
  11068. backgroundColor: Color.Transparent,
  11069. title: { title: '悬浮歌词' }
  11070. })
  11071. } else if (more.id === 11) {
  11072. Image(more.image)
  11073. .width(24)
  11074. .height(24)
  11075. .margin({ left: 10, right: 10 })
  11076. Text(more.title)
  11077. .fontSize(16)
  11078. .fontColor(Color.White)
  11079. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  11080. height: this.isCoverOpacity() ? '95%' : '60%',
  11081. dragBar: true,
  11082. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11083. showClose: true,
  11084. blurStyle: BlurStyle.Thin,
  11085. backgroundColor: Color.Transparent,
  11086. title: { title: '跳过头尾' }
  11087. })
  11088. } else if (more.id === 12) { //投播
  11089. AVCastPicker({
  11090. customPicker: (): void => this.TPImageBuilder(more),
  11091. onStateChange: (state) => {
  11092. if (state == AVCastPickerState.STATE_APPEARING) {
  11093. console.log(' The picker starts showing.');
  11094. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  11095. console.log(' The picker finishes presenting.');
  11096. }
  11097. },
  11098. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  11099. sessionType: 'video'
  11100. })
  11101. .id('AVCastPicker')
  11102. } else {
  11103. Image(more.image)
  11104. .width(24)
  11105. .height(24)
  11106. .fillColor(Color.White)
  11107. .margin({ left: 10, right: 10 })
  11108. .onClick(() => {
  11109. this.doMore(more.id)
  11110. })
  11111. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  11112. .fontSize(16)
  11113. .fontColor(Color.White)
  11114. .onClick(() => {
  11115. this.doMore(more.id)
  11116. })
  11117. Select([//倍速
  11118. { value: '0.25x' },
  11119. { value: '0.5x' },
  11120. { value: '0.75x' },
  11121. { value: '1x' },
  11122. { value: '1.25x' },
  11123. { value: '1.5x' },
  11124. { value: '1.75x' },
  11125. { value: '2x' },
  11126. { value: '3x' }])
  11127. .font({ size: 16, weight: FontWeight.Medium })
  11128. .fontColor($r('sys.color.white'))
  11129. .margin({ left: 25 })
  11130. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  11131. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  11132. .value(Utility.optimizedFormat(this.playSpeed))
  11133. .onSelect(async (_index: number, text?: string | undefined) => {
  11134. let speed = parseFloat(text?.replace('x', '') || '1');
  11135. if (!CommonConstants.video_speed_list.includes(speed)) {
  11136. speed = 1;
  11137. }
  11138. this.playSpeed = speed
  11139. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  11140. })
  11141. Slider({
  11142. value: this.volume,
  11143. min: 0,
  11144. max: 1,
  11145. step: 0.1,
  11146. style: SliderStyle.OutSet
  11147. })
  11148. .margin({ left: 18, right: 8 })
  11149. .blockColor(this.themeColor)
  11150. .trackColor($r('app.color.speed_text_color'))
  11151. .selectedColor(Color.White)
  11152. .trackThickness(9)
  11153. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  11154. .onChange((value: number) => {
  11155. this.volume = value;
  11156. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  11157. PreferencesUtil.putSync('DefalutVolume',this.volume)
  11158. })
  11159. .layoutWeight(1)
  11160. Blank()
  11161. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  11162. .selectedColor(this.themeColor)
  11163. .switchPointColor(Color.White)
  11164. .margin({ right: 15 })
  11165. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11166. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  11167. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11168. if (more.id == 6) {
  11169. this.isMusicMemoryPlay = checked;
  11170. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  11171. if (this.isMusicMemoryPlay) {
  11172. ToastUtil.showToast('记忆播放已开启')
  11173. } else {
  11174. ToastUtil.showToast('记忆播放已关闭')
  11175. }
  11176. }
  11177. })
  11178. .width(48)
  11179. .height(24);
  11180. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  11181. .selectedColor(this.themeColor)
  11182. .switchPointColor(Color.White)
  11183. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11184. .margin({ right: 15 })
  11185. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  11186. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11187. if (more.id == 7) {
  11188. this.isMusicBGCover = checked;
  11189. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  11190. if (this.isMusicBGCover) {
  11191. ToastUtil.showToast('播放背景随音乐封面已开启')
  11192. } else {
  11193. ToastUtil.showToast('播放背景随音乐封面已关闭')
  11194. }
  11195. }
  11196. })
  11197. .width(48)
  11198. .height(24);
  11199. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  11200. .selectedColor(this.themeColor)
  11201. .switchPointColor(Color.White)
  11202. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11203. .margin({ right: 15 })
  11204. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  11205. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11206. if (more.id == 8) {
  11207. this.isSavePlayMode = checked;
  11208. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  11209. if (this.isSavePlayMode) {
  11210. ToastUtil.showToast('保存播放模式已开启')
  11211. } else {
  11212. ToastUtil.showToast('保存播放模式已关闭')
  11213. }
  11214. }
  11215. })
  11216. .width(48)
  11217. .height(24);
  11218. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  11219. .selectedColor(this.themeColor)
  11220. .switchPointColor(Color.White)
  11221. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11222. .margin({ right: 15 })
  11223. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  11224. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11225. if (more.id == 13) {
  11226. this.isCoverRectangle = checked;
  11227. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  11228. if (this.isCoverRectangle) {
  11229. ToastUtil.showToast('封面方形已开启')
  11230. this.animationRoFun()
  11231. } else {
  11232. ToastUtil.showToast('封面圆形已开启')
  11233. this.animationRoFun()
  11234. }
  11235. }
  11236. })
  11237. .width(48)
  11238. .height(24);
  11239. Toggle({ type: ToggleType.Switch, isOn: this.isShowBgLiuGUANG })
  11240. .selectedColor(this.themeColor)
  11241. .switchPointColor(Color.White)
  11242. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11243. .margin({ right: 15 })
  11244. .visibility(more.id == 21 ? Visibility.Visible : Visibility.None)
  11245. .onChange((checked: boolean) => { // 是否开启背景流光效果
  11246. if (more.id == 21) {
  11247. this.isShowBgLiuGUANG = checked;
  11248. PreferencesUtil.putSync('isShowBgLiuGUANG',this.isShowBgLiuGUANG)
  11249. }
  11250. })
  11251. .width(48)
  11252. .height(24);
  11253. }
  11254. }
  11255. .width('100%')
  11256. .height(45)
  11257. .padding(15)
  11258. .backgroundColor(Color.Transparent)
  11259. .borderRadius(12)
  11260. .margin({ bottom: 6 })
  11261. }
  11262. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  11263. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  11264. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  11265. .backgroundColor(Color.Transparent)
  11266. .onClick(() => {
  11267. this.doMore(more.id)
  11268. })
  11269. });
  11270. }
  11271. .width('100%')
  11272. .padding(16)
  11273. }.margin({ bottom: 18 })
  11274. }
  11275. @Builder
  11276. TPImageBuilder(more: MoreItem): void {
  11277. Row() {
  11278. Image($r('app.media.tuoping'))
  11279. .width(22)
  11280. .height(22)
  11281. .margin({ left: 10, right: 10 })
  11282. Text(more.title)
  11283. .fontSize(16)
  11284. .fontColor(Color.White)
  11285. }
  11286. .width('100%')
  11287. .layoutWeight(1)
  11288. .alignItems(VerticalAlign.Center)
  11289. .justifyContent(FlexAlign.Start)
  11290. }
  11291. private moreItems: MoreItem[] = [
  11292. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  11293. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  11294. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  11295. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  11296. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  11297. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  11298. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  11299. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  11300. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  11301. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  11302. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  11303. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  11304. { id: 4, image: $r('app.media.share2'), title: '分享' },
  11305. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  11306. // { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  11307. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  11308. { id : 21, image: $r('app.media.music_red'), title: '开启背景流光' },
  11309. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  11310. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  11311. ];
  11312. @State isShowBgLiuGUANG: boolean = true;
  11313. @State isShowMoreView: boolean = false;
  11314. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  11315. @State isShowTimeCloseMore: boolean = false
  11316. @State isShowDetailMore: boolean = false
  11317. @State isMusicBGCover: boolean = true
  11318. @State isSavePlayMode: boolean = true
  11319. @State isLyricSetting: boolean = false
  11320. @State isJumpSetting: boolean = false
  11321. @State isShowEdit: boolean = false
  11322. @State showPipLyric: boolean = false
  11323. async setRingTone() {
  11324. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  11325. return
  11326. }
  11327. // 确定后的逻辑
  11328. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  11329. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  11330. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  11331. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  11332. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  11333. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  11334. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  11335. , this.videoUrl, this.name).then(res => {
  11336. LogUtil.info('onecold setFlag :' + res);
  11337. });
  11338. }
  11339. doMore(moreId: number) {
  11340. switch (moreId) {
  11341. case 2: //歌词
  11342. this.isLyricSetting = !this.isLyricSetting;
  11343. this.isShowMoreView = false
  11344. break;
  11345. case 3: //详情
  11346. this.isShowDetailMore = !this.isShowDetailMore;
  11347. break;
  11348. case 4: //分享
  11349. if (this.currentSong !== undefined) {
  11350. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  11351. }
  11352. this.isShowMoreView = false
  11353. break;
  11354. case 5: //定时关闭
  11355. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  11356. break;
  11357. case 10: //设为铃声
  11358. this.setRingTone()
  11359. this.isShowMoreView = false
  11360. break;
  11361. case 11: //跳过头尾
  11362. this.isJumpSetting = !this.isJumpSetting;
  11363. break;
  11364. case 13: //倍速
  11365. break;
  11366. case 14: //搜索封面
  11367. if (this.currentSong !== undefined) {
  11368. this.doSearchCover(this.currentSong)
  11369. }
  11370. this.isShowMoreView = false
  11371. break;
  11372. case 15: //编辑标签
  11373. this.initEditFields(this.currentSong)
  11374. this.tempLyricContent = this.lyricContent
  11375. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  11376. this.lyricConStr = this.tempLyricContent
  11377. }
  11378. this.isShowEdit = !this.isShowEdit;
  11379. break;
  11380. case 16: //悬浮歌词
  11381. this.showPipLyric = !this.showPipLyric;
  11382. break;
  11383. case 17: //横屏模式
  11384. if (this.isLandscape) {
  11385. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  11386. } else {
  11387. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  11388. }
  11389. this.isShowMoreView = false
  11390. break;
  11391. case 20://AB循环
  11392. this.isABSheet = !this.isABSheet
  11393. break;
  11394. }
  11395. }
  11396. //AB循环
  11397. @State isOpenAB:boolean = false
  11398. @State jumpATime:number = 0
  11399. @State jumpBTime:number = 0
  11400. @State isABSheet:boolean = false
  11401. @Builder
  11402. ABLoopSheet() {
  11403. ABLoopComptent({
  11404. jumpATime:this.jumpATime,
  11405. jumpBTime:this.jumpBTime,
  11406. onClickAItem: async ()=>{
  11407. if(this.mIjkMediaPlayer){
  11408. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  11409. }
  11410. },
  11411. onClickBItem: async ()=>{
  11412. if(this.mIjkMediaPlayer){
  11413. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  11414. if(this.jumpBTime<=this.jumpATime){
  11415. ToastUtil.showToast('设置B点时间不能小于A点时间')
  11416. this.jumpBTime = 0
  11417. }
  11418. }
  11419. },
  11420. onCancleButtonClick: async ()=>{
  11421. this.isOpenAB = false
  11422. this.isABSheet = false
  11423. },
  11424. onStartButtonClick: async ()=>{
  11425. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  11426. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  11427. return
  11428. }
  11429. this.isABSheet = false
  11430. this.startABLoop()
  11431. },
  11432. })
  11433. }
  11434. //开始AB循环
  11435. startABLoop(){
  11436. if(this.mIjkMediaPlayer){
  11437. this.seekTo(this.jumpATime+'')
  11438. this.isOpenAB = true
  11439. }
  11440. }
  11441. /**
  11442. * 切换横竖屏
  11443. *
  11444. */
  11445. setOrientation(orientation: number) {
  11446. this.windowClass.setPreferredOrientation(orientation).then(() => {
  11447. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  11448. }).catch((err: BusinessError) => {
  11449. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  11450. });
  11451. }
  11452. /**
  11453. * 画中画功能(悬浮歌词功能)
  11454. *
  11455. */
  11456. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  11457. pipController?: PiPWindow.PiPController;
  11458. navigationId: string = '';
  11459. @State curState: string = '';
  11460. @State curError: ResourceStr = '';
  11461. @State pipBg: string = '#E8E8E8'
  11462. @State buttonAction: string = '';
  11463. //开启画中画功能
  11464. async startPip() {
  11465. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  11466. if (!this.pipController) {
  11467. await this.createPipController();
  11468. }
  11469. if (!this.pipController) {
  11470. Logger.info(`[${TAG}] pipController create error`);
  11471. return;
  11472. }
  11473. await this.pipController.startPiP();
  11474. }
  11475. async stopPip() {
  11476. if (!this.pipController) {
  11477. Logger.info(`[${TAG}] pipController is not exist`);
  11478. return;
  11479. }
  11480. this.isOpenPip = false
  11481. await this.pipController.stopPiP();
  11482. }
  11483. async createPipController() {
  11484. this.pipController = await PiPWindow.create({
  11485. context: getContext(this),
  11486. componentController: this.xcomponentController,
  11487. navigationId: this.navigationId,
  11488. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  11489. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  11490. customUIController: this.nodeController,
  11491. });
  11492. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  11493. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  11494. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  11495. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  11496. this.onStateChange(state, reason);
  11497. });
  11498. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  11499. this.onActionEvent(event, status);
  11500. });
  11501. }
  11502. destroyPipController() {
  11503. if (!this.pipController) {
  11504. return;
  11505. }
  11506. this.pipController.off('stateChange');
  11507. this.pipController.off('controlPanelActionEvent');
  11508. this.pipController = undefined;
  11509. }
  11510. onStateChange(state: PiPWindow.PiPState, reason: string) {
  11511. switch (state) {
  11512. case PiPWindow.PiPState.ABOUT_TO_START:
  11513. this.curState = 'ABOUT_TO_START';
  11514. this.curError = $r('app.string.current_error_hint');
  11515. break;
  11516. case PiPWindow.PiPState.STARTED:
  11517. this.curState = 'STARTED';
  11518. this.curError = $r('app.string.current_error_hint');
  11519. break;
  11520. case PiPWindow.PiPState.ABOUT_TO_STOP:
  11521. this.curState = 'ABOUT_TO_STOP';
  11522. this.curError = $r('app.string.current_error_hint');
  11523. break;
  11524. case PiPWindow.PiPState.STOPPED:
  11525. this.curState = 'STOPPED';
  11526. this.curError = $r('app.string.current_error_hint');
  11527. this.stopPip()
  11528. this.destroyPipController()
  11529. break;
  11530. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  11531. this.curState = 'ABOUT_TO_RESTORE';
  11532. this.curError = $r('app.string.current_error_hint');
  11533. break;
  11534. case PiPWindow.PiPState.ERROR:
  11535. this.curState = 'ERROR';
  11536. this.curError = reason;
  11537. break;
  11538. default:
  11539. break;
  11540. }
  11541. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  11542. }
  11543. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  11544. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  11545. switch (event) {
  11546. case 'playbackStateChanged':
  11547. if (status === 0) {
  11548. this.pause();
  11549. } else {
  11550. console.info('onecold startPlayOrResumePlay 9869')
  11551. this.startPlayOrResumePlay();
  11552. }
  11553. break;
  11554. case 'nextVideo':
  11555. // 切换到下一个视频
  11556. this.playNext().catch(() => {
  11557. Logger.error('heanup onActionEvent playNext', `播放下一首失败`);
  11558. });
  11559. break;
  11560. case 'previousVideo':
  11561. // 切换到上一个视频
  11562. this.playPrevious().catch(() => {
  11563. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败`);
  11564. });
  11565. break;
  11566. case 'previousVideo':
  11567. // 切换到上一个视频
  11568. this.playPrevious().catch(() => {
  11569. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败:`);
  11570. });
  11571. break;
  11572. default:
  11573. }
  11574. this.buttonAction = event + `-status:${status}`;
  11575. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  11576. }
  11577. /**
  11578. * 画中画功能(悬浮歌词功能)结束
  11579. *
  11580. */
  11581. async doSearchCover(item: VideoItem,title?:string,artist?:string): Promise<string> {
  11582. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  11583. this.isShowMoreView = false;
  11584. this.showTipsDialog();
  11585. return ''; // Return empty string when no API is configured
  11586. }
  11587. if (!item) {
  11588. return ''; // Return empty string if item is undefined
  11589. }
  11590. const titleS = title||item?.name || '';
  11591. const artistS = artist||item?.artist || ''; // Use empty string if artist is missing
  11592. return this.searchCover(item, titleS, artistS); // Await is not needed here as we return the promise directly
  11593. }
  11594. /**
  11595. *api搜索封面
  11596. *item,根据title和artist
  11597. */
  11598. searchCover(item: VideoItem, title: string, artist: string): Promise<string> {
  11599. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  11600. LogUtil.debug("onecold res =" + res);
  11601. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  11602. if (item.filePath == this.currentSong?.filePath) {
  11603. this.cover = res;
  11604. if (this.currentSong) {
  11605. this.currentSong.pixelMapPath = res;
  11606. }
  11607. }
  11608. // Update pixel map path but always return res regardless of success
  11609. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  11610. if (success) {
  11611. this.doUpdateData();
  11612. console.log("onecold 更新音乐封面成功,数据库已同步");
  11613. } else {
  11614. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  11615. }
  11616. // Note: We don't resolve/reject here because we already returned res
  11617. });
  11618. LogUtil.debug("onecold this.cover =" + this.cover);
  11619. }
  11620. return res; // Always return res regardless of updatePixelMapPath result
  11621. });
  11622. }
  11623. @State jumpTopTime: number = 0
  11624. @State jumpEndTime: number = 0
  11625. @State isOpenJump: boolean = false
  11626. @Builder
  11627. JumpTopEndSheet() {
  11628. Scroll() {
  11629. Column() {
  11630. Column() {
  11631. Text('仅对本播放列表有效')
  11632. .fontSize(16)
  11633. .fontColor($r('app.color.text_color'))
  11634. // 跳过头尾
  11635. Column() {
  11636. Row() {
  11637. Text('跳过片头:')
  11638. .fontSize(16)
  11639. .fontColor($r('app.color.text_color'))
  11640. Text(this.jumpTopTime + 's')
  11641. .fontSize(16)
  11642. .fontColor($r('app.color.text_color'))
  11643. }
  11644. .margin({ bottom: 5 })
  11645. Row() {
  11646. Slider({
  11647. value: this.jumpTopTime,
  11648. min: 0,
  11649. max: 120,
  11650. step: 1,
  11651. style: SliderStyle.OutSet
  11652. })
  11653. .blockColor(this.themeColor)
  11654. .trackColor($r('app.color.speed_text_color'))
  11655. .selectedColor(Color.White)
  11656. .trackThickness(8)
  11657. .onChange((value: number) => {
  11658. this.jumpTopTime = value;
  11659. })
  11660. .width('85%')
  11661. }
  11662. .alignItems(VerticalAlign.Top)
  11663. }
  11664. .margin({ top: 10, bottom: 10 })
  11665. // 跳过头尾
  11666. Column() {
  11667. Row() {
  11668. Text('跳过片尾:')
  11669. .fontSize(16)
  11670. .fontColor($r('app.color.text_color'))
  11671. Text(this.jumpEndTime + 's')
  11672. .fontSize(16)
  11673. .fontColor($r('app.color.text_color'))
  11674. }
  11675. .margin({ bottom: 5 })
  11676. Row() {
  11677. Slider({
  11678. value: this.jumpEndTime,
  11679. min: 0,
  11680. max: 120,
  11681. step: 1,
  11682. style: SliderStyle.OutSet
  11683. })
  11684. .blockColor(this.themeColor)
  11685. .trackColor($r('app.color.speed_text_color'))
  11686. .selectedColor(Color.White)
  11687. .trackThickness(8)
  11688. .onChange((value: number) => {
  11689. this.jumpEndTime = value;
  11690. })
  11691. .width('85%')
  11692. }
  11693. .alignItems(VerticalAlign.Top)
  11694. }
  11695. .margin({ top: 10, bottom: 10 })
  11696. Row() {
  11697. Button('保存设置')
  11698. .fontColor(Color.White)
  11699. .layoutWeight(1)
  11700. .height(40)
  11701. .width(80)
  11702. .backgroundColor(this.themeColor)
  11703. .stateEffect(true)
  11704. .margin({ left: 0, bottom: 20 })
  11705. .onClick(async () => {
  11706. if (!Utility.isNoble()) {
  11707. this.isJumpSetting = false
  11708. this.isShowMoreView = false
  11709. this.showVipDialog()
  11710. return
  11711. }
  11712. if (this.currentSong === undefined) {
  11713. return
  11714. }
  11715. if (this.modeType === 0) {
  11716. let parentPath = FileUtil.getParentPath(this.videoUrl)
  11717. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  11718. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  11719. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  11720. } else if (this.modeType === 1) { //媒体库
  11721. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  11722. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  11723. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  11724. } else if (this.modeType === 2) { //艺术家
  11725. if (this.currentSong?.artist) {
  11726. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  11727. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  11728. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  11729. }
  11730. } else if (this.modeType === 3) { //专辑
  11731. if (this.currentSong?.album) {
  11732. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  11733. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  11734. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  11735. }
  11736. }
  11737. ToastUtil.showShort("保存成功")
  11738. this.isJumpSetting = false
  11739. })
  11740. }
  11741. .margin({
  11742. left: 38,
  11743. right: 38,
  11744. top: 10,
  11745. bottom: 10
  11746. })
  11747. .width(120)
  11748. .height(50)
  11749. }
  11750. }
  11751. }
  11752. .width('100%')
  11753. .height('100%')
  11754. }
  11755. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  11756. private onStateVastChange(state: AVCastPickerState) {
  11757. if (state == AVCastPickerState.STATE_APPEARING) {
  11758. console.log('The picker starts showing.');
  11759. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  11760. console.log('The picker finishes presenting.');
  11761. }
  11762. }
  11763. private showSelectLyric() {
  11764. DialogHelper.showActionSheetDialog({
  11765. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  11766. // sheets: ["本地歌词", "搜索歌词"],
  11767. sheets: [
  11768. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  11769. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  11770. ],
  11771. maskColor: Color.Transparent,
  11772. backgroundColor: $r('app.color.bg_card'),
  11773. transition: AnimationHelper.transitionInDown(666),
  11774. onAction: (index) => {
  11775. switch (index) {
  11776. case 0:
  11777. this.callFilePickerSelectFileForLyric()
  11778. break;
  11779. case 1:
  11780. if (StrUtil.isNotEmpty(this.videoUrl)) {
  11781. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  11782. this.initLyric(lyricPath);
  11783. }
  11784. break;
  11785. }
  11786. }
  11787. })
  11788. }
  11789. // 拉起picker选择文件管理器
  11790. async callFilePickerSelectFileForLyric(): Promise<void> {
  11791. try {
  11792. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  11793. DocumentSelectOptions.maxSelectNumber = 1
  11794. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  11795. let documentPicker = new picker.DocumentViewPicker();
  11796. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  11797. Logger.info(TAG,
  11798. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  11799. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  11800. this.saveVideoDatasLyric(DocumentSelectResult)
  11801. }
  11802. }).catch((err: BusinessError) => {
  11803. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  11804. });
  11805. } catch (err) {
  11806. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  11807. }
  11808. }
  11809. async saveVideoDatasLyric(uris: string[]) {
  11810. if (ArrayUtil.isEmpty(uris)) {
  11811. return
  11812. }
  11813. let newUris: string[] = [];
  11814. for (let i = 0; i < uris.length; i++) {
  11815. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  11816. Logger.info(TAG, 'filePath uri: ' + filePath);
  11817. newUris.push(filePath)
  11818. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  11819. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  11820. fileIo.copyFileSync(file.fd, file2.fd)
  11821. fileIo.closeSync(file);
  11822. fileIo.closeSync(file2);
  11823. this.initLyric(filePath,false,false,true)
  11824. }
  11825. }
  11826. private initDelayPlay(context: object) {
  11827. this.mContext = context;
  11828. }
  11829. startPipLyric() {
  11830. if (this.pipController) {
  11831. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  11832. PiPWindow.PiPControlStatus.PLAY);
  11833. }
  11834. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  11835. if (this.isOpenPip) {
  11836. this.startPip()
  11837. } else {
  11838. this.stopPip()
  11839. }
  11840. }
  11841. //startOffset 从cue分轨时间开始播
  11842. private startPlayOrResumePlay(startOffset?:number) {
  11843. //针对dsf文件高采样率,统一转wav播放
  11844. const sampleRate = this.currentSong?.sampleRate||0
  11845. if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  11846. console.info('onecold 采样率 ='+sampleRate)
  11847. let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  11848. console.info('onecold newDsfPath ='+newDsfPath)
  11849. if(!FileUtil.accessSync(newDsfPath)){
  11850. const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  11851. taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  11852. this.videoUrl = newDsfPath
  11853. this.startPlay(startOffset)
  11854. }).catch((e:object)=>{
  11855. console.info("task1 catch e: " + e);
  11856. })
  11857. }else{
  11858. this.videoUrl = newDsfPath
  11859. this.startPlay(startOffset)
  11860. }
  11861. }else{
  11862. this.startPlay(startOffset)
  11863. }
  11864. }
  11865. startPlay(startOffset?:number) {
  11866. this.startPipLyric()
  11867. this.mDestroyPage = false;
  11868. this.animationState = AnimationStatus.Running
  11869. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  11870. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  11871. this.stopProgressTask();
  11872. this.startProgressTask();
  11873. this.play(this.videoUrl.toString(),startOffset);
  11874. }
  11875. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  11876. this.mIjkMediaPlayer.start();
  11877. this.setProgress()
  11878. this.CONTROL_PlayStatus = PlayStatus.PLAY
  11879. }
  11880. this.setIsPlaying(true)
  11881. this.updateSessionPlayState(true)
  11882. this.watchStatus();
  11883. this.updateLastPlayTimeStr(this.videoUrl)
  11884. }
  11885. updateLastPlayTimeStr(filePath: string) {
  11886. // 检查是否为网络音频(WebDAV),如果是则不更新本地数据库
  11887. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  11888. Logger.info(`heanup 检测到网络音频播放,跳过数据库更新: ${filePath}`)
  11889. return;
  11890. }
  11891. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  11892. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  11893. if (success) {
  11894. this.getHistoryList(false)
  11895. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  11896. } else {
  11897. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  11898. }
  11899. });
  11900. }
  11901. private completionNum(num: number): string | number {
  11902. if (num < 10) {
  11903. return '0' + num;
  11904. } else {
  11905. return num;
  11906. }
  11907. }
  11908. private stringForTime(timeMs: number): string {
  11909. let totalSeconds: number | string = (timeMs / 1000);
  11910. let newSeconds: number | string = totalSeconds % 60;
  11911. let minutes: number | string = (totalSeconds / 60) % 60;
  11912. let hours: number | string = totalSeconds / 3600;
  11913. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  11914. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  11915. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  11916. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  11917. if (this.isCurrentTime) {
  11918. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  11919. this.oldSeconds = newSeconds
  11920. } else {
  11921. newSeconds = this.oldSeconds
  11922. }
  11923. }
  11924. newSeconds = this.completionNum(newSeconds);
  11925. if (hours > 0) {
  11926. return hours + ":" + minutes + ":" + newSeconds;
  11927. } else {
  11928. return minutes + ":" + newSeconds;
  11929. }
  11930. }
  11931. private setProgress() {
  11932. let position = this.mIjkMediaPlayer.getCurrentPosition();
  11933. let duration = this.mIjkMediaPlayer.getDuration();
  11934. let pos = 0;
  11935. if (duration > 0) {
  11936. this.slideEnable = true;
  11937. let curPercent = position / duration;
  11938. pos = curPercent * 100;
  11939. if (pos > this.PROGRESS_MAX_VALUE) {
  11940. this.progressValue = this.PROGRESS_MAX_VALUE
  11941. } else {
  11942. this.progressValue = pos;
  11943. }
  11944. }
  11945. // LogUtils.getInstance()
  11946. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  11947. this.totalTime = this.stringForTime(duration);
  11948. if (position > duration) {
  11949. position = duration;
  11950. }
  11951. this.isCurrentTime = true;
  11952. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  11953. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  11954. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  11955. this.currentTime = this.stringForTime(position);
  11956. this.isCurrentTime = false
  11957. if (this.mIjkMediaPlayer.isPlaying()) {
  11958. this.randomColor =
  11959. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  11960. //如果是开启AB循环
  11961. if(this.isOpenAB){
  11962. if(position >=this.jumpBTime){
  11963. this.seekTo(this.jumpATime+'')
  11964. return
  11965. }
  11966. }
  11967. // 判断是否播放到结束时间
  11968. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  11969. if (position >= duration - this.jumpEndTime * 1000) {
  11970. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  11971. this.CONTROL_PlayStatus = PlayStatus.INIT
  11972. this.startPlayOrResumePlay();
  11973. }else if (this.playType == 2) { //2:正常播放,单曲播完
  11974. this.showRePlay();
  11975. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  11976. this.progressValue = this.PROGRESS_MAX_VALUE;
  11977. this.slideEnable = false;
  11978. this.stop();
  11979. // ToastUtil.showToast('开始重新播放')
  11980. }else{
  11981. this.playNext().catch(() => {
  11982. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  11983. });
  11984. }
  11985. }
  11986. }
  11987. } else {
  11988. this.randomColor = 'rbg(0,0,0)'
  11989. }
  11990. }
  11991. private startProgressTask() {
  11992. let that = this;
  11993. this.updateProgressTimer = setInterval(() => {
  11994. //LogUtils.getInstance().LOGI("startProgressTask");
  11995. if (!that.mDestroyPage) {
  11996. that.setProgress();
  11997. }
  11998. }, 300);
  11999. }
  12000. private stopProgressTask() {
  12001. LogUtils.getInstance().LOGI("stopProgressTask");
  12002. clearInterval(this.updateProgressTimer);
  12003. }
  12004. private showLoadIng() {
  12005. this.loadingVisible = Visibility.Visible;
  12006. this.replayVisible = Visibility.None;
  12007. }
  12008. private hideLoadIng() {
  12009. this.loadingVisible = Visibility.None;
  12010. this.replayVisible = Visibility.None;
  12011. }
  12012. private showRePlay() {
  12013. this.loadingVisible = Visibility.None;
  12014. this.replayVisible = Visibility.Visible;
  12015. }
  12016. private async play(url: string,startOffset?:number) {
  12017. this.isShowBgLiuGUANG = PreferencesUtil.getBooleanSync('isShowBgLiuGUANG', true)
  12018. console.info('onecold this.url 1= '+url)
  12019. if(!url.toLowerCase().startsWith('http')){
  12020. let hasPermission = await PermissionUtil.activatePermission(url)
  12021. console.info('onecold this.hasPermission 1= '+hasPermission)
  12022. if(!url.includes(this.packName)){
  12023. const file = fs.openSync(url)
  12024. this.videoUrl = file.path
  12025. url= this.videoUrl
  12026. }
  12027. console.info('onecold this.hasPermission 1= '+hasPermission)
  12028. console.info('onecold this.videoUrl 1= '+this.videoUrl)
  12029. }
  12030. let that = this;
  12031. that.showLoadIng();
  12032. this.isOpenAB = false
  12033. //设置XComponent回调的context
  12034. if (!!this.mContext) {
  12035. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  12036. }
  12037. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  12038. this.mIjkMediaPlayer.reset();
  12039. }
  12040. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  12041. //设置debug模式
  12042. this.mIjkMediaPlayer.setDebug(false);
  12043. //初始化配置
  12044. this.mIjkMediaPlayer.native_setup();
  12045. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  12046. if(this.volumeSmall){
  12047. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  12048. this.mIjkMediaPlayer.setVolume('1', '1');
  12049. }else{
  12050. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  12051. }
  12052. }else{
  12053. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  12054. }
  12055. //设置视频源
  12056. this.mIjkMediaPlayer.setDataSource(url);
  12057. // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
  12058. const headers = new Map<string, string>();
  12059. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  12060. headers.set("Accept", "*/*");
  12061. if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
  12062. &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
  12063. //如果封面为空,则搜索封面
  12064. this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
  12065. }
  12066. // 如果是WebDAV网络音频,使用webdav_account_id获取认证信息(等待完成后再设置一次性头部)
  12067. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  12068. Logger.info(`heanup WebDAV歌曲认证 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
  12069. if (this.currentSong.webdav_account_id) {
  12070. try {
  12071. const webdavManager = RemoteDriveManager.getInstance();
  12072. const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  12073. if (webDavHeaders && webDavHeaders.size > 0) {
  12074. webDavHeaders.forEach((value, key) => headers.set(key, value));
  12075. Logger.info(`heanup 成功通过webdav_account_id获取并合并WebDAV认证头`);
  12076. } else {
  12077. Logger.warn(`heanup 通过webdav_account_id获取认证头失败,播放可能无法继续`);
  12078. }
  12079. } catch (error) {
  12080. const err = error as Error;
  12081. Logger.error(`heanup 获取WebDAV认证头时出错: ${err.message}`);
  12082. }
  12083. } else {
  12084. Logger.error(`heanup WebDAV歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法进行认证`);
  12085. }
  12086. }
  12087. // 统一设置带认证的请求头
  12088. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  12089. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  12090. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  12091. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  12092. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  12093. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  12094. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  12095. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  12096. // 缓冲和播放优化设置
  12097. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  12098. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  12099. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1"); // 预加载启动
  12100. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  12101. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  12102. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  12103. // 网络相关设置
  12104. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  12105. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  12106. // 重连设置
  12107. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  12108. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  12109. }
  12110. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  12111. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  12112. // }
  12113. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  12114. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  12115. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  12116. const fileSize = await this.getFileSize(this.videoUrl);
  12117. let bufferSize = 1 * 1024 ; // 默认缓冲区大小为1MB
  12118. if (fileSize > 3 * 1024 * 1024 * 1024) { // 文件大于3GB
  12119. bufferSize = 25 * 1024 * 1024; // 设置缓冲区大小为25MB
  12120. }
  12121. // 使用软件解码(通常比硬件解码更节省内存)
  12122. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", '0');
  12123. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", '0');
  12124. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", '1024');
  12125. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzeduration", '500000');
  12126. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  12127. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  12128. //停止预读的最小帧数
  12129. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  12130. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  12131. // 设置其他缓冲相关选项
  12132. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  12133. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  12134. //启动预加载
  12135. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  12136. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  12137. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  12138. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  12139. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  12140. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  12141. // 因此需要播放器丢包,才不会累积延时
  12142. // 这个和第三个参数packet-buffering无关。
  12143. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  12144. // 无限制收流
  12145. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  12146. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  12147. // 屏幕常亮
  12148. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  12149. // 设置超时
  12150. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  12151. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  12152. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  12153. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  12154. // 变速播放
  12155. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  12156. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  12157. let Speed = this.mIjkMediaPlayer.getSpeed()
  12158. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  12159. //是否开启循环播放
  12160. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  12161. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  12162. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  12163. if (height === 0) {
  12164. return;
  12165. }
  12166. const va = width / height;
  12167. const vpa = that.videoParentAspectRatio;
  12168. if (vpa > va) {
  12169. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  12170. } else {
  12171. that.videoWidth = '100%';
  12172. }
  12173. if (width && height) {
  12174. that.videoAspectRatio = width / height;
  12175. }
  12176. LogUtils.getInstance()
  12177. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  12178. that.hideLoadIng();
  12179. }
  12180. }
  12181. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  12182. let mOnPreparedListener: OnPreparedListener = {
  12183. onPrepared: async () => {
  12184. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  12185. try {
  12186. //保存碰一碰分享的当前的歌曲
  12187. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  12188. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  12189. await this.initLyric(lyricPath);
  12190. setTimeout(() => {
  12191. this.avSessionController.initAvSession(false);
  12192. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  12193. this.setAvSessionListener();
  12194. this.updateSessionPlayState(true)
  12195. this.setCurrentPlayMode()
  12196. }, 500)
  12197. if(startOffset&&startOffset>0){//cue分轨播放
  12198. this.seekTo(startOffset + "");
  12199. this.saveLastPlayList()
  12200. return
  12201. }
  12202. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12203. let timeoutPlay = 0
  12204. if (StrUtil.isNotEmpty(this.videoUrl) &&
  12205. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  12206. timeoutPlay = 1000
  12207. }
  12208. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  12209. if (this.modeType === 0) { //文件夹
  12210. let parentPath = FileUtil.getParentPath(this.videoUrl)
  12211. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  12212. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  12213. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  12214. } else if (this.modeType === 1) { //媒体库
  12215. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  12216. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  12217. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  12218. } else if (this.modeType === 2) { //艺术家
  12219. if (this.currentSong?.artist) {
  12220. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  12221. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  12222. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  12223. }
  12224. } else if (this.modeType === 3) { //专辑
  12225. if (this.currentSong?.album) {
  12226. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  12227. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  12228. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  12229. }
  12230. }
  12231. this.duration = this.mIjkMediaPlayer.getDuration()
  12232. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  12233. if (this.mIjkMediaPlayer != null) {
  12234. let jumpTopTimeMs = this.jumpTopTime*1000;
  12235. if (jumpTopTimeMs <= this.duration) {
  12236. // 调用 seekTo 方法,跳到指定时间
  12237. if(PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY,true)){
  12238. console.log('onecold jumpTopTime = '+jumpTopTimeMs);
  12239. const position:number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  12240. console.log('onecold position = '+position);
  12241. if (position > jumpTopTimeMs) {
  12242. jumpTopTimeMs = position
  12243. }
  12244. }
  12245. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12246. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  12247. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  12248. }
  12249. }, timeoutPlay)
  12250. } else {
  12251. // 提示用户无法跳过
  12252. ToastUtil.showToast('跳过时间超过视频时长');
  12253. }
  12254. }
  12255. } else {
  12256. this.jumpTopTime = 0
  12257. this.jumpEndTime = 0
  12258. console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  12259. console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  12260. console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  12261. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  12262. //记忆播放(每一首都会记忆播放)
  12263. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  12264. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12265. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  12266. this.restorePlaybackPosition() //读取播放记忆功能
  12267. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  12268. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  12269. this.restorePlaybackPosition() //读取播放记忆功能
  12270. }
  12271. this.isFirstStartPlay = false
  12272. }, timeoutPlay)
  12273. } else {
  12274. this.isFirstStartPlay = false
  12275. }
  12276. }
  12277. this.saveLastPlayList()
  12278. } catch (error) {
  12279. let err: BusinessError = error as BusinessError;
  12280. console.error('onecold failed with err: ' + JSON.stringify(err));
  12281. }
  12282. }
  12283. }
  12284. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  12285. let mOnTimedTextListener: OnTimedTextListener = {
  12286. onTimedText: () => {
  12287. }
  12288. }
  12289. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  12290. let mOnCompletionListener: OnCompletionListener = {
  12291. onCompletion: () => {
  12292. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  12293. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  12294. // 异步调用playNext
  12295. this.playNext().catch(() => {
  12296. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  12297. });
  12298. } else if (this.playType == 1) { //1:单片重复播放
  12299. this.CONTROL_PlayStatus = PlayStatus.INIT
  12300. that.startPlayOrResumePlay();
  12301. } else if (this.playType == 2) { //2:正常播放,单曲播完
  12302. that.showRePlay();
  12303. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  12304. that.progressValue = this.PROGRESS_MAX_VALUE;
  12305. that.slideEnable = false;
  12306. that.stop();
  12307. // ToastUtil.showToast('开始重新播放')
  12308. } else if (this.playType == 3) { //3:随机播放
  12309. // 异步调用randomPlay
  12310. this.randomPlay().catch(() => {
  12311. Logger.error('heanup OnCompletionListener randomPlay', `随机播放失败`);
  12312. });
  12313. }
  12314. }
  12315. }
  12316. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  12317. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  12318. onBufferingUpdate: (percent: number) => {
  12319. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  12320. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  12321. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  12322. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  12323. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  12324. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  12325. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  12326. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  12327. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  12328. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  12329. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  12330. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  12331. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  12332. let Looping = this.mIjkMediaPlayer.isLooping()
  12333. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  12334. }
  12335. }
  12336. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  12337. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  12338. onSeekComplete: () => {
  12339. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  12340. console.info('onecold startPlayOrResumePlay 10643')
  12341. that.startPlayOrResumePlay();
  12342. }
  12343. }
  12344. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  12345. let mOnInfoListener: OnInfoListener = {
  12346. onInfo: (what: number, extra: number) => {
  12347. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  12348. that.hideLoadIng();
  12349. }
  12350. }
  12351. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  12352. let mOnErrorListener: OnErrorListener = {
  12353. onError: (what: number, extra: number) => {
  12354. this.stopProgressTask();
  12355. LogUtils.getInstance().LOGI("heanup OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  12356. LogUtils.getInstance().LOGI('heanup 播放错误,歌曲详情:' + JSON.stringify(this.currentSong))
  12357. // 检查是否为WebDAV播放错误
  12358. let isWebDavError = false;
  12359. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.currentSong.filePath) {
  12360. try {
  12361. const globalContext = GlobalContext.getContext();
  12362. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  12363. if (webDavAuthInfo) {
  12364. isWebDavError = true;
  12365. }
  12366. } catch (error) {
  12367. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  12368. }
  12369. }
  12370. if (isWebDavError) {
  12371. Logger.error(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  12372. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  12373. // this.currentWebDavAuthInfo = null;
  12374. Logger.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  12375. // 根据错误代码提供更具体的错误信息
  12376. let errorMessage = "WebDAV播放失败";
  12377. if (what === -1) { // 网络错误
  12378. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  12379. } else if (what === -1004) { // HTTP 404
  12380. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  12381. } else if (what === -1001) { // 超时
  12382. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  12383. } else if (what === -1003) { // 无法解析主机
  12384. errorMessage = "无法连接到WebDAV服务器";
  12385. }
  12386. ToastUtil.showToast(errorMessage);
  12387. } else {
  12388. if (StrUtil.isNotEmpty(this.videoUrl) &&
  12389. !this.videoUrl.startsWith('http://') &&
  12390. !this.videoUrl.startsWith('https://') &&
  12391. !FileUtil.accessSync(this.videoUrl)) {
  12392. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  12393. } else {
  12394. ToastUtil.showToast(getContext()
  12395. .resourceManager
  12396. .getStringByNameSync("Honey_the_video_is_playing_errant_The_system_is_wandering"))
  12397. }
  12398. }
  12399. that.hideLoadIng();
  12400. }
  12401. }
  12402. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  12403. this.mIjkMediaPlayer.setMessageListener();
  12404. this.mIjkMediaPlayer.prepareAsync();
  12405. this.mIjkMediaPlayer.start();
  12406. }
  12407. //保存最后播放的那首歌和已经对应的播放列表
  12408. saveLastPlayList() {
  12409. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  12410. PreferencesUtil.putSync('LastMusicList', this.songList)
  12411. }
  12412. // 清空播放记录
  12413. clearVideoHistory() {
  12414. this.table.clearPlayHistory((success: boolean, error?: string) => {
  12415. if (success) {
  12416. this.historyList = [];
  12417. this.updateListData(this.historyList)
  12418. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  12419. ToastUtil.showToast('清空播放记录成功')
  12420. } else {
  12421. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  12422. }
  12423. });
  12424. }
  12425. public async setAvSessionListener() {
  12426. if (!this.avSessionController) {
  12427. return;
  12428. }
  12429. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  12430. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  12431. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  12432. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  12433. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  12434. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  12435. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  12436. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  12437. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  12438. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  12439. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  12440. }
  12441. setLoopMode() {
  12442. let itype = this.playType + 1
  12443. if (itype >= 4) {
  12444. this.playType = 0
  12445. ToastUtil.showToast('连续播放')
  12446. } else if (itype === 1) {
  12447. this.playType = 1
  12448. ToastUtil.showToast('单曲循环')
  12449. } else if (itype === 2) {
  12450. this.playType = 2
  12451. ToastUtil.showToast('单曲播完')
  12452. } else if (itype === 3) {
  12453. this.playType = 3
  12454. ToastUtil.showToast('随机播放')
  12455. } else if (itype === 0) {
  12456. this.playType = 0
  12457. ToastUtil.showToast('连续播放')
  12458. }
  12459. PreferencesUtil.putSync('musicPlayType', this.playType)
  12460. this.setCurrentPlayMode()
  12461. }
  12462. private sessionSetLoopModeCallback = (mode: number) => {
  12463. if (this.mIjkMediaPlayer != null) {
  12464. ToastUtil.showToast('当前播放模式:' + mode)
  12465. Logger.info('onecold 当前播放模式= ' + mode)
  12466. let hmPlayMode = mode + 1
  12467. if (hmPlayMode >= 4) {
  12468. hmPlayMode = 0
  12469. }
  12470. if (hmPlayMode === 1) {
  12471. this.playType = 1
  12472. ToastUtil.showToast('单曲循环')
  12473. } else if (hmPlayMode === 0) {
  12474. this.playType = 2
  12475. ToastUtil.showToast('单曲播完')
  12476. } else if (hmPlayMode === 3) {
  12477. this.playType = 3
  12478. ToastUtil.showToast('随机播放')
  12479. } else if (hmPlayMode === 2) {
  12480. this.playType = 0
  12481. ToastUtil.showToast('连续播放')
  12482. }
  12483. PreferencesUtil.putSync('musicPlayType', this.playType)
  12484. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  12485. let playBackState: avSession.AVPlaybackState = {
  12486. loopMode: hmPlayMode,
  12487. };
  12488. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  12489. console.info(`set setLoopMode AVPlaybackState successfully`);
  12490. }).catch((err: BusinessError) => {
  12491. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  12492. });
  12493. }
  12494. }
  12495. setCurrentPlayMode() {
  12496. if (!this.avSessionController) {
  12497. return;
  12498. }
  12499. let mLoopMode = 0
  12500. switch (this.playType) {
  12501. case 0:
  12502. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  12503. break;
  12504. case 1:
  12505. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  12506. break;
  12507. case 2:
  12508. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  12509. break;
  12510. case 3:
  12511. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  12512. break;
  12513. }
  12514. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  12515. let playBState: avSession.AVPlaybackState = {
  12516. loopMode: mLoopMode,
  12517. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  12518. };
  12519. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  12520. console.info(`set setLoopMode AVPlaybackState successfully`);
  12521. }).catch((err: BusinessError) => {
  12522. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  12523. });
  12524. }
  12525. private sessionToggleFavoriteCallback = (assetId: string) => {
  12526. if (this.mIjkMediaPlayer != null && this.currentSong) {
  12527. console.info(`on toggleFavorite `);
  12528. // 应用收到收藏命令,进行收藏处理。
  12529. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  12530. this.doFav(this.currentSong)
  12531. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  12532. let playbackState: avSession.AVPlaybackState = {
  12533. isFavorite: !this.isFac,
  12534. };
  12535. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  12536. console.info(`SetAVPlaybackState successfully`);
  12537. }).catch((err: BusinessError) => {
  12538. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  12539. });
  12540. }
  12541. }
  12542. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  12543. device: avSession.OutputDeviceInfo) => {
  12544. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  12545. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  12546. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  12547. await this.startCasting();
  12548. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  12549. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  12550. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  12551. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  12552. if (device) {
  12553. this.endCasting();
  12554. }
  12555. }
  12556. };
  12557. private async startCasting() {
  12558. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  12559. this.setPlaybackStateChangeListener();
  12560. this.pause();
  12561. this.initQueueItem();
  12562. this.prepare();
  12563. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  12564. refToIsCasting?.set(true);
  12565. this.castSeek = true;
  12566. this.isCastPlaying = true;
  12567. }
  12568. async changeCasting() {
  12569. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  12570. this.initQueueItem();
  12571. this.prepare();
  12572. this.setPlaybackStateChangeListener();
  12573. this.isCastPlaying = true;
  12574. this.castSeek = true;
  12575. }
  12576. public endCasting() {
  12577. this.avSessionController.getAvSession()?.stopCasting();
  12578. this.stopCast();
  12579. this.isCastPlaying = false;
  12580. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  12581. refToIsCasting?.set(false);
  12582. this.pause();
  12583. this.setIsPlaying(false);
  12584. // if (this.curIndex === this.curSource.index) {
  12585. // this.play
  12586. // this.seek(this.currentTime * 1000);
  12587. // this.setIsPlaying(true);
  12588. // } else {
  12589. // this.pauseVideo();
  12590. // this.setIsPlaying(false);
  12591. // }
  12592. }
  12593. public setIsPlaying(isPlayer: boolean) {
  12594. this.isPlaying = isPlayer;
  12595. // 发送播放状态变化事件给歌单详情页面
  12596. try {
  12597. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  12598. const currentFilePath = this.currentSong?.filePath || ''
  12599. const eventData: emitter.EventData = {
  12600. data: {
  12601. isPlaying: this.isPlaying,
  12602. curIndex: this.curIndex,
  12603. currentFilePath: currentFilePath
  12604. }
  12605. };
  12606. emitter.emit(eventPlaybackStatus, eventData)
  12607. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  12608. } catch (error) {
  12609. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  12610. }
  12611. }
  12612. private setPlaybackStateChangeListener(): void {
  12613. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  12614. this.castController?.on('endOfStream', this.reloadCasting);
  12615. this.castController?.on('playNext', this.playNextCallback);
  12616. this.castController?.on('playPrevious', this.playPreviousCallback);
  12617. }
  12618. private updateSessionPlayState(isPlay: boolean): void {
  12619. // if(!this.isBgPlayOpen)
  12620. // return
  12621. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  12622. this.setAVSessionPlayState({
  12623. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  12624. position: {
  12625. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  12626. updateTime: new Date().getTime()
  12627. }
  12628. });
  12629. }
  12630. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  12631. this.avSessionController.setAvSessionPlayState(playbackState)
  12632. }
  12633. private positionChange(position: number) {
  12634. this.currentTime2 = position / 1000;
  12635. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  12636. }
  12637. private playDurationChange(duration: number) {
  12638. this.duration = duration;
  12639. this.durationTime = Math.floor(this.duration / 1000);
  12640. this.durationStringTime = secondToTime((this.durationTime));
  12641. }
  12642. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  12643. const duration = playbackState?.extras?.duration;
  12644. if (typeof duration === 'number') {
  12645. this.playDurationChange(duration as number);
  12646. }
  12647. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  12648. this.positionChange(playbackState?.position?.elapsedTime);
  12649. }
  12650. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  12651. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  12652. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  12653. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  12654. this.isCastPlaying = false;
  12655. }
  12656. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  12657. this.isCastPlaying = true;
  12658. }
  12659. };
  12660. private reloadCasting = async () => {
  12661. let item = this.songList[this.curIndex];
  12662. let uri = fileUri.getUriFromPath(item.filePath);
  12663. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  12664. // description.startPosition = 0;
  12665. this.castItem = {
  12666. itemId: this.curIndex,
  12667. description: {
  12668. assetId: item.filePath,
  12669. title: item.name,
  12670. artist: '',
  12671. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  12672. // mediaUri: item.filePath,
  12673. fdSrc: {
  12674. fd: file.fd
  12675. },
  12676. // 该字段大写,音频'AUDIO',视频'VIDEO'
  12677. mediaType: 'VIDEO',
  12678. mediaSize: item.videoSize,
  12679. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  12680. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  12681. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  12682. duration: this.duration,
  12683. // albumCoverUri: 'https://www.example.jpeg',
  12684. // albumTitle: '《ExampleAlbum》',
  12685. appName: this.appName,
  12686. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  12687. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  12688. }
  12689. };
  12690. this.prepare();
  12691. this.isCastPlaying = true;
  12692. };
  12693. public playNextCallback = (): void => {
  12694. this.playNext().catch(() => {
  12695. Logger.error('heanup playNextCallback', `播放下一首失败`);
  12696. });
  12697. };
  12698. public playPreviousCallback = (): void => {
  12699. this.playPrevious().catch(() => {
  12700. Logger.error('heanup playNextCallback', `播放上一首失败`);
  12701. });
  12702. };
  12703. async prepare() {
  12704. await this.castController?.prepare(this.castItem);
  12705. await this.castController?.start(this.castItem);
  12706. }
  12707. public initQueueItem() {
  12708. let item = this.songList[this.curIndex];
  12709. let time = this.currentTime;
  12710. let uri = fileUri.getUriFromPath(item.filePath);
  12711. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  12712. this.castItem = {
  12713. itemId: this.curIndex,
  12714. description: {
  12715. assetId: item.filePath,
  12716. title: item.name,
  12717. artist: '',
  12718. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  12719. fdSrc: {
  12720. fd: file.fd
  12721. },
  12722. // 该字段大写,音频'AUDIO',视频'VIDEO'
  12723. mediaType: 'AUDIO',
  12724. mediaSize: item.videoSize,
  12725. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  12726. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  12727. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  12728. duration: this.duration,
  12729. // albumCoverUri: 'https://www.example.jpeg',
  12730. // albumTitle: '《ExampleAlbum》',
  12731. appName: this.appName,
  12732. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  12733. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  12734. }
  12735. };
  12736. }
  12737. async stopCast() {
  12738. try {
  12739. this.castController?.off('playbackStateChange');
  12740. this.castController?.off('endOfStream');
  12741. this.castController?.off('playNext');
  12742. this.castController?.off('playPrevious');
  12743. this.castController?.off('error');
  12744. } catch (error) {
  12745. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  12746. }
  12747. }
  12748. private sessionPlayCallback = (): void => {
  12749. this.playOrPause()
  12750. };
  12751. private sessionPauseCallback = (): void => {
  12752. this.pause()
  12753. };
  12754. private playOrPause() {
  12755. if (!this.debounce()) {
  12756. return;
  12757. }
  12758. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  12759. this.pause();
  12760. } else {
  12761. console.info('onecold startPlayOrResumePlay 11064')
  12762. this.startPlayOrResumePlay();
  12763. this.playChange()
  12764. }
  12765. }
  12766. private sessionPlayNextCallback = (): void => {
  12767. this.playNext().catch(() => {
  12768. Logger.error('heanup sessionPlayPreviousCallback', `播放下 一首失败`);
  12769. });
  12770. };
  12771. private sessionPlayPreviousCallback = (): void => {
  12772. this.playPrevious().catch(() => {
  12773. Logger.error('heanup sessionPlayPreviousCallback', `播放上一首失败`);
  12774. });
  12775. };
  12776. private sessionStopCallback = (): void => {
  12777. this.stop()
  12778. };
  12779. private sessionFastForwardCallback = (time?: number) => {
  12780. if (!time) {
  12781. return;
  12782. }
  12783. if (this.mIjkMediaPlayer != null) {
  12784. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12785. let seeTime = curPosition + time * 1000;
  12786. // 限制 seekValue 在合法范围内
  12787. if (seeTime < 0) {
  12788. seeTime = 0;
  12789. } else if (seeTime > this.duration) {
  12790. seeTime = this.duration;
  12791. }
  12792. Logger.info('onecold seeTime= ' + seeTime)
  12793. this.setSeekToActionProgress(seeTime)
  12794. this.seekTo(seeTime + "")
  12795. }
  12796. };
  12797. /**
  12798. * Gesture method onActionUpdate.
  12799. *
  12800. * @param event Gesture event.手势拖动设置快进和后退
  12801. */
  12802. private setSeekToActionProgress(position: number) {
  12803. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  12804. let duration = this.mIjkMediaPlayer.getDuration();
  12805. let pos = 0;
  12806. if (duration > 0) {
  12807. this.slideEnable = true;
  12808. let curPercent = position / duration;
  12809. pos = curPercent * 100;
  12810. if (pos > this.PROGRESS_MAX_VALUE) {
  12811. this.progressValue = this.PROGRESS_MAX_VALUE
  12812. } else {
  12813. this.progressValue = pos;
  12814. }
  12815. }
  12816. // LogUtils.getInstance()
  12817. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  12818. this.totalTime = this.stringForTime(duration);
  12819. if (position > duration) {
  12820. position = duration;
  12821. }
  12822. this.isCurrentTime = true;
  12823. this.currentTime = this.stringForTime(position);
  12824. this.isCurrentTime = false
  12825. }
  12826. private sessionRewindCallback = (time?: number) => {
  12827. if (!time) {
  12828. return;
  12829. }
  12830. if (this.mIjkMediaPlayer != null) {
  12831. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12832. let seeTime = curPosition - time * 1000;
  12833. // 限制 seekValue 在合法范围内
  12834. if (seeTime < 0) {
  12835. seeTime = 0;
  12836. } else if (seeTime > this.duration) {
  12837. seeTime = this.duration;
  12838. }
  12839. Logger.info('onecold seeTime= ' + seeTime)
  12840. this.setSeekToActionProgress(seeTime)
  12841. this.seekTo(seeTime + "")
  12842. }
  12843. };
  12844. private sessionSeekCallback = (seekTime: number) => {
  12845. if (this.mIjkMediaPlayer != null) {
  12846. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12847. this.seekTo(seekTime + "")
  12848. }
  12849. };
  12850. private async getFileSize(filePath: string): Promise<number> {
  12851. try {
  12852. const stat = await fs.stat(filePath);
  12853. return stat.size;
  12854. } catch (err) {
  12855. console.error('Failed to get file size: ' + err.message);
  12856. return 0;
  12857. }
  12858. }
  12859. private pause() {
  12860. if (this.mIjkMediaPlayer.isPlaying()) {
  12861. this.savePlaybackPosition();
  12862. this.mIjkMediaPlayer.pause();
  12863. this.setProgress();
  12864. this.mDestroyPage = true;
  12865. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  12866. this.updateSessionPlayState(false)
  12867. this.playChange()
  12868. if (this.pipController) {
  12869. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  12870. PiPWindow.PiPControlStatus.PAUSE);
  12871. }
  12872. }
  12873. }
  12874. private stop() {
  12875. this.savePlaybackPosition();
  12876. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12877. this.mIjkMediaPlayer.stop();
  12878. this.mIjkMediaPlayer.release();
  12879. this.stopProgressTask();
  12880. this.updateSessionPlayState(false)
  12881. this.playChange()
  12882. this.watchStatus();
  12883. }
  12884. //保持记忆播放功能
  12885. private savePlaybackPosition() {
  12886. if (this.mIjkMediaPlayer != null) {
  12887. const position = this.mIjkMediaPlayer.getCurrentPosition();
  12888. // ToastUtil.showToast('保存记忆播放 = ' + position)
  12889. const duration = this.mIjkMediaPlayer.getDuration();
  12890. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  12891. // 如果播放位置接近视频末尾,则保存 position 为 0
  12892. const playbackPosition = (duration - position < threshold) ? 0 : position;
  12893. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  12894. }
  12895. }
  12896. //获取记忆播放功能
  12897. private restorePlaybackPosition() {
  12898. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  12899. // ToastUtil.showToast('position = ' + position)
  12900. if (this.mIjkMediaPlayer != null && position > 0) {
  12901. // ToastUtil.showToast('seekTo = ' + position)
  12902. this.seekTo(position + "");
  12903. }
  12904. }
  12905. private seekTo(value: string) {
  12906. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  12907. ToastUtil.showToast('wma格式不支持拖动快进。')
  12908. return
  12909. }
  12910. this.isSeekTo = true
  12911. this.mIjkMediaPlayer.seekTo(value);
  12912. console.info('onecold startPlayOrResumePlay 11227')
  12913. // this.startPlayOrResumePlay()
  12914. // 在这里恢复计时器状态
  12915. this.setProgress()
  12916. this.isSeekTo = false
  12917. }
  12918. // 添加到下一首播放
  12919. private addToNextPlay(song: VideoItem) {
  12920. if (!this.debounce()) {
  12921. return;
  12922. }
  12923. if (this.currentSong) {
  12924. if (this.currentSong === song) {
  12925. ToastUtil.showToast('当前已经在播放这首歌了!')
  12926. return
  12927. }
  12928. }
  12929. // 如果未开始播放或队列为空
  12930. if (this.curIndex === -1 || this.songList.length === 0) {
  12931. this.songList = [song];
  12932. this.curIndex = 0;
  12933. this.doPlay(song)
  12934. return;
  12935. }
  12936. // 插入到当前索引+1的位置
  12937. const insertPos = this.curIndex + 1;
  12938. this.songList.splice(insertPos, 0, song);
  12939. this.songList = [...this.songList]; // 触发状态更新
  12940. this.sonDataSource.pushArrayData(this.songList)
  12941. ToastUtil.showToast('已添加至下一首播放')
  12942. }
  12943. //后退10s,可再设置设置默认几秒
  12944. backForward() {
  12945. if(this.mIjkMediaPlayer){
  12946. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  12947. let value = pos - Number(this.fastForwardSeconds) * 1000;
  12948. this.seekTo(value+"");
  12949. }
  12950. }
  12951. //快进10s,可再设置设置默认几秒
  12952. fastForward() {
  12953. if(this.mIjkMediaPlayer){
  12954. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  12955. let value = pos + Number(this.fastForwardSeconds) * 1000;
  12956. this.seekTo(value+"");
  12957. }
  12958. }
  12959. //下一个
  12960. private async playNext() {
  12961. if (!this.debounce()) {
  12962. return;
  12963. }
  12964. if (this.playType == 3) { //3:随机播放
  12965. await this.randomPlay()
  12966. return;
  12967. }
  12968. if (ArrayUtil.isNotEmpty(this.songList)) {
  12969. if (this.curIndex == this.songList.length - 1) {
  12970. this.curIndex = 0;
  12971. } else {
  12972. this.curIndex++;
  12973. }
  12974. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12975. this.stop();
  12976. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  12977. this.currentSong = this.songList[this.curIndex];
  12978. Logger.info('heanup playNext', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  12979. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12980. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  12981. context: this.context,
  12982. autoParseMusicName: this.autoParseMusicName
  12983. });
  12984. this.artist = this.songList[this.curIndex].artist
  12985. this.name = this.songList[this.curIndex].name
  12986. //this.cover = this.songList[this.curIndex].pixelMapPath
  12987. this.changeImageAnimation()
  12988. }
  12989. }
  12990. changeImageAnimation() {
  12991. if(this.openSkipSongAnimate){
  12992. // 第一步:淡出动画
  12993. this.getUIContext()?.animateTo({
  12994. duration: 500,
  12995. curve: Curve.EaseOut,
  12996. }, () => {
  12997. this.opacityValueImage = 0.1;
  12998. if(this.isCoverRectangle){
  12999. this.scaleValueImage = 0.88
  13000. }
  13001. });
  13002. // 第二步:切换图片后淡入
  13003. setTimeout(() => {
  13004. this.cover = this.songList[this.curIndex].pixelMapPath
  13005. this.getUIContext()?.animateTo({
  13006. duration: 500,
  13007. curve: Curve.EaseIn,
  13008. }, () => {
  13009. this.opacityValueImage = 1;
  13010. this.scaleValueImage = 1 // 图标恢复到原始大小
  13011. this.startPlayOrResumePlay()
  13012. });
  13013. }, 500);
  13014. }else{
  13015. this.cover = this.songList[this.curIndex].pixelMapPath
  13016. this.startPlayOrResumePlay()
  13017. }
  13018. }
  13019. // 存储已播放的歌曲索引
  13020. private playedIndices: Set<number> = new Set();
  13021. //随机播放
  13022. private async randomPlay() {
  13023. // if (!this.debounce()) {
  13024. // return;
  13025. // }
  13026. if (ArrayUtil.isNotEmpty(this.songList)) {
  13027. if (this.songList.length > 3) {
  13028. // 如果所有歌曲都播放过一次,清空已播放索引集合
  13029. if (this.playedIndices.size === this.songList.length) {
  13030. this.playedIndices.clear();
  13031. }
  13032. // 随机选择一个未播放的歌曲索引
  13033. let newIndex: number;
  13034. // 添加超时机制防止无限循环
  13035. let attempt = 0;
  13036. const maxAttempts = 100; // 根据需求调整
  13037. do {
  13038. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  13039. attempt++;
  13040. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  13041. if (attempt >= maxAttempts) {
  13042. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  13043. newIndex = Math.floor(Math.random() * this.songList.length);
  13044. }
  13045. this.curIndex = newIndex;
  13046. this.playedIndices.add(newIndex);
  13047. } else {
  13048. // 当歌曲数量小于或等于3时,直接播放下一首
  13049. if (this.curIndex == this.songList.length - 1) {
  13050. this.curIndex = 0;
  13051. } else {
  13052. this.curIndex++;
  13053. }
  13054. }
  13055. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13056. this.stop();
  13057. this.currentSong = this.songList[this.curIndex];
  13058. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13059. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13060. context: this.context,
  13061. autoParseMusicName: this.autoParseMusicName
  13062. });
  13063. this.name = this.songList[this.curIndex].name;
  13064. this.artist = this.songList[this.curIndex].artist
  13065. // this.cover = this.songList[this.curIndex].pixelMapPath
  13066. this.changeImageAnimation()
  13067. }
  13068. }
  13069. private async playIndex(index: number) {
  13070. if (!this.debounce()) {
  13071. return;
  13072. }
  13073. if (ArrayUtil.isNotEmpty(this.songList)) {
  13074. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13075. this.stop();
  13076. this.curIndex = index;
  13077. this.currentSong = this.songList[index];
  13078. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13079. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13080. context: this.context,
  13081. autoParseMusicName: this.autoParseMusicName
  13082. });
  13083. this.name = this.currentSong.name
  13084. this.artist = this.currentSong.artist
  13085. this.changeImageAnimation()
  13086. }
  13087. }
  13088. //上一个
  13089. private async playPrevious() {
  13090. if (!this.debounce()) {
  13091. return;
  13092. }
  13093. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  13094. this.randomModePlayFromHistory()
  13095. return;
  13096. }
  13097. if (this.curIndex == 0) {
  13098. this.curIndex = this.songList.length - 1;
  13099. } else {
  13100. this.curIndex--;
  13101. }
  13102. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13103. this.stop();
  13104. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  13105. this.currentSong = this.songList[this.curIndex];
  13106. Logger.info('heanup playPrevious', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  13107. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13108. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13109. context: this.context,
  13110. autoParseMusicName: this.autoParseMusicName
  13111. });
  13112. this.name = this.songList[this.curIndex].name
  13113. this.artist = this.songList[this.curIndex].artist
  13114. this.changeImageAnimation()
  13115. }
  13116. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  13117. private async randomModePlayFromHistory() {
  13118. if (this.historyList.length >= 2) {
  13119. // 播放历史记录的第二首
  13120. const prevSong = this.historyList[1];
  13121. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  13122. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13123. this.stop();
  13124. // 直接使用历史记录中的歌曲信息,历史记录中的数据应该是完整的
  13125. this.currentSong = prevSong;
  13126. Logger.info('heanup randomModePlayFromHistory', `直接使用历史歌曲信息: ${prevSong.name}, type: ${prevSong.type}`);
  13127. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13128. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13129. context: this.context,
  13130. autoParseMusicName: this.autoParseMusicName
  13131. });
  13132. this.cover = prevSong.pixelMapPath
  13133. this.artist = prevSong.artist
  13134. this.name = prevSong.name;
  13135. console.info('onecold startPlayOrResumePlay 11434')
  13136. this.startPlayOrResumePlay();
  13137. } else {
  13138. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  13139. if (this.curIndex === 0) {
  13140. this.curIndex = this.songList.length - 1;
  13141. } else {
  13142. this.curIndex--;
  13143. }
  13144. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13145. this.stop();
  13146. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  13147. this.currentSong = this.songList[this.curIndex];
  13148. Logger.info('heanup randomModePlayFromHistory', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  13149. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13150. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13151. context: this.context,
  13152. autoParseMusicName: this.autoParseMusicName
  13153. });
  13154. this.artist = this.songList[this.curIndex].artist
  13155. this.name = this.songList[this.curIndex].name;
  13156. this.changeImageAnimation()
  13157. }
  13158. }
  13159. debounce() {
  13160. const delay = 600;
  13161. let cur = new Date().getTime();
  13162. if (cur - this.last > delay) {
  13163. this.last = cur;
  13164. return true;
  13165. }
  13166. return false;
  13167. }
  13168. /**
  13169. * Sets whether the screen is a constant based on the playback status.
  13170. */
  13171. watchStatus() {
  13172. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  13173. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  13174. this.windowClass.setWindowKeepScreenOn(true);
  13175. } else {
  13176. this.windowClass.setWindowKeepScreenOn(false);
  13177. }
  13178. }
  13179. /**
  13180. * Volume gesture method onActionStart.
  13181. *
  13182. * @param event Gesture event.
  13183. */
  13184. private customDialogComponentIdMM: number = 0
  13185. @Builder
  13186. customDialogComponentMM() {
  13187. Column() {
  13188. Row() {
  13189. Blank()
  13190. Text('验证密码')
  13191. .fontSize(22)
  13192. .fontColor($r('app.color.pri_bg'))
  13193. .margin({ top: 18 })
  13194. Blank()
  13195. Image($r('app.media.close'))
  13196. .fillColor(Color.White)
  13197. .margin({ top: 18, right: 18 })
  13198. .width(20)
  13199. .onClick(() => {
  13200. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  13201. })
  13202. }
  13203. .width('100%') // 使Row占据整个宽度
  13204. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  13205. Verify({
  13206. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  13207. });
  13208. }.height('60%')
  13209. .backgroundColor($r('app.color.index_background'))
  13210. .justifyContent(FlexAlign.SpaceBetween)
  13211. }
  13212. private handleVerifyCompleted(isSuccess: boolean) {
  13213. if (isSuccess) {
  13214. console.log('验证成功');
  13215. // 在这里处理验证成功后的逻辑
  13216. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  13217. this.currentPath = this.lockPath
  13218. this.getSortedFiles(this.currentPath)
  13219. } else {
  13220. // console.log('验证失败');
  13221. ToastUtil.showToast('验证失败')
  13222. }
  13223. }
  13224. private showVerifyDialog() {
  13225. promptAction.openCustomDialog({
  13226. transition: TransitionEffect.asymmetric(
  13227. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  13228. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  13229. ,
  13230. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  13231. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  13232. ),
  13233. builder: () => {
  13234. this.customDialogComponentMM()
  13235. },
  13236. isModal: true,
  13237. autoCancel: true,
  13238. maskColor: Color.Transparent,
  13239. alignment: DialogAlignment.Bottom,
  13240. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  13241. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  13242. console.log("dialog onWillDismiss")
  13243. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  13244. dismissDialogAction.dismiss()
  13245. }
  13246. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  13247. dismissDialogAction.dismiss()
  13248. }
  13249. }
  13250. }).then((dialogId: number) => {
  13251. this.customDialogComponentIdMM = dialogId
  13252. })
  13253. }
  13254. //左滑操作 移动文件 重命名 删除等操作
  13255. @Builder
  13256. DeleteButton(item: VideoItem, index: number, filePath: string) {
  13257. Row() {
  13258. //加入收藏
  13259. Button() {
  13260. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  13261. .fillColor(Color.White)
  13262. .width(20)
  13263. }
  13264. .width(40)
  13265. .height(40)
  13266. .type(ButtonType.Circle)
  13267. .backgroundColor(this.themeColor)
  13268. .margin(5)
  13269. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13270. .onClick(() => {
  13271. if (item) {
  13272. this.doFav(item)
  13273. }
  13274. })
  13275. //加入下一首播放
  13276. Button() {
  13277. Image($r('app.media.next_to_play'))
  13278. .fillColor(Color.White)
  13279. .width(20)
  13280. }
  13281. .width(40)
  13282. .height(40)
  13283. .type(ButtonType.Circle)
  13284. .backgroundColor(this.themeColor)
  13285. .margin(5)
  13286. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13287. .onClick(() => {
  13288. this.addToNextPlay(item);
  13289. })
  13290. //复制文件
  13291. Button() {
  13292. Image($r('app.media.copy'))
  13293. .fillColor(Color.White)
  13294. .width(20)
  13295. }
  13296. .width(40)
  13297. .height(40)
  13298. .type(ButtonType.Circle)
  13299. .backgroundColor(this.themeColor)
  13300. .margin(5)
  13301. .id(filePath + 'copy')
  13302. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13303. .onClick(() => {
  13304. this.showCopyDialog(false, item, index, filePath + 'copy');
  13305. })
  13306. //移动文件
  13307. Button() {
  13308. Image($r('app.media.cut'))
  13309. .fillColor(Color.White)
  13310. .width(20)
  13311. }
  13312. .width(40)
  13313. .height(40)
  13314. .type(ButtonType.Circle)
  13315. .backgroundColor(this.themeColor)
  13316. .margin(5)
  13317. .id(filePath)
  13318. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13319. .onClick(() => {
  13320. this.showCutDialog(false, item, index, filePath);
  13321. })
  13322. Button() {
  13323. Image($r('app.media.cut_current'))
  13324. .fillColor(Color.White)
  13325. .width(20)
  13326. }
  13327. .width(40)
  13328. .height(40)
  13329. .type(ButtonType.Circle)
  13330. .backgroundColor(this.themeColor)
  13331. .margin(5)
  13332. .id(filePath + 'current')
  13333. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  13334. (this.isHasDir ? Visibility.Visible : Visibility.None))
  13335. .onClick(() => {
  13336. this.showCutDialog(true, item, index, filePath + 'current');
  13337. })
  13338. //重命名
  13339. Button() {
  13340. Image($r('app.media.rename2'))
  13341. .fillColor(Color.White)
  13342. .width(20)
  13343. }
  13344. .width(40)
  13345. .height(40)
  13346. .type(ButtonType.Circle)
  13347. .backgroundColor(this.themeColor)
  13348. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  13349. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  13350. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  13351. .margin(5)
  13352. .onClick(() => {
  13353. this.showReNameDialog(item, index + '', filePath)
  13354. })
  13355. Button() {
  13356. Image($r('app.media.delete2'))
  13357. .fillColor(Color.White)
  13358. .width(20)
  13359. }
  13360. .width(40)
  13361. .height(40)
  13362. .type(ButtonType.Circle)
  13363. .backgroundColor(this.themeColor)
  13364. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  13365. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  13366. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  13367. .margin(5)
  13368. .onClick(() => {
  13369. this.selectedFiles.push(item)
  13370. this.showWarnIsDelete()
  13371. // this.showWarnIsDeleteFile(item, index + '', filePath)
  13372. })
  13373. Button() {
  13374. Image($r('app.media.share2'))
  13375. .fillColor(Color.White)
  13376. .width(20)
  13377. }
  13378. .width(40)
  13379. .height(40)
  13380. .type(ButtonType.Circle)
  13381. .backgroundColor(this.themeColor)
  13382. .margin(5)
  13383. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13384. .onClick(() => {
  13385. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  13386. })
  13387. }
  13388. }
  13389. /**
  13390. * 穿山甲banner广告
  13391. */
  13392. // private declare bannerAd: CSJNativeExpressAd;
  13393. // @State private status: string = "未加载"
  13394. // @State private isShowAd: boolean = false
  13395. // private declare mAdSlot: AdSlot;
  13396. // private mBiddingAdm = '' //服务端bidding才需要设置
  13397. // private expressLoadAdListener: NativeExpressAdListener = {
  13398. // /**
  13399. // * 加载失败的回调
  13400. // *
  13401. // * @param code
  13402. // * @param message
  13403. // */
  13404. // onError: (code: number, message: string) => {
  13405. // console.error("加载广告失败,code=" + code + ",message=" + message);
  13406. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  13407. // },
  13408. //
  13409. // /**
  13410. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  13411. // *
  13412. // * @param ads 返回的广告列表
  13413. // */
  13414. //
  13415. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  13416. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  13417. // if (ads && ads.length > 0) {
  13418. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  13419. // ad.setExpressInteractionListener({
  13420. // /**
  13421. // *广告的点击回调
  13422. // * @param type 广告的交互类型
  13423. // */
  13424. // onAdClicked: (type: number) => {
  13425. // console.log("BannerExpressAdPage==onAdClicked......");
  13426. // },
  13427. //
  13428. // /**
  13429. // * 广告的展示回调 每个广告仅回调一次
  13430. // * @param type 广告的交互类型
  13431. // */
  13432. // onAdShow: (type: number) => {
  13433. // console.log("BannerExpressAdPage==onAdShow......");
  13434. // },
  13435. //
  13436. // /**
  13437. // * 模板渲染失败
  13438. // */
  13439. // onRenderFail: (code: number, msg: string) => {
  13440. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  13441. // },
  13442. //
  13443. // /**
  13444. // * 模板渲染成功
  13445. // * @param width 返回view的宽 单位 vp
  13446. // * @param height 返回view的高 单位 vp
  13447. // */
  13448. // onRenderSuccess: (width: number, height: number) => {
  13449. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  13450. // this.bannerAd = ad;
  13451. // this.status = "广告加载完成待展示";
  13452. //
  13453. // this.showBannerAd()
  13454. // }
  13455. // })
  13456. // //渲染广告
  13457. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  13458. // this.setDislikeCallback(ad); //设置dislike
  13459. // ad.render(this.getUIContext())
  13460. // this.status = "广告加载中...";
  13461. // });
  13462. // }
  13463. // }
  13464. // }
  13465. //
  13466. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  13467. // ad.setDislikeCallback({
  13468. // /**
  13469. // * dislike show
  13470. // */
  13471. // onShow: () => {
  13472. // console.log("BannerExpressAdPage==dislike......show");
  13473. // },
  13474. //
  13475. // /**
  13476. // * @param position 选择的位置
  13477. // * @param value 选择的内容
  13478. // * @param enforceRemove 是否强制关闭广告
  13479. // */
  13480. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  13481. // this.isShowAd = false;
  13482. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  13483. // ",enforce=" + enforceRemove);
  13484. // },
  13485. //
  13486. // /**
  13487. // * 点击取消
  13488. // */
  13489. // onCancel: () => {
  13490. // console.log("BannerExpressAdPage==dislike......onCancel");
  13491. // }
  13492. //
  13493. // })
  13494. // }
  13495. /**
  13496. * 加载Banner广告
  13497. */
  13498. loadBannerAd(rit: string) {
  13499. // if (Utility.isNoble()) {
  13500. // return
  13501. // }
  13502. // if (!Utility.isPassInstallTime(2)) {
  13503. // return
  13504. // }
  13505. // this.isShowAd = false;
  13506. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  13507. // this.mAdSlot = new AdSlotBuilder()
  13508. // .setCodeId(rit)
  13509. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  13510. // .setAdCount(1)
  13511. // .setBidAdm(this.mBiddingAdm)
  13512. // .build()
  13513. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  13514. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  13515. // this.status = "广告加载中..."
  13516. }
  13517. /**
  13518. * 展示Banner广告
  13519. */
  13520. // showBannerAd() {
  13521. // if (!this.bannerAd) {
  13522. // return
  13523. // }
  13524. // this.isShowAd = true
  13525. // this.status = "已展示"
  13526. // }
  13527. /**
  13528. * 穿山甲广告代码结束
  13529. */
  13530. /**
  13531. * 处理歌单播放请求
  13532. */
  13533. private async handlePlaylistPlayRequest(playlistId: string, playlistName:
  13534. string, songFilePaths: string[], startIndex: number) {
  13535. try {
  13536. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 歌曲数量: ${songFilePaths.length}, 开始索引: ${startIndex}`)
  13537. // 检查是否为WebDAV播放请求
  13538. if (playlistId === 'webdav-playlist') {
  13539. Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
  13540. // 从全局内存读取videoItems数据
  13541. const videoItems = getWebdavVideoItems();
  13542. const currentPlayIndex = getWebdavCurrentPlayIndex();
  13543. Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
  13544. if (videoItems && videoItems.length > 0) {
  13545. // 验证webdav_account_id设置情况
  13546. const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
  13547. Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
  13548. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName)
  13549. return
  13550. } else {
  13551. return
  13552. }
  13553. }
  13554. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  13555. const songMap: Map<number, VideoItem> = new Map()
  13556. let completedQueries = 0
  13557. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  13558. // 遍历所有文件路径,使用索引记录位置
  13559. for (let i = 0; i < songFilePaths.length; i++) {
  13560. const filePath = songFilePaths[i]
  13561. const index = i
  13562. // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  13563. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  13564. const queryPromise = this.table.queryVideoByFilePath(filePath)
  13565. // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  13566. queryPromise.then((videoItem) => {
  13567. completedQueries++
  13568. // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  13569. if (videoItem) {
  13570. // 使用索引作为key保存到Map中,保持原始顺序
  13571. songMap.set(index, videoItem)
  13572. // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  13573. } else {
  13574. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  13575. }
  13576. // 检查是否所有歌曲都已加载完成
  13577. if (completedQueries === songFilePaths.length) {
  13578. // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  13579. // 按照索引顺序重建歌曲数组
  13580. const songs: VideoItem[] = []
  13581. for (let j = 0; j < songFilePaths.length; j++) {
  13582. const song = songMap.get(j)
  13583. if (song) {
  13584. songs.push(song)
  13585. // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  13586. }
  13587. }
  13588. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  13589. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  13590. }
  13591. }).catch((error: Error) => {
  13592. completedQueries++
  13593. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  13594. // 即使出错也要检查是否完成所有查询
  13595. if (completedQueries === songFilePaths.length) {
  13596. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  13597. // 按照索引顺序重建歌曲数组
  13598. const songs: VideoItem[] = []
  13599. for (let j = 0; j < songFilePaths.length; j++) {
  13600. const song = songMap.get(j)
  13601. if (song) {
  13602. songs.push(song)
  13603. }
  13604. }
  13605. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  13606. }
  13607. })
  13608. }
  13609. } catch (error) {
  13610. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  13611. ToastUtil.showToast('播放失败')
  13612. }
  13613. }
  13614. /**
  13615. * 完成歌单加载并开始播放
  13616. */
  13617. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string) {
  13618. if (songs.length === 0) {
  13619. Logger.error('heanup 没有找到任何可播放的歌曲')
  13620. ToastUtil.showToast('没有找到可播放的歌曲')
  13621. return
  13622. }
  13623. this.songList = songs
  13624. this.sonDataSource.pushArrayData(songs)
  13625. this.sonDataSource.notifyDataReload()
  13626. this.curIndex = startIndex
  13627. if (songs[startIndex]) {
  13628. // 确保当前播放的歌曲也更新到存储
  13629. AppStorage.setOrCreate('currentSong', songs[startIndex])
  13630. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  13631. this.doPlay(songs[startIndex], startIndex, true)
  13632. }
  13633. PreferencesUtil.putSync('LastMusicList', this.songList)
  13634. ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  13635. }
  13636. }
  13637. //视频气泡窗口的布局
  13638. @Builder
  13639. function customPopupBuilder(dataBu: BubbleBean) {
  13640. List() {
  13641. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  13642. ListItem() {
  13643. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13644. Row() {
  13645. Column() {
  13646. Image(dataBu.imageRes[index])
  13647. .height(28)
  13648. .fillColor(dataBu.color)
  13649. .alignSelf(ItemAlign.Center)
  13650. }
  13651. .width(32)
  13652. Text(item)
  13653. .padding({
  13654. top: 10,
  13655. bottom: 10,
  13656. right: 10,
  13657. left: 10
  13658. })
  13659. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  13660. .textAlign(TextAlign.Start)
  13661. .width("100%")
  13662. }
  13663. }
  13664. .backgroundColor($r('app.color.settings_background_main'))
  13665. .margin({ top: 6, bottom: 6 })
  13666. }
  13667. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  13668. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  13669. TransitionEffect.scale({ x: 0, y: 0 })))
  13670. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  13671. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  13672. .onClick(() => {
  13673. dataBu.onItemClick?.(index)
  13674. })
  13675. })
  13676. }
  13677. .scrollBar(BarState.Off)
  13678. .width(120)
  13679. .divider({
  13680. strokeWidth: 1,
  13681. color: "#22FFFFFF"
  13682. })
  13683. }
  13684. // Function to calculate a hash for the file list
  13685. function simpleHash(fileList: string[]): string {
  13686. let hash = 0;
  13687. const str = fileList.join(',');
  13688. for (let i = 0; i < str.length; i++) {
  13689. const char = str.charCodeAt(i);
  13690. hash = (hash << 5) - hash + char;
  13691. hash |= 0; // Convert to 32bit integer
  13692. }
  13693. return hash.toString();
  13694. }
  13695. interface MoreItem {
  13696. id: number;
  13697. image: Resource;
  13698. title: string;
  13699. }
  13700. //视频气泡窗口的布局
  13701. @Builder
  13702. function cutPopupBuilder(dataBu: BubbleBean) {
  13703. Column() {
  13704. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  13705. .padding({
  13706. top: 10,
  13707. bottom: 10,
  13708. right: 10,
  13709. left: 10
  13710. })
  13711. .textAlign(TextAlign.Start)
  13712. .width(160)
  13713. .fontWeight(666)
  13714. .fontSize(16)
  13715. List() {
  13716. ForEach(dataBu.data, (item: string, index: number) => {
  13717. ListItem() {
  13718. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13719. Row() {
  13720. Column() {
  13721. Image($r('app.media.music_group'))
  13722. .height(28)
  13723. .fillColor(dataBu.color)
  13724. .alignSelf(ItemAlign.Center)
  13725. }
  13726. .width(32)
  13727. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  13728. .padding({
  13729. top: 10,
  13730. bottom: 10,
  13731. right: 10,
  13732. left: 10
  13733. })
  13734. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  13735. .fontSize(15)
  13736. }
  13737. }
  13738. .backgroundColor(Color.Transparent)
  13739. .margin({ top: 7, bottom: 7 })
  13740. }
  13741. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  13742. .animation({ duration: 500 }),
  13743. TransitionEffect.scale({ x: 0, y: 0 })))
  13744. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  13745. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  13746. .onClick(() => {
  13747. dataBu.onItemClick?.(index)
  13748. })
  13749. })
  13750. }
  13751. .scrollBar(BarState.Off)
  13752. .width(150)
  13753. .divider({
  13754. strokeWidth: 1,
  13755. color: "#22FFFFFF"
  13756. })
  13757. }
  13758. .height(300)
  13759. .padding({
  13760. bottom: 30
  13761. })
  13762. }
  13763. function getFileDirName(filePath: string,rootPath:string): string{
  13764. if(filePath===rootPath){
  13765. return '首页'
  13766. }
  13767. let result = FileUtil.getFileName(filePath)
  13768. if(StrUtil.isEmpty(result))
  13769. return ''
  13770. if(result.startsWith('.'))
  13771. result = result.replace(/\./g, '')
  13772. return result
  13773. }
  13774. //只扫描当前目录下文件(不扫描子文件夹)的方法
  13775. @Concurrent
  13776. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  13777. const table: MediaTable = new MediaTable(context);
  13778. try {
  13779. // 直接获取当前目录下的文件列表
  13780. const files = FileUtil.listFileSync(dirPath);
  13781. await Promise.all(files.map(async (file) => {
  13782. const fPath = `${dirPath}/${file}`;
  13783. // 跳过目录,只处理文件
  13784. if (FileUtil.isDirectory(fPath)) {
  13785. return;
  13786. }
  13787. // 跳过特定格式文件
  13788. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  13789. return;
  13790. }
  13791. // 检查是否为媒体文件
  13792. if (Utility.isMeidaByExtension(fPath)) {
  13793. let mType = CommonConstants.TYPE_LOCAL;
  13794. if (fPath.includes(lockPath)) {
  13795. mType = CommonConstants.TYPE_LOCK;
  13796. }
  13797. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  13798. context, fPath, mType, true
  13799. );
  13800. table.insert(mediaItem, (id: number) => {
  13801. // 插入回调函数
  13802. }, cover_api);
  13803. }
  13804. }));
  13805. } catch (error) {
  13806. console.error(' 扫描当前目录失败:', error);
  13807. }
  13808. }
  13809. //内嵌标签后更新库
  13810. @Concurrent
  13811. async function updateInfoDb(
  13812. context: Context,
  13813. filePath: string,
  13814. titleStr: string,
  13815. artistStr: string,
  13816. albumStr: string,
  13817. lyricConStr: string,
  13818. yearStr: string,
  13819. genreStr: string,
  13820. trackStr: string,
  13821. albumArtistStr: string,
  13822. composerStr: string,
  13823. lyricistStr: string,
  13824. commentStr: string,
  13825. discStr: string,
  13826. ): Promise<boolean> {
  13827. const table: MediaTable = new MediaTable(context);
  13828. await new Promise<void>((resolve, reject) => {
  13829. table.getRdbStore(context, (err:Error) => {
  13830. err ? reject(err) : resolve();
  13831. });
  13832. });
  13833. return await new Promise<boolean>((resolve) => {
  13834. table.updateMediaInfo(filePath, titleStr, artistStr, albumStr, lyricConStr,
  13835. yearStr, genreStr, trackStr, albumArtistStr, composerStr, lyricistStr, commentStr, discStr,
  13836. (success: boolean, error?: string) => {
  13837. if (success) {
  13838. console.log("onecold 编辑信息成功,数据库已同步");
  13839. } else {
  13840. console.error("onecold 编辑信息数据库失败原因: " + error);
  13841. }
  13842. resolve(success);
  13843. });
  13844. });
  13845. }