LocalMusic.ets 520 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028
  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 NetAxiosUtil from '../common/util/NetAxiosUtil';
  77. import ImageUtils from '../common/util/ImageUtils';
  78. import { ringtone } from '@kit.RingtoneKit';
  79. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  80. import { resourceManager } from '@kit.LocalizationKit';
  81. import { deviceInfo } from '@kit.BasicServicesKit';
  82. import { ensureSmbFileCached } from '../common/network/SmbFileCache';
  83. import { findWebDavCacheIfExists, triggerWebDavCacheDownload } from '../common/network/WebDavFileCache';
  84. import { navidromeApi } from '../common/network/NavidromeApi';
  85. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  86. import app from '@system.app';
  87. import { TextNodeController } from './PipLyricTextBuilder';
  88. import { IndexerView } from './IndexerView';
  89. import { KeyCode } from '@kit.InputKit';
  90. import { KnockController } from '../controller/KnockController';
  91. import { DeleteComptent } from '../view/DeleteComptent';
  92. import { ABLoopComptent } from '../view/ABLoopComptent';
  93. import { FixMessyView } from '../view/FixMessyView';
  94. import { parseCueFile,CueTrack,CueInfo } from '../common/util/CueUtils';
  95. import { CueComptent } from '../view/CueComptent';
  96. import PlaylistTable from '../common/util/PlaylistTable';
  97. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  98. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  99. import { convertPlaylistSongsToVideoItems, emptyView,updateAllSongsSortOrder } from '../pages/PlaylistDetailPage';
  100. import { Playlist, PlaylistSong } from '../viewmodel/Playlist';
  101. import { Song } from '../viewmodel/Song';
  102. import { SongType } from '../common/enums/SongType';
  103. import { RemoteDriveManager, WebDavAuthInfo as WebDavManagerAuthInfo,
  104. buildHttpHeadersWithWebDav,
  105. WebDavAuthItem} from '../common/util/RemoteDriveManager';
  106. import PermissionUtil from '../common/util/PermissionUtil'
  107. import { EditAudio, setRingTone } from './EditAudio';
  108. import { ExtractAccompaniment } from './ExtractAccompaniment';
  109. import { ExtractAudioFromVideo } from './ExtractAudioFromVideo';
  110. import { AudioFormatConverter } from './AudioFormatConverter';
  111. import { MergeAudio } from './MergeAudio';
  112. import { AIVoiceSeparation } from './AIVoiceSeparation';
  113. import { WebDavUrlUtil } from '../common/util/WebDavUrlUtil';
  114. import {
  115. hdsEffect,
  116. HdsVisualComponent,
  117. HdsSceneController,
  118. HdsSceneType,
  119. HdsVisualComponentAttribute,
  120. } from '@kit.UIDesignKit';
  121. const TAG = 'LocalMusic';
  122. /**
  123. * 歌单播放事件数据
  124. */
  125. interface PlaylistEventData {
  126. playlistId: string;
  127. playlistName: string;
  128. songCount: number;
  129. startIndex: number;
  130. songFilePaths: string[];
  131. webDavAuthInfo?: WebDavAuthItem; // 新增WebDAV认证信息
  132. }
  133. const DEFAULT_INDEX =
  134. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  135. 'X', 'Y', 'Z']
  136. //排序类型
  137. function getTypeOrder(type: number) {
  138. switch (type) {
  139. case CommonConstants.TYPE_IS_DIR:
  140. return 1; // First
  141. case CommonConstants.TYPE_IS_CSJAD:
  142. return 2; // Middle
  143. case CommonConstants.TYPE_LOCAL:
  144. return 3; // Last
  145. case CommonConstants.TYPE_WEBDAV:
  146. case CommonConstants.TYPE_SMB:
  147. case CommonConstants.TYPE_NAVIDROME:
  148. return 3;
  149. default:
  150. return 4; // Unknown types, if any, go last
  151. }
  152. }
  153. function isWebDavType(type: number): boolean {
  154. return type === CommonConstants.TYPE_WEBDAV;
  155. }
  156. function isSmbType(type: number): boolean {
  157. return type === CommonConstants.TYPE_SMB;
  158. }
  159. function isNavidromeType(type: number): boolean {
  160. return type === CommonConstants.TYPE_NAVIDROME;
  161. }
  162. function isRemoteCloudType(type: number): boolean {
  163. return isWebDavType(type) || isSmbType(type) || isNavidromeType(type);
  164. }
  165. function getShareNameFromFilePath(filePath?: string): string | undefined {
  166. if (!filePath) {
  167. return undefined;
  168. }
  169. const match = filePath.match(/^smb:\/\/[^/]+\/([^/]+)/i);
  170. return match && match[1] ? match[1] : undefined;
  171. }
  172. function removeSharePrefixFromPath(path: string, primaryShare?: string, secondaryShare?: string): string {
  173. const uniqueShares: string[] = [];
  174. [primaryShare, secondaryShare].forEach((name?: string) => {
  175. const cleaned = name ? name.replace(/^\/+|\/+$/g, '') : '';
  176. if (cleaned.length > 0 && !uniqueShares.some(item => item.toLowerCase() === cleaned.toLowerCase())) {
  177. uniqueShares.push(cleaned);
  178. }
  179. });
  180. if (uniqueShares.length === 0) {
  181. return path;
  182. }
  183. let result = path;
  184. for (let i = 0; i < uniqueShares.length; i++) {
  185. const share = uniqueShares[i];
  186. const lowerPath = result.toLowerCase();
  187. const lowerShare = share.toLowerCase();
  188. if (lowerPath === lowerShare) {
  189. result = '';
  190. break;
  191. }
  192. const prefix = `${lowerShare}/`;
  193. if (lowerPath.startsWith(prefix)) {
  194. result = result.substring(share.length + 1);
  195. break;
  196. }
  197. }
  198. return result;
  199. }
  200. function extractSmbRelativePath(song: VideoItem, shareNameOverride?: string): string {
  201. const shareFromFilePath = getShareNameFromFilePath(song.filePath);
  202. const shareName = shareNameOverride ?? shareFromFilePath;
  203. if (song.remote_rel_path && song.remote_rel_path.length > 0) {
  204. const cleaned = song.remote_rel_path.replace(/^\/+/, '');
  205. return removeSharePrefixFromPath(cleaned, shareName, shareFromFilePath);
  206. }
  207. if (!song.filePath) {
  208. return '';
  209. }
  210. const match = song.filePath.match(/^smb:\/\/[^/]+\/([^/]+)(\/.*)?$/i);
  211. if (!match) {
  212. return song.filePath.replace(/^\/+/, '');
  213. }
  214. const remainder = match[2] ? match[2].replace(/^\/+/, '') : '';
  215. if (remainder.length === 0) {
  216. return '';
  217. }
  218. return remainder;
  219. }
  220. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  221. interface MetadataExtractionOptions {
  222. context?: common.Context;
  223. autoParseMusicName?: boolean;
  224. }
  225. interface WorkerMetadataPayload {
  226. originFilePath: string;
  227. originId?: string;
  228. bit_rate?: string;
  229. duration?: string;
  230. sampleRate?: string;
  231. mimeType?: string;
  232. md5Str?: string;
  233. videoSize?: number;
  234. size?: string;
  235. pixelMapPath?: string;
  236. artist?: string;
  237. album?: string;
  238. name?: string;
  239. lyricContent?: string;
  240. bits_per_raw_sample?: string;
  241. channels?: string;
  242. channel_layout?: string;
  243. start_time?: string;
  244. genre?: string;
  245. year?: string;
  246. probe_score?: number;
  247. track?: string;
  248. disc?: string;
  249. ALBUMARTIST?: string;
  250. COMPOSER?: string;
  251. COMMENT?: string;
  252. LYRICIST?: string;
  253. nb_streams?: number;
  254. nb_programs?: number;
  255. error?: string;
  256. }
  257. const metadataExtractionInFlight: Set<string> = new Set();
  258. function scheduleMetadataExtractionFromCache(
  259. song: VideoItem,
  260. cachePath: string,
  261. options?: MetadataExtractionOptions
  262. ): void {
  263. if (!song || !cachePath || !song.filePath || !options || !options.context) {
  264. return;
  265. }
  266. if (!isRemoteCloudType(song.type ?? -1)) {
  267. return;
  268. }
  269. if (metadataExtractionInFlight.has(song.filePath)) {
  270. return;
  271. }
  272. if (song.bit_rate && song.sampleRate && song.duration) {
  273. return;
  274. }
  275. metadataExtractionInFlight.add(song.filePath);
  276. workerInstance.postMessage({
  277. code: 5,
  278. data: options.context,
  279. data2: cachePath,
  280. data3: song.type,
  281. data4: {
  282. name:song.name,
  283. originFilePath: song.filePath,
  284. originId: song.id,
  285. autoParseMusicName: options.autoParseMusicName ?? false
  286. }
  287. });
  288. }
  289. function sanitizePlaybackUrl(rawUrl: string | null | undefined): string {
  290. if (!rawUrl) {
  291. return '';
  292. }
  293. try {
  294. const decoded = decodeURI(rawUrl);
  295. const encoded = encodeURI(decoded);
  296. // encodeURI 不会处理 #,手动转义避免播放器把剩余内容当作片段
  297. return encoded.replace(/#/g, '%23');
  298. } catch (error) {
  299. const err = error as Error;
  300. Logger.warn(TAG, `URL 编码失败,使用降级方案: ${err?.message}`);
  301. return rawUrl.replace(/ /g, '%20').replace(/#/g, '%23');
  302. }
  303. }
  304. function cloneVideoItem(item: VideoItem): VideoItem {
  305. const copy = new VideoItem(
  306. item.name,
  307. item.id,
  308. item.filePath,
  309. item.type,
  310. item.videoSize,
  311. item.cTime,
  312. item.pixelMap,
  313. item.size,
  314. item.pixelMapPath,
  315. item.artist,
  316. item.album,
  317. item.fileName,
  318. item.lastPlayed
  319. );
  320. copy.parentPath = item.parentPath;
  321. copy.isFav = item.isFav;
  322. copy.pixelMap = item.pixelMap;
  323. copy.size = item.size;
  324. copy.pixelMapPath = item.pixelMapPath;
  325. copy.artist = item.artist;
  326. copy.album = item.album;
  327. copy.duration = item.duration;
  328. copy.mimeType = item.mimeType;
  329. copy.sampleRate = item.sampleRate;
  330. copy.trackCount = item.trackCount;
  331. copy.lastPlayedStr = item.lastPlayedStr;
  332. copy.playCount = item.playCount;
  333. copy.lyricContent = item.lyricContent;
  334. copy.md5Str = item.md5Str;
  335. copy.extra_json = item.extra_json;
  336. copy.pyStr = item.pyStr;
  337. copy.bit_rate = item.bit_rate;
  338. copy.probe_score = item.probe_score;
  339. copy.year = item.year;
  340. copy.nb_streams = item.nb_streams;
  341. copy.nb_programs = item.nb_programs;
  342. copy.genre = item.genre;
  343. copy.track = item.track;
  344. copy.bits_per_raw_sample = item.bits_per_raw_sample;
  345. copy.channels = item.channels;
  346. copy.channel_layout = item.channel_layout;
  347. copy.start_time = item.start_time;
  348. copy.ALBUMARTIST = item.ALBUMARTIST;
  349. copy.COMPOSER = item.COMPOSER;
  350. copy.LYRICIST = item.LYRICIST;
  351. copy.COMMENT = item.COMMENT;
  352. copy.disc = item.disc;
  353. copy.webdav_account_id = item.webdav_account_id;
  354. copy.remote_rel_path = item.remote_rel_path;
  355. return copy;
  356. }
  357. /**
  358. * 异步设置videoUrl的辅助方法,处理WebDAV URL的构建
  359. * @param song 歌曲对象
  360. * @returns Promise<string> 完整的URL
  361. */
  362. /**
  363. * 设置videoUrl,通过webdav_account_id设置完整的 URL
  364. * @param song 歌曲对象
  365. * @returns Promise<string> 完整的URL
  366. */
  367. async function setVideoUrlForSong(song: VideoItem, options?: MetadataExtractionOptions): Promise<string> {
  368. const metadataOptions = options ?? {};
  369. if (isWebDavType(song.type) && song.webdav_account_id) {
  370. try {
  371. Logger.info(TAG, `WebDAV 路径信息 remote_rel_path: ${song.remote_rel_path}`);
  372. Logger.info(TAG, `WebDAV 路径信息 filePath: ${song.filePath}`);
  373. const relativePath = song.remote_rel_path || song.filePath;
  374. const manager = RemoteDriveManager.getInstance();
  375. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  376. if (account) {
  377. const cachePath = await findWebDavCacheIfExists(account, relativePath);
  378. if (cachePath) {
  379. Logger.info(TAG, `WebDAV 缓存命中,直接播放: ${cachePath}`);
  380. scheduleMetadataExtractionFromCache(song, cachePath, metadataOptions);
  381. return cachePath;
  382. }
  383. const fullUrlFromAccount = WebDavUrlUtil.buildFullUrl(account, relativePath);
  384. if (fullUrlFromAccount) {
  385. const sanitizedUrl = sanitizePlaybackUrl(fullUrlFromAccount);
  386. const downloadPromise = triggerWebDavCacheDownload(account, relativePath, sanitizedUrl);
  387. if (downloadPromise) {
  388. downloadPromise.then((completedPath?: string | null) => {
  389. if (completedPath) {
  390. scheduleMetadataExtractionFromCache(song, completedPath, metadataOptions);
  391. }
  392. }).catch((error: Error) => {
  393. Logger.error(TAG, `WebDAV 缓存后台下载失败: ${error.message}`);
  394. });
  395. }
  396. Logger.info(TAG, `WebDAV 启动异步缓存: ${relativePath}`);
  397. return sanitizedUrl;
  398. }
  399. }
  400. const fallbackUrl = await WebDavUrlUtil.buildFullUrlByAccountId(song.webdav_account_id, relativePath);
  401. if (fallbackUrl) {
  402. Logger.warn(TAG, `WebDAV 使用全局查询到的URL: ${fallbackUrl}`);
  403. return sanitizePlaybackUrl(fallbackUrl);
  404. }
  405. Logger.error(TAG, `WebDAV URL构建失败,使用原始路径: ${relativePath}`);
  406. return sanitizePlaybackUrl(relativePath);
  407. } catch (error) {
  408. Logger.error(TAG, `WebDAV URL构建出错: ${(error as Error).message}`);
  409. const fallbackPath = song.remote_rel_path || song.filePath;
  410. return sanitizePlaybackUrl(fallbackPath);
  411. }
  412. }
  413. if (isNavidromeType(song.type) && song.webdav_account_id) {
  414. try {
  415. const manager = RemoteDriveManager.getInstance();
  416. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  417. if (!account) {
  418. throw new Error('Navidrome账号不可用');
  419. }
  420. const navSongId = song.remote_rel_path || song.id || song.filePath;
  421. const streamUrl = await navidromeApi.buildStreamUrl(account, navSongId);
  422. Logger.info(TAG, `Navidrome 流地址构建成功: ${streamUrl}`);
  423. return sanitizePlaybackUrl(streamUrl);
  424. } catch (error) {
  425. const err = error as Error;
  426. Logger.error(TAG, `Navidrome URL构建失败: ${err.message}`);
  427. throw new Error(err.message);
  428. }
  429. }
  430. if (isSmbType(song.type) && song.webdav_account_id) {
  431. try {
  432. const manager = RemoteDriveManager.getInstance();
  433. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  434. if (!account) {
  435. throw new Error('SMB账号不可用');
  436. }
  437. const relativePath = extractSmbRelativePath(song, account.smbShare);
  438. const cachedPath = await ensureSmbFileCached(account, relativePath);
  439. Logger.info(TAG, `SMB 缓存路径: ${cachedPath}`);
  440. scheduleMetadataExtractionFromCache(song, cachedPath, metadataOptions);
  441. return cachedPath;
  442. } catch (error) {
  443. const err = error as Error;
  444. Logger.error(TAG, `SMB 缓存失败: ${err.message}`);
  445. throw new Error(err.message);
  446. }
  447. }
  448. if (isWebDavType(song.type)) {
  449. Logger.warn(TAG, `WebDAV歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
  450. return sanitizePlaybackUrl(song.filePath);
  451. }
  452. if (isSmbType(song.type)) {
  453. Logger.warn(TAG, `SMB歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
  454. return song.filePath;
  455. }
  456. if (isNavidromeType(song.type)) {
  457. throw new Error('Navidrome歌曲缺少webdav_account_id,无法构建播放链接');
  458. }
  459. return song.filePath;
  460. }
  461. // 定义接口
  462. interface HiCarAspectRatio {
  463. ratio: number;
  464. name: string;
  465. }
  466. interface GeneratedObjectLiteralInterface_1 {
  467. assetId: string;
  468. title: string;
  469. artist: string;
  470. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  471. mediaUri: string;
  472. // 该字段大写,音频'AUDIO',视频'VIDEO'
  473. mediaType: string;
  474. mediaSize: number;
  475. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  476. startPosition: number;
  477. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  478. duration: number;
  479. albumCoverUri: string;
  480. albumTitle: string;
  481. appName: string;
  482. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  483. drmScheme: string;
  484. }
  485. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  486. const ITEM_HEIGHT: number = 65; // 列表项中高度
  487. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  488. //功能强大的音乐播放器
  489. @Preview
  490. @Component
  491. export struct LocalMusic {
  492. @State isShowPrecious: boolean = false //播控条显示上一首按钮
  493. //背景两侧流光控制器
  494. @State sceneBgController: HdsSceneController|undefined = deviceInfo.sdkApiVersion>=20
  495. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  496. new HdsSceneController()
  497. .setSceneParams({
  498. backgroundMaskColors: [Color.Green, Color.Red],
  499. firstEdgeFlowLight: {
  500. startPos: 0,
  501. endPos: 0.5,
  502. color: Color.Red
  503. },
  504. secondEdgeFlowLight: {
  505. startPos: 0,
  506. endPos: -0.5,
  507. color: Color.Green
  508. }
  509. }) : undefined;
  510. //背景流光控制器
  511. @State bgController: hdsEffect.ShaderEffectController|undefined = deviceInfo.sdkApiVersion>=20
  512. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  513. new hdsEffect.ShaderEffectController():undefined;
  514. @State showAddSheet:boolean = false
  515. searchController: SearchController = new SearchController()
  516. @State rightTopImage:Resource = $r('sys.symbol.sort')
  517. @State isEditAudio:boolean = false
  518. @State isExtractAcc:boolean = false
  519. @State isConverter:boolean = false
  520. @State isAIVoiceSeparation:boolean = false
  521. @State isExtractAudio:boolean = false
  522. @State isMergeAudio:boolean = false
  523. @State isCopyFileToDownLoad: boolean = false
  524. @State offHeight: number = 75
  525. @State currentSongList: Array<VideoItem> = []//当前歌单
  526. @Consume currentSongListName:string //当前歌单名称
  527. @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
  528. @State isRefreshing: boolean = false;
  529. @State maxRefreshingHeight: number = 100.0;
  530. private contentNode?: ComponentContent<Object> = undefined;
  531. // WebDAV相关实例变量(现在改为从内存读取,不再需要存储)
  532. @State ratioL: number = 1;
  533. @State mediaKuCount: number = 0;
  534. @State albumCount: number = 0;
  535. @State artistCount: number = 0;
  536. @State fastForwardSeconds: string = '10'
  537. @State isShowBackFast: boolean = true//快进快退按钮
  538. @State isCanAuto:boolean = true
  539. @State opacityValueImage: number = 1;
  540. @State tipPopup:boolean = false
  541. @Consume mType: number;
  542. @StorageProp('themeColor') themeColor: string =
  543. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  544. themeMode: number = 0;
  545. @State titleName: string = '首页'
  546. @State textStr: string = ''
  547. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  548. // private download_path: string = '';
  549. @Consume rootPath: string //音频根目录
  550. @Consume currentPath: string
  551. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  552. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  553. @State lockPath: string = ''
  554. @State favPath: string = ''
  555. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  556. @State historyPath: string = ''
  557. @State historyList: Array<VideoItem> = []
  558. @Consume isHistory: boolean
  559. static readonly HISTORY_MUSIC: string = 'music_historyList';
  560. private table: MediaTable = new MediaTable(getContext(this))
  561. private playlistTable: PlaylistTable | null = null
  562. @State allPlaylists: Playlist[] = []
  563. @State isZero: boolean = false
  564. @State fileList: Array<string> = []
  565. @State dirList: Array<VideoItem> = []
  566. @Consume videoLocalList:VideoItem[]
  567. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  568. @State listRefreshKey: number = 0
  569. // @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  570. @StorageProp('mediaKuList') mediaKuList: Array<VideoItem> = []; //媒体库文件
  571. @State artistList: Array<VideoItem> = []; //艺术家文件
  572. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  573. @State albumList: Array<VideoItem> = []; //专辑文件
  574. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  575. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  576. @State imageOpacities: number[] = [];
  577. @Consume isCanBack: boolean
  578. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  579. @State showSingleLyric: boolean = false
  580. @State sortType: number = 4 //默认排序方式
  581. @State isShowSimi: boolean = false //是否显示私密音频
  582. @State isShowFAV: boolean = true //是否显示我的收藏
  583. @State @Watch('onTopBarhange')isShowTitleBar: boolean = true //是否显示分类导航条
  584. @State isShowAllBar: boolean = true //是否显示播放全部条
  585. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  586. @State isShowHistory: boolean = true //是否显示最近播放
  587. @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
  588. @State isGridMusic: boolean = false //是否网格布局
  589. @State isCircleBtn: boolean = false //是否圆形播放按钮
  590. @State twoFingerType: number = 3 //双支放大缩小的类型
  591. @State isScrollHide: boolean = false //是否滚动隐藏
  592. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  593. @State isStartAutoPlay: boolean = false //启动后自动播放
  594. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  595. @State isShowHeader: boolean = true
  596. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  597. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  598. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  599. @State isSwipe: boolean = false //listItem的左滑开关
  600. @State openSkipSongAnimate: boolean = true//切歌动画效果
  601. @State customizeBgPath: string | undefined = '';
  602. @State isDarkMode: boolean = false
  603. @State lyricTextWeight: number = 400
  604. @State lyricTextWeightPip: number = 400
  605. @State currentSwiperIndex: number = 0
  606. @State blurValue: number = 0 //背景模糊
  607. @State bgBrightness: number = 0 //背景亮度
  608. private listScroller: ListScroller = new ListScroller()
  609. private playListScroller: Scroller = new Scroller()
  610. @State isOneKeyTags:boolean = false
  611. @State isFixMessy:boolean = false
  612. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  613. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  614. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  615. @StorageProp('windowWidth') windowWidth: number = 0;
  616. @StorageProp('windowHeight') windowHeight: number = 0;
  617. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  618. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  619. private UNKONWN:string = '';
  620. private listArea: Area = {
  621. width: 0,
  622. height: 0,
  623. position: {},
  624. globalPosition: {}
  625. }
  626. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  627. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  628. // WebDAV认证信息缓存(作为实例变量,比全局上下文更可靠)
  629. private currentWebDavAuthInfo: WebDavAuthItem | null = null;
  630. //瀑布流的列数横竖屏动态切换
  631. onIsLandscapeChange() {
  632. if(this.isLandscape){
  633. this.columns = 4
  634. }else{
  635. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  636. }
  637. }
  638. onColorModeChange() {
  639. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  640. }
  641. //bar导航条显示状态变化,不显示的话把topBarHeight=0
  642. onTopBarhange(){
  643. if(this.isShowTitleBar){
  644. console.log('onecold 导航条显示')
  645. this.topBarHeight = 50
  646. this.offHeight = 75
  647. }else{
  648. console.log('onecold 导航条隐藏')
  649. this.topBarHeight = 0
  650. if(this.twoFingerType!=4){
  651. this.offHeight = 30
  652. }
  653. }
  654. }
  655. //点击某个歌单id发生变化的时候回调
  656. onIDChange(){
  657. console.log('onecold 歌单id发生变化this.currentSongListID='+this.currentSongListID)
  658. console.log('onecold 歌单id发生变化this.currentSongListName='+this.currentSongListName)
  659. if(this.modeType==4){
  660. this.isShowTitleBar = false
  661. this.titleName = this.currentSongListName
  662. this.rightTopImage = $r('sys.symbol.sort')
  663. //获取缓存
  664. const cacheSongs:string =PreferencesUtil.getStringSync(this.currentSongListID+'currentSongList', '')
  665. console.log('onecold 歌单id发生变化获取缓存2 cacheSongs = '+cacheSongs)
  666. if(StrUtil.isNotEmpty(cacheSongs)){
  667. this.currentSongList = JSON.parse(cacheSongs) as VideoItem[]
  668. this.updateListData(this.currentSongList, true)
  669. }
  670. this.doSongListTask()//获取歌单信息
  671. }
  672. }
  673. async doSongListTask() {
  674. // 初始化歌单数据库
  675. const playlistTable = new PlaylistTable(this.context);
  676. // 查询歌单中的所有歌曲
  677. const playlistSongs: PlaylistSong[] = await playlistTable.queryPlaylistSongs(this.currentSongListID);
  678. console.log('onecold 歌单id发生变化获取缓存7 playlistSongs='+playlistSongs.length)
  679. if (ArrayUtil.isEmpty(playlistSongs)) {
  680. this.updateListData([], true)
  681. } else {
  682. this.currentSongList = await convertPlaylistSongsToVideoItems(this.context, playlistSongs);
  683. console.log('onecold 从数据库读取的歌曲为 playlistSongs='+this.currentSongList.length)
  684. this.updateListData(this.currentSongList, true)
  685. if (ArrayUtil.isNotEmpty(this.currentSongList)&&this.currentSongList.length > 100) {
  686. // 只保存前100条记录到缓存中
  687. let canceList = this.currentSongList.slice(0, 100);
  688. PreferencesUtil.putSync(this.currentSongListID+'currentSongList',
  689. JSON.stringify(canceList))
  690. } else {
  691. PreferencesUtil.putSync(this.currentSongListID+'currentSongList', JSON.stringify(this.currentSongList));
  692. }
  693. }
  694. this.isRefreshing = false
  695. }
  696. onModeChange() {
  697. this.isFavMusic = false
  698. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, false)
  699. switch (this.modeType) {
  700. case 0:
  701. this.getSortedFiles(this.currentPath)
  702. break
  703. case 1:
  704. this.rightTopImage = $r('sys.symbol.sort')
  705. this.updateListData(this.mediaKuList)
  706. this.titleName = Utility.resourceToString(this.context,$r('app.string.media_ku'))
  707. break
  708. case 2:
  709. this.rightTopImage = $r('sys.symbol.sort')
  710. this.updateListData(this.artistList)
  711. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  712. break
  713. case 3:
  714. this.rightTopImage = $r('sys.symbol.sort')
  715. this.updateListData(this.albumList)
  716. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  717. break
  718. }
  719. }
  720. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  721. // @StorageLink('isPlay') isPlay: boolean = false;
  722. @StorageLink('isShowPlay') isShowPlay: boolean = false;
  723. @StorageLink('songList') songList: Array<VideoItem> = [];
  724. @State translateY: number = 0;
  725. @State isShowSheet: boolean = false;
  726. @State isShowSheetView: boolean = false;
  727. @State isShowTimeCloseView: boolean = false;
  728. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  729. @StorageLink('currIndex') curIndex: number = 0;
  730. @Consume isShowDrawer: boolean;
  731. @Consume offsetX: number;
  732. @State isFac: boolean = false;
  733. @State favList: Array<VideoItem> = []
  734. @Consume isFavMusic: boolean
  735. @State isClickedPLayAll: boolean = false;
  736. private scrollerForlist: ListScroller = new ListScroller();
  737. private knockController: KnockController | undefined = undefined;
  738. // 修改为:
  739. imagesF: ImageFrameInfo[] = CommonConstants.IMAGE_FRAME_INFO;
  740. @StorageProp('animationState') animationState: AnimationStatus = AnimationStatus.Initial
  741. // 缓存机制
  742. private cache: Map<string, Array<VideoItem>> = new Map();
  743. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  744. // 持久化缓存
  745. private async saveCacheToStorage() {
  746. const cacheArray = Array.from(this.cache.entries());
  747. const stringCacheArray = Array.from(this.stringCache.entries());
  748. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  749. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  750. }
  751. // 载入缓存
  752. private async loadCacheFromStorage() {
  753. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  754. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  755. if (cacheString) {
  756. const cacheArray: [string, Array<VideoItem>][] = JSON.parse(cacheString);
  757. this.cache = new Map(cacheArray);
  758. }
  759. if (stringCacheString) {
  760. const stringCacheArray: [string, string][] = JSON.parse(stringCacheString);
  761. this.stringCache = new Map(stringCacheArray);
  762. }
  763. }
  764. // 查找缓存
  765. private findCache(key: string): Array<VideoItem> | undefined {
  766. return this.cache.get(key);
  767. }
  768. // 查找字符串缓存
  769. private findStringCache(key: string): string | undefined {
  770. return this.stringCache.get(key);
  771. }
  772. // 添加缓存
  773. private addCache(key: string, value: Array<VideoItem>) {
  774. this.cache.set(key, value);
  775. }
  776. // 添加字符串缓存
  777. private addStringCache(key: string, value: string) {
  778. this.stringCache.set(key, value);
  779. }
  780. // 删除缓存
  781. private deleteCache(key: string) {
  782. this.cache.delete(key);
  783. this.saveCacheToStorage()
  784. }
  785. // 删除字符串缓存
  786. private deleteStringCache(key: string) {
  787. this.stringCache.delete(key);
  788. }
  789. // 多选机制
  790. @State selectedFiles: Array<VideoItem> = [];
  791. @State isMultiSelect: boolean = false;
  792. @State isAllSelected: boolean = false;
  793. @State appName: string = ''
  794. @State isHasDir: boolean = false
  795. @State packName: string = ''
  796. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  797. doSwipBack() {
  798. if(this.isSearchMode){
  799. console.info('onecold doSwipBack = ' +this.isSearchMode)
  800. this.isSearchMode = false
  801. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  802. this.searchText = ''
  803. this.getSortedFiles(this.currentPath)
  804. return
  805. }
  806. this.onSearchInput('')
  807. return
  808. }
  809. this.isZero = false
  810. if (this.modeType !== 0 && this.isCanBack) {
  811. this.onModeChange()
  812. this.isCanBack = false
  813. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  814. setTimeout(() => {
  815. if (this.modeType == 2) {
  816. if (this.isGridMusic||this.twoFingerType==4) {
  817. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  818. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  819. if(this.twoFingerType==4){
  820. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  821. }else{
  822. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  823. }
  824. } else {
  825. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  826. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  827. }
  828. } else if (this.modeType == 3) {
  829. if (this.isGridMusic||this.twoFingerType==4) {
  830. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  831. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 0
  832. if(this.twoFingerType==4){
  833. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  834. }else{
  835. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  836. }
  837. } else {
  838. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  839. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  840. }
  841. }
  842. }, 200)
  843. return
  844. }
  845. if (this.isHistory || this.isFavMusic) {
  846. this.isHistory = false
  847. this.getSortedFiles(this.currentPath)
  848. return
  849. }
  850. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  851. animateTo({ duration: 555 }, () => {
  852. // 动画闭包内控制Image组件的出现和消失
  853. this.isShowDrawer = !this.isShowDrawer
  854. this.offsetX = 0
  855. })
  856. return
  857. }
  858. //返回上一级歌单的滚动位置
  859. setTimeout(() => {
  860. if (this.modeType == 0) {
  861. if (this.isGridMusic||this.twoFingerType==4) {
  862. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  863. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
  864. if(this.twoFingerType==4){
  865. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  866. }else{
  867. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  868. }
  869. } else {
  870. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  871. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  872. }
  873. }
  874. }, 300)
  875. this.currentPath = Utility.getParentDirectory(this.currentPath)
  876. Logger.info('this.currentPath2 = ' + this.currentPath)
  877. this.getSortedFiles(this.currentPath)
  878. }
  879. // 组件生命周期
  880. aboutToAppear() {
  881. console.info('onecold aboutToAppear sdkApiVersion = '+deviceInfo.sdkApiVersion)
  882. if(ArrayUtil.isNotEmpty(this.videoLocalList)&&this.modeType==0){
  883. this.updateListData(this.videoLocalList)
  884. }
  885. // 初始化 PlaylistTable
  886. this.playlistTable = new PlaylistTable(getContext(this))
  887. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  888. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  889. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  890. this.tipPopup = !this.tipPopup
  891. PreferencesUtil.putSync('isFirstTiped',false)
  892. }
  893. this.initSetting()
  894. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  895. Utility.getAppName(getContext(this)).then((appName: string) => {
  896. this.appName = appName
  897. })
  898. this.packName = AppUtil.getBundleName()
  899. this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
  900. this.loadCacheFromStorage(); // 加载文件夹缓存
  901. // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
  902. this.initLoadCache()
  903. this.mkDownLoadDir()
  904. let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
  905. // 监听广播事件(打开其他应用处理)
  906. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  907. this.saveVideoDatas([eventData.data?.message], true)
  908. });
  909. //侧滑广播接收时间
  910. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
  911. // 监听广播事件(打开其他应用处理)
  912. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  913. animateTo({ duration: 555 }, () => {
  914. this.doSwipBack()
  915. })
  916. });
  917. //ScanFilePage广播接收时间
  918. let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
  919. // 监听ScanFilePage广播事件(更新数据库)
  920. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  921. this.doUpdateData()
  922. });
  923. // 监听歌单播放请求事件
  924. let eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY }
  925. emitter.on(eventPlaylistPlay, async (eventData: emitter.EventData) => {
  926. const data = eventData.data as Record<string, Object>
  927. if (!data) {
  928. Logger.error('heanup eventPlaylistPlay: eventData.data is undefined or null')
  929. return
  930. }
  931. // 检查歌单播放数据结构
  932. if (data.playlistId && data.songFilePaths && data.startIndex !== undefined) {
  933. const playlistData: PlaylistEventData = {
  934. playlistId: data.playlistId as string,
  935. playlistName: data.playlistName as string,
  936. songCount: data.songCount as number,
  937. startIndex: data.startIndex as number,
  938. songFilePaths: data.songFilePaths as string[]
  939. }
  940. await this.handlePlaylistPlayRequest(
  941. playlistData.playlistId,
  942. playlistData.playlistName,
  943. playlistData.songFilePaths,
  944. playlistData.startIndex
  945. )
  946. return
  947. }
  948. Logger.error('heanup eventPlaylistPlay: 接收到无效的数据结构')
  949. });
  950. let eventRefreshSort: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_REFRESH_SORT }
  951. // 监听广播事件(通用设置配置更新)
  952. emitter.on(eventRefreshSort, (eventData: emitter.EventData) => {
  953. if(this.modeType ==4){
  954. this.doSongListTask()//获取歌单信息
  955. }
  956. });
  957. let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
  958. // 监听广播事件(通用设置配置更新)
  959. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  960. this.doChangeSetting()
  961. });
  962. let event: Callback<InterruptEvent> = (event) => {
  963. // LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  964. console.info(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  965. this.savePlaybackPosition()
  966. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  967. this.pause();
  968. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  969. console.info(`onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  970. console.info('onecold startPlayOrResumePlay 514')
  971. this.startPlayOrResumePlay();
  972. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  973. this.stop();
  974. }
  975. }
  976. this.mIjkMediaPlayer.on('audioInterrupt', event);
  977. // 音频设备断连回调处理
  978. let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  979. LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  980. if (event.reason === DeviceChangeReason.REASON_NEW_DEVICE_AVAILABLE) { // 音频设备连接
  981. } else if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  982. this.pause();
  983. }
  984. }
  985. // 订阅音频设备断开和连接事件
  986. this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  987. const eventPause: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_PAUSE }
  988. // 监听广播事件(hicar断开暂停播放)
  989. emitter.on(eventPause, (eventData: emitter.EventData) => {
  990. this.pause();
  991. });
  992. this.makeWorker()
  993. //折叠屏的屏幕显示模式变化
  994. display.on('foldDisplayModeChange', (data) => {
  995. this.doChangeBarHeight()
  996. });
  997. display.on('foldStatusChange', (data) => {
  998. Logger.info('onecold foldStatusChange ')
  999. });
  1000. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  1001. // 读取 themeMode 并同步 currentColorMode
  1002. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  1003. this.applyThemeMode(this.themeMode)
  1004. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  1005. AppStorage.setOrCreate('themeColor', themeColor);
  1006. this.themeColor = themeColor;
  1007. this.doChangeSetting()
  1008. this.windowClass.on('windowSizeChange', (size) => {
  1009. LogUtil.info('onecold windowSizeChange')
  1010. this.doChangeBarHeight()
  1011. let viewWidth = px2vp(size.width);
  1012. let viewHeight = px2vp(size.height);
  1013. if(this.isPhoneLan()){
  1014. this.is_auto_hide_progress = false
  1015. if(this.isHiCar()){
  1016. return
  1017. }
  1018. setTimeout(() => {
  1019. this.is_auto_hide_progress = true
  1020. }, 6000)
  1021. }else{
  1022. this.startAutoHide()
  1023. }
  1024. });
  1025. this.eventHub.on('onStateChange', (fg: boolean) => {
  1026. if (fg && this.curState === 'STARTED') {
  1027. this.stopPip();
  1028. }
  1029. });
  1030. }
  1031. //载入媒体库,艺术家,专辑等缓存
  1032. initLoadCache(){
  1033. this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
  1034. this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
  1035. this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
  1036. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  1037. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  1038. if(ArrayUtil.isNotEmpty(cachedList)){
  1039. this.mediaKuList = cachedList
  1040. if(this.modeType==1){
  1041. this.updateListData(this.mediaKuList)
  1042. }
  1043. }
  1044. let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
  1045. let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
  1046. if(ArrayUtil.isNotEmpty(artistCachedList)){
  1047. this.artistList = artistCachedList
  1048. let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
  1049. const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
  1050. this.artistMap = new Map(parsedArray);
  1051. // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
  1052. if(this.modeType==2){
  1053. this.updateListData(this.artistList)
  1054. }
  1055. }
  1056. let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
  1057. let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
  1058. if(ArrayUtil.isNotEmpty(albumCachedList)){
  1059. this.albumList = albumCachedList
  1060. let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
  1061. const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
  1062. this.albumMap = new Map(parsedArray);
  1063. if(this.modeType==3){
  1064. this.updateListData(this.albumList)
  1065. }
  1066. }
  1067. }
  1068. startAutoHide() {
  1069. if(this.isHiCar()){
  1070. return
  1071. }
  1072. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  1073. console.info('onecold startAutoHide')
  1074. this.is_auto_hide_progress = false
  1075. setTimeout(() => {
  1076. this.is_auto_hide_progress = true
  1077. }, 6000)
  1078. }
  1079. }
  1080. applyThemeMode(mode: number) {
  1081. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  1082. if (mode === 1) {
  1083. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  1084. } else if (mode === 2) {
  1085. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1086. }
  1087. AppStorage.setOrCreate('currentColorMode', colorMode)
  1088. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  1089. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  1090. AppStorage.setOrCreate('themeMode', mode)
  1091. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1092. // 只有强制浅色/深色时才主动设置
  1093. const context = getContext(this) as common.UIAbilityContext
  1094. context.getApplicationContext().setColorMode(colorMode)
  1095. }
  1096. initSetting() {
  1097. this.isShowPrecious = PreferencesUtil.getBooleanSync('isShowPrecious', false)
  1098. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1099. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  1100. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  1101. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, false)
  1102. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  1103. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  1104. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  1105. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  1106. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  1107. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  1108. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  1109. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, false)
  1110. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  1111. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 2)
  1112. this.isCoverTop = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP, true)
  1113. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  1114. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  1115. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  1116. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  1117. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  1118. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  1119. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  1120. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  1121. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  1122. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  1123. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  1124. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  1125. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  1126. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  1127. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  1128. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  1129. this.isCopyFileToDownLoad = PreferencesUtil.getBooleanSync(SettingPage.IS_COPYFILE_TO_DOWNLOAD, false)
  1130. if(this.volumeSmall){
  1131. this.volume = 0.5
  1132. }else{
  1133. this.volume = 1
  1134. }
  1135. //如果是hicar连接状态,这些都是false
  1136. if(this.isHiCar()){
  1137. this.isShowTitleBar = false//不显示导航栏
  1138. this.columns=4
  1139. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  1140. {
  1141. this.isShowHeader = false//二级菜单不显示头部
  1142. this.isGridMusic= false//用list不用网格
  1143. this.isCoverTopBig = false
  1144. }
  1145. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  1146. }
  1147. if (this.isSavePlayMode) {
  1148. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  1149. }
  1150. }
  1151. doChangeSetting() {
  1152. this.initSetting()
  1153. this.deleteCache(this.currentPath)
  1154. if (this.modeType === 0) {
  1155. this.getSortedFiles(this.currentPath)
  1156. }
  1157. }
  1158. doChangeBarHeight() {
  1159. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  1160. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  1161. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  1162. this.setBarHeightNormal()
  1163. }
  1164. }
  1165. onPageShow() {
  1166. this.knockController?.immersiveListening();
  1167. app.setImageCacheCount(100);
  1168. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  1169. app.setImageRawDataCacheSize(104857600);
  1170. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  1171. }
  1172. //开启线程查看各个数据库
  1173. makeWorker() {
  1174. setTimeout(() => {
  1175. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  1176. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  1177. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  1178. // workerInstance.postMessage({
  1179. // code: 1,
  1180. // data1: this.context,
  1181. // data2: this.rootPath,
  1182. // data3: this.lockPath,
  1183. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1184. // data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  1185. // });
  1186. PreferencesUtil.putSync('isFirstApp', false)
  1187. } else {
  1188. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1189. workerInstance.postMessage({ code: 3, data: this.context });
  1190. workerInstance.postMessage({ code: 4, data: this.context });
  1191. this.getHistoryList(false)
  1192. }
  1193. }, 1000)
  1194. workerInstance.onmessage = (e: MessageEvents): void => {
  1195. switch (e.data.code) {
  1196. case 101: //第一次扫描文件夹入库
  1197. ToastUtil.showToast('刷新同步数据库成功!')
  1198. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  1199. this.doAllUpdateData()
  1200. break;
  1201. case 102: //查询媒体库列表
  1202. this.isRefreshing = false
  1203. this.mediaKuList = e.data.data
  1204. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  1205. Utility.doSortListAscending(this.mediaKuList)
  1206. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  1207. if (this.modeType === 1) {
  1208. this.updateListData(this.mediaKuList)
  1209. }
  1210. PreferencesUtil.putSync('mediaKuCount', this.mediaKuList.length)
  1211. // 处理媒体库前100条记录,列表长度并存储到PreferencesUtil
  1212. if (ArrayUtil.isNotEmpty(this.mediaKuList)&&this.mediaKuList.length > 100) {
  1213. // 只保存前100条记录到缓存中
  1214. let truncatedList = this.mediaKuList.slice(0, 100);
  1215. PreferencesUtil.putSync('mediaKuList', JSON.stringify(truncatedList));
  1216. } else {
  1217. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  1218. }
  1219. break;
  1220. case 103: //收到查询艺术家列表
  1221. this.isRefreshing = false
  1222. this.artistMap = e.data.data1;
  1223. this.artistList = e.data.data2;
  1224. PreferencesUtil.putSync('artistCount', this.artistList.length)
  1225. // 处理艺术家前100条记录,列表长度并存储到PreferencesUtil
  1226. if (ArrayUtil.isNotEmpty(this.artistList)&&this.artistList.length > 100) {
  1227. // 只保存前100条记录到缓存中
  1228. let truncatedList = this.artistList.slice(0, 100);
  1229. PreferencesUtil.putSync('artistList', JSON.stringify(truncatedList));
  1230. } else {
  1231. PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
  1232. }
  1233. // 处理并缓存前60条艺术家数据
  1234. const sortedEntries = Array.from(this.artistMap.entries())
  1235. .sort((a, b) => b[1].length - a[1].length)
  1236. .slice(0, 60);
  1237. PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
  1238. break;
  1239. case 104: //收到查询专辑列表
  1240. this.isRefreshing = false
  1241. this.albumMap = e.data.data1;
  1242. this.albumList = e.data.data2
  1243. //查询完毕在启动是否自动播放
  1244. if (this.isStartAutoPlay&&this.isCanAuto) {
  1245. this.isCanAuto = false
  1246. console.info('onecold startPlayOrResumePlay 757')
  1247. this.startPlayOrResumePlay()
  1248. }
  1249. PreferencesUtil.putSync('albumCount', this.albumList.length)
  1250. // 处理专辑前100条记录,列表长度并存储到PreferencesUtil
  1251. if (ArrayUtil.isNotEmpty(this.albumList)&&this.albumList.length > 100) {
  1252. // 只保存前100条记录到缓存中
  1253. let truncatedList = this.albumList.slice(0, 100);
  1254. PreferencesUtil.putSync('albumList', JSON.stringify(truncatedList));
  1255. } else {
  1256. PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
  1257. }
  1258. const mapArrayAlbum = Array.from(this.albumMap.entries())
  1259. .sort((a, b) => b[1].length - a[1].length)
  1260. .slice(0, 60);
  1261. PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
  1262. break;
  1263. case 105: // 缓存完成后返回的元数据
  1264. this.handleWorkerMetadataPayload(e.data.data as WorkerMetadataPayload);
  1265. break;
  1266. }
  1267. };
  1268. // 在调用terminate后,执行onexit
  1269. workerInstance.onexit = (code) => {
  1270. metadataExtractionInFlight.clear();
  1271. Logger.info(TAG, 'workerInstance 线程已退出,code: ' + code);
  1272. }
  1273. workerInstance.onerror = (err: ErrorEvent) => {
  1274. metadataExtractionInFlight.clear();
  1275. console.error('workerInstance 线程执行发生异常: ' + err.message)
  1276. }
  1277. }
  1278. private handleWorkerMetadataPayload(payload: WorkerMetadataPayload | undefined): void {
  1279. if (!payload || !payload.originFilePath) {
  1280. return;
  1281. }
  1282. metadataExtractionInFlight.delete(payload.originFilePath);
  1283. if (payload.error) {
  1284. Logger.warn(TAG, `缓存文件元数据解析失败: ${payload.error}`);
  1285. return;
  1286. }
  1287. this.applyMetadataToCollections(payload.originFilePath, payload);
  1288. }
  1289. private applyMetadataToCollections(filePath: string, payload: WorkerMetadataPayload): void {
  1290. const targets: Array<VideoItem> = [];
  1291. if (this.currentSong && this.currentSong.filePath === filePath) {
  1292. targets.push(this.currentSong);
  1293. }
  1294. const collectFromList = (list?: Array<VideoItem>) => {
  1295. if (!list || list.length === 0) {
  1296. return;
  1297. }
  1298. const found = Utility.getItemByFilePath(list, filePath);
  1299. if (found) {
  1300. targets.push(found);
  1301. }
  1302. };
  1303. collectFromList(this.songList);
  1304. collectFromList(this.videoLocalList);
  1305. collectFromList(this.historyList);
  1306. collectFromList(this.favList);
  1307. const remoteManager = RemoteDriveManager.getInstance();
  1308. collectFromList(remoteManager.webDavSongs);
  1309. const updated = new Set<VideoItem>();
  1310. for (let i = 0; i < targets.length; i++) {
  1311. const target = targets[i];
  1312. if (!target || updated.has(target)) {
  1313. continue;
  1314. }
  1315. updated.add(target);
  1316. this.mergeVideoItemWithPayload(target, payload);
  1317. }
  1318. if (this.currentSong && this.currentSong.filePath === filePath) {
  1319. this.mergeVideoItemWithPayload(this.currentSong, payload);
  1320. if (payload.name) {
  1321. this.name = payload.name;
  1322. }
  1323. if (payload.artist) {
  1324. this.artist = payload.artist;
  1325. }
  1326. if (payload.pixelMapPath) {
  1327. this.cover = payload.pixelMapPath;
  1328. }
  1329. if (payload.lyricContent) {
  1330. this.applyInlineLyricContent(payload.lyricContent);
  1331. }
  1332. this.currentSong = cloneVideoItem(this.currentSong);
  1333. AppStorage.setOrCreate('currentSong', this.currentSong);
  1334. }
  1335. const primaryTarget = targets.length > 0 ? targets[0] : undefined;
  1336. if (primaryTarget) {
  1337. this.persistRemoteMetadataToDb(primaryTarget).catch((error: Error) => {
  1338. Logger.error(TAG, `缓存元数据持久化失败: ${error.message}`);
  1339. });
  1340. }
  1341. }
  1342. private assignStringMetadata(target: VideoItem, key: keyof VideoItem, value?: string | null, allowEmpty = false): void {
  1343. if (value === undefined || value === null) {
  1344. return;
  1345. }
  1346. const text = value.toString();
  1347. if (!allowEmpty && text.trim().length === 0) {
  1348. return;
  1349. }
  1350. Reflect.set(target, key as string, value);
  1351. }
  1352. private assignNumberMetadata(target: VideoItem, key: keyof VideoItem, value?: number | null): void {
  1353. if (value === undefined || value === null || Number.isNaN(value)) {
  1354. return;
  1355. }
  1356. Reflect.set(target, key as string, value);
  1357. }
  1358. private mergeVideoItemWithPayload(target: VideoItem, payload: WorkerMetadataPayload): void {
  1359. if (!target || !payload) {
  1360. return;
  1361. }
  1362. this.assignStringMetadata(target, 'name', payload.name);
  1363. this.assignStringMetadata(target, 'artist', payload.artist);
  1364. this.assignStringMetadata(target, 'album', payload.album);
  1365. this.assignStringMetadata(target, 'bit_rate', payload.bit_rate);
  1366. this.assignStringMetadata(target, 'duration', payload.duration);
  1367. this.assignStringMetadata(target, 'sampleRate', payload.sampleRate);
  1368. this.assignStringMetadata(target, 'mimeType', payload.mimeType);
  1369. this.assignStringMetadata(target, 'size', payload.size);
  1370. this.assignStringMetadata(target, 'pixelMapPath', payload.pixelMapPath);
  1371. this.assignStringMetadata(target, 'lyricContent', payload.lyricContent, true);
  1372. this.assignStringMetadata(target, 'genre', payload.genre);
  1373. this.assignStringMetadata(target, 'track', payload.track);
  1374. this.assignStringMetadata(target, 'bits_per_raw_sample', payload.bits_per_raw_sample);
  1375. this.assignStringMetadata(target, 'channels', payload.channels);
  1376. this.assignStringMetadata(target, 'channel_layout', payload.channel_layout);
  1377. this.assignStringMetadata(target, 'start_time', payload.start_time);
  1378. this.assignStringMetadata(target, 'year', payload.year);
  1379. this.assignStringMetadata(target, 'disc', payload.disc);
  1380. this.assignStringMetadata(target, 'ALBUMARTIST', payload.ALBUMARTIST);
  1381. this.assignStringMetadata(target, 'COMPOSER', payload.COMPOSER);
  1382. this.assignStringMetadata(target, 'LYRICIST', payload.LYRICIST);
  1383. this.assignStringMetadata(target, 'COMMENT', payload.COMMENT, true);
  1384. this.assignNumberMetadata(target, 'videoSize', payload.videoSize);
  1385. this.assignNumberMetadata(target, 'probe_score', payload.probe_score);
  1386. this.assignNumberMetadata(target, 'nb_streams', payload.nb_streams);
  1387. this.assignNumberMetadata(target, 'nb_programs', payload.nb_programs);
  1388. }
  1389. private mergeVideoItemFromSource(target: VideoItem, source: VideoItem): void {
  1390. if (!target || !source) {
  1391. return;
  1392. }
  1393. this.assignStringMetadata(target, 'name', source.name);
  1394. this.assignStringMetadata(target, 'artist', source.artist);
  1395. this.assignStringMetadata(target, 'album', source.album);
  1396. this.assignStringMetadata(target, 'bit_rate', source.bit_rate);
  1397. this.assignStringMetadata(target, 'duration', source.duration);
  1398. this.assignStringMetadata(target, 'sampleRate', source.sampleRate);
  1399. this.assignStringMetadata(target, 'trackCount', source.trackCount);
  1400. this.assignStringMetadata(target, 'mimeType', source.mimeType);
  1401. this.assignStringMetadata(target, 'size', source.size);
  1402. this.assignStringMetadata(target, 'pixelMapPath', source.pixelMapPath);
  1403. this.assignStringMetadata(target, 'lyricContent', source.lyricContent, true);
  1404. this.assignStringMetadata(target, 'genre', source.genre);
  1405. this.assignStringMetadata(target, 'track', source.track);
  1406. this.assignStringMetadata(target, 'bits_per_raw_sample', source.bits_per_raw_sample);
  1407. this.assignStringMetadata(target, 'channels', source.channels);
  1408. this.assignStringMetadata(target, 'channel_layout', source.channel_layout);
  1409. this.assignStringMetadata(target, 'start_time', source.start_time);
  1410. this.assignStringMetadata(target, 'year', source.year);
  1411. this.assignStringMetadata(target, 'disc', source.disc);
  1412. this.assignStringMetadata(target, 'ALBUMARTIST', source.ALBUMARTIST);
  1413. this.assignStringMetadata(target, 'COMPOSER', source.COMPOSER);
  1414. this.assignStringMetadata(target, 'LYRICIST', source.LYRICIST);
  1415. this.assignStringMetadata(target, 'COMMENT', source.COMMENT, true);
  1416. this.assignNumberMetadata(target, 'videoSize', source.videoSize);
  1417. this.assignNumberMetadata(target, 'probe_score', source.probe_score);
  1418. this.assignNumberMetadata(target, 'nb_streams', source.nb_streams);
  1419. this.assignNumberMetadata(target, 'nb_programs', source.nb_programs);
  1420. if (source.pixelMap && !target.pixelMap) {
  1421. target.pixelMap = source.pixelMap;
  1422. }
  1423. if (source.remote_rel_path && StrUtil.isEmpty(target.remote_rel_path)) {
  1424. target.remote_rel_path = source.remote_rel_path;
  1425. }
  1426. }
  1427. private async hydrateRemoteSongFromDb(item: VideoItem | undefined): Promise<void> {
  1428. if (!item || !isRemoteCloudType(item.type)) {
  1429. return;
  1430. }
  1431. const storagePath = item.remote_rel_path || WebDavUrlUtil.toStoragePath(item.filePath);
  1432. if (!storagePath) {
  1433. return;
  1434. }
  1435. try {
  1436. const cached = await this.table.queryVideoByFilePath(storagePath);
  1437. if (!cached) {
  1438. return;
  1439. }
  1440. this.mergeVideoItemFromSource(item, cached);
  1441. if (StrUtil.isEmpty(item.remote_rel_path)) {
  1442. item.remote_rel_path = storagePath;
  1443. }
  1444. if (item === this.currentSong) {
  1445. if (StrUtil.isNotEmpty(item.name)) {
  1446. this.name = item.name;
  1447. }
  1448. if (StrUtil.isNotEmpty(item.artist)) {
  1449. this.artist = item.artist!;
  1450. }
  1451. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  1452. this.cover = item.pixelMapPath!;
  1453. }
  1454. if (StrUtil.isNotEmpty(item.lyricContent) && StrUtil.isEmpty(this.lyricContent)) {
  1455. this.applyInlineLyricContent(item.lyricContent as string);
  1456. }
  1457. }
  1458. } catch (error) {
  1459. Logger.error(TAG, `hydrateRemoteSongFromDb 失败: ${(error as Error).message}`);
  1460. }
  1461. }
  1462. private applyInlineLyricContent(content: string): void {
  1463. if (StrUtil.isEmpty(content)) {
  1464. return;
  1465. }
  1466. this.lyricContent = content;
  1467. const lines = content.split('\n').map(line => line.trim());
  1468. const lyric = this.parser.parse(lines);
  1469. this.lyricController.setLyric(lyric);
  1470. this.lyricControllerXF.setLyric(lyric);
  1471. this.lyricControllerSingle.setLyric(lyric);
  1472. }
  1473. private extractParentPathFromStoragePath(path: string): string {
  1474. if (!path) {
  1475. return '';
  1476. }
  1477. const lastSlash = path.lastIndexOf('/');
  1478. if (lastSlash <= 0) {
  1479. return '';
  1480. }
  1481. return path.substring(0, lastSlash);
  1482. }
  1483. private async persistRemoteMetadataToDb(target: VideoItem): Promise<void> {
  1484. if (!this.context || !target || !isWebDavType(target.type)) {
  1485. return;
  1486. }
  1487. const storagePath = target.remote_rel_path || WebDavUrlUtil.toStoragePath(target.filePath);
  1488. if (!storagePath) {
  1489. return;
  1490. }
  1491. target.remote_rel_path = target.remote_rel_path || storagePath;
  1492. const table = new MediaTable(this.context);
  1493. await new Promise<void>((resolve) => {
  1494. table.getRdbStore(this.context as Context, () => resolve());
  1495. });
  1496. const cloneItem = cloneVideoItem(target);
  1497. cloneItem.filePath = storagePath;
  1498. cloneItem.remote_rel_path = storagePath;
  1499. cloneItem.parentPath = this.extractParentPathFromStoragePath(storagePath);
  1500. await table.saveOrUpdateWebDavItem(cloneItem);
  1501. }
  1502. onPageHide(): void {
  1503. this.knockController?.immersiveDisableListening();
  1504. }
  1505. @State isFirstStartPlay: boolean = false
  1506. //获取download_path
  1507. async mkDownLoadDir() {
  1508. const documentViewPicker = new picker.DocumentViewPicker()
  1509. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  1510. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  1511. PreferencesUtil.putSync('download_path', this.rootPath+'/')
  1512. this.currentPath = this.rootPath
  1513. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  1514. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  1515. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  1516. Logger.info('onecold rootPath = ' + this.rootPath)
  1517. Logger.info('onecold lockPath = ' + this.lockPath)
  1518. if (!FileUtil.accessSync(this.lockPath)) {
  1519. FileUtil.mkdirSync(this.lockPath)
  1520. }
  1521. if (!FileUtil.accessSync(this.favPath)) {
  1522. FileUtil.mkdirSync(this.favPath)
  1523. }
  1524. if (!FileUtil.accessSync(this.historyPath)) {
  1525. FileUtil.mkdirSync(this.historyPath)
  1526. }
  1527. this.getSortedFiles(this.rootPath).then(async () => {
  1528. this.isFavMusic = false
  1529. //穿山甲
  1530. // this.loadBannerAd(CSJUtil.getBannerID())
  1531. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  1532. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  1533. if (ArrayUtil.isEmpty(this.songList)) {
  1534. this.songList = this.getCurFileList()
  1535. } else {
  1536. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  1537. }
  1538. if (ArrayUtil.isNotEmpty(this.songList)) {
  1539. this.isFirstStartPlay = true
  1540. this.sonDataSource.pushArrayData(this.songList)
  1541. if (this.currentSong === undefined) {
  1542. this.isFirstStartPlay = false
  1543. this.currentSong = this.songList[0]
  1544. }
  1545. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  1546. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  1547. context: this.context,
  1548. autoParseMusicName: this.autoParseMusicName
  1549. });
  1550. Logger.info(TAG, `WebDAV URL同步构建完成: ${this.videoUrl}`);
  1551. this.name = this.currentSong.name
  1552. this.cover = this.currentSong.pixelMapPath
  1553. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  1554. } else {
  1555. this.name = '空空如也'
  1556. }
  1557. })
  1558. this.getFavList(false)
  1559. }
  1560. getFavList(isFavRefresh: boolean) {
  1561. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  1562. this.favList = result
  1563. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  1564. this.videoLocalList = this.favList
  1565. this.updateListData(this.videoLocalList)
  1566. }
  1567. })
  1568. }
  1569. getHistoryList(isRefresh: boolean) {
  1570. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  1571. this.historyList = result
  1572. // for (let i = 0; i < this.historyList.length; i++) {
  1573. //
  1574. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  1575. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  1576. // }
  1577. if (isRefresh) {
  1578. this.videoLocalList = this.historyList
  1579. this.updateListData(this.videoLocalList, true)
  1580. }
  1581. })
  1582. }
  1583. // 组件消失生命周期
  1584. aboutToDisappear() {
  1585. console.info('LifeCycleComponent aboutToDisappear');
  1586. this.knockController?.immersiveDisableListening();
  1587. this.curIndex = 0
  1588. emitter.off(EventConstants.EVENT_AUDIO_OPEN);
  1589. emitter.off(EventConstants.EVENT_SCAN_UPDATE);
  1590. emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
  1591. emitter.off(EventConstants.EVENT_SETTING_UPDATE);
  1592. this.mDestroyPage = true;
  1593. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  1594. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  1595. this.stop();
  1596. }
  1597. this.mIjkMediaPlayer.off('audioInterrupt');
  1598. if (workerInstance) {
  1599. workerInstance.terminate();
  1600. }
  1601. this.stopPip();
  1602. this.destroyPipController()
  1603. }
  1604. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean,openItem?:VideoItem) {
  1605. this.isFavMusic = false
  1606. console.info('onecold getSortedFiles 1 curPath '+curPath)
  1607. if (isWorkerPost) {
  1608. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1609. }
  1610. if (this.modeType !== 0) {
  1611. return
  1612. }
  1613. console.info('onecold getSortedFiles 2')
  1614. this.isCanBack = false
  1615. this.currentPath = curPath
  1616. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  1617. this.titleName = getFileDirName(this.currentPath,this.rootPath)
  1618. if (curPath === this.rootPath) {
  1619. this.rightTopImage = $r('sys.symbol.sort')
  1620. } else {
  1621. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  1622. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  1623. this.rightTopImage = $r('sys.symbol.chevron_left')
  1624. }
  1625. }
  1626. // Get the current file list and calculate its hash
  1627. this.fileList = FileUtil.listFileSync(curPath);
  1628. const currentHash = simpleHash(this.fileList);
  1629. // Check cache
  1630. const cachedValue = this.findCache(curPath);
  1631. Logger.info('onecold cachedValue = ' + cachedValue)
  1632. const cachedHash = this.findStringCache(curPath + '_hash');
  1633. const cachedDirList = this.findCache(curPath + "_dirList");
  1634. if (cachedValue !== undefined&&!this.isRefreshing) {
  1635. // this.videoLocalList = cachedValue;
  1636. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  1637. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  1638. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  1639. }
  1640. this.isRefreshing = false
  1641. this.updateListData(cachedValue)
  1642. }
  1643. if (cachedDirList !== undefined) {
  1644. this.dirList = cachedDirList
  1645. }
  1646. //通过当前hash值和缓存hash判断list有没有变化
  1647. if (cachedValue && cachedHash === currentHash) {
  1648. return;
  1649. }
  1650. this.fileList = FileUtil.listFileSync(curPath)
  1651. let directories: Array<VideoItem> = [];
  1652. let files: Array<VideoItem> = [];
  1653. for (let i = 0; i < this.fileList.length; i++) {
  1654. console.info(`The name of file: ${this.fileList[i]}`);
  1655. let path = curPath + '/' + this.fileList[i]
  1656. if (FileUtil.isDirectory(path)) {
  1657. let item: VideoItem =
  1658. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  1659. '')
  1660. if (this.isShowDir(item.name)) {
  1661. directories.push(item);
  1662. }
  1663. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1664. // Utility.doSortListAscending(directories)
  1665. } else {
  1666. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  1667. let item: VideoItem =
  1668. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  1669. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  1670. files.push(item);
  1671. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1672. // this.doSortListAscending(files)
  1673. }
  1674. }
  1675. }
  1676. }
  1677. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  1678. if (this.currentPath !== this.lockPath) {
  1679. files = result;
  1680. }
  1681. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1682. Utility.doSortListAscending(files)
  1683. if (this.currentPath === this.rootPath) {
  1684. this.dirList = directories
  1685. this.addCache(curPath + "_dirList", this.dirList);
  1686. }
  1687. //插入广告先注释掉
  1688. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  1689. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  1690. // directories.push(adItem)
  1691. // }
  1692. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  1693. this.videoLocalList = directories.concat(files);
  1694. this.updateListData(this.videoLocalList)
  1695. if (ArrayUtil.isNotEmpty(files)) {
  1696. if (this.currentPath != this.rootPath) {
  1697. if (files) {
  1698. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  1699. }
  1700. }
  1701. // 缓存结果
  1702. this.addCache(curPath, this.videoLocalList);
  1703. await this.saveCacheToStorage(); // 保存缓存至本地存储
  1704. this.addStringCache(curPath + '_hash', currentHash);
  1705. }
  1706. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  1707. for (let i = 0; i < this.videoLocalList.length; i++) {
  1708. console.info(`onecold gengxin 1: ${this.videoLocalList[i].name}`);
  1709. }
  1710. // this.setButtonStatus()
  1711. this.openMusic(isOpen, destPath,openItem)
  1712. this.isRefreshing = false
  1713. });
  1714. }
  1715. //第三方app打开天天静听导入音乐后播放
  1716. openMusic(isOpen?: boolean, destPath?: string,openItem?:VideoItem){
  1717. if (isOpen&&destPath) {
  1718. if (destPath === undefined) {
  1719. // 处理 destPath 为 undefined 的情况
  1720. return
  1721. }
  1722. if (destPath.endsWith('.lrc')) {
  1723. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  1724. if (StrUtil.isNotEmpty(this.videoUrl)) {
  1725. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  1726. this.initLyric(lyricPath);
  1727. }
  1728. return
  1729. }
  1730. if(openItem){
  1731. this.doPlay(openItem,0,false,true)
  1732. // this.isShowPlay = true
  1733. this.setShowPlayTrue()
  1734. }
  1735. }
  1736. }
  1737. //扫描文件夹入库
  1738. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  1739. const files = FileUtil.listFileSync(curPath);
  1740. let mediaItems: VideoItem[] = [];
  1741. Logger.info('onecold scanDirectory start ')
  1742. for (const file of files) {
  1743. const fPath = `${curPath}/${file}`;
  1744. if (fPath === this.lockPath) {
  1745. Logger.info(`Skipping locked path: ${fPath}`);
  1746. continue;
  1747. }
  1748. if (FileUtil.isDirectory(fPath)) {
  1749. // Recursively scan subdirectories
  1750. const subDirItems = await this.scanDirectory(fPath);
  1751. mediaItems = mediaItems.concat(subDirItems);
  1752. } else {
  1753. Logger.info('onecold scanDirectory filePath = ' + fPath)
  1754. // Process media files
  1755. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  1756. let mediaItem: VideoItem =
  1757. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1758. mediaItems.push(mediaItem);
  1759. this.table.insert(mediaItem, (id: number) => {
  1760. });
  1761. }
  1762. }
  1763. }
  1764. return mediaItems;
  1765. }
  1766. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  1767. animateTo({ duration: 666 }, () => {
  1768. this.opacityItem = 0.5;
  1769. });
  1770. setTimeout(() => {
  1771. this.videoLocalList = mList;
  1772. if (!noSort) {
  1773. if (this.modeType === 0 || this.modeType === 1) {
  1774. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1775. this.doSortType(this.sortType)
  1776. }
  1777. }
  1778. this.dataSource.pushArrayData(this.videoLocalList)
  1779. animateTo({ duration: 666 }, () => {
  1780. this.opacityItem = 1;
  1781. });
  1782. this.setButtonStatus()
  1783. }, 200);
  1784. }
  1785. getCurFileList(): Array<VideoItem> {
  1786. if(this.isSearchMode){
  1787. return this.filteredList
  1788. }
  1789. let files: Array<VideoItem> = [];
  1790. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1791. for (let i = 0; i < this.videoLocalList.length; i++) {
  1792. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  1793. files.push(this.videoLocalList[i]);
  1794. }
  1795. }
  1796. }
  1797. return files
  1798. }
  1799. setButtonStatus() {
  1800. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1801. this.isZero = false
  1802. } else {
  1803. this.isZero = true
  1804. }
  1805. if (this.currentPath !== this.rootPath &&
  1806. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  1807. this.isHasDir = true //不为空,说明有子文件夹
  1808. } else {
  1809. this.isHasDir = false
  1810. }
  1811. }
  1812. @Builder
  1813. SortMenuBuilder() {
  1814. Menu() {
  1815. MenuItem({
  1816. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  1817. content: "按艺术家升序"
  1818. })
  1819. .onClick(async () => {
  1820. this.doSortType(0)
  1821. PreferencesUtil.put(SettingPage.SORT_TYPE, 0)
  1822. this.updateListData(this.videoLocalList, true)
  1823. })
  1824. MenuItem({
  1825. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  1826. content: "按艺术家降序"
  1827. })
  1828. .onClick(async () => {
  1829. this.doSortType(1)
  1830. PreferencesUtil.put(SettingPage.SORT_TYPE, 1)
  1831. this.updateListData(this.videoLocalList, true)
  1832. })
  1833. MenuItem({
  1834. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat_size_square')),
  1835. content: "按专辑升序"
  1836. })
  1837. .onClick(async () => {
  1838. this.doSortType(2)
  1839. PreferencesUtil.put(SettingPage.SORT_TYPE, 2)
  1840. this.updateListData(this.videoLocalList, true)
  1841. })
  1842. MenuItem({
  1843. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.character_arrow_clockwise')),
  1844. content: "按专辑降序"
  1845. })
  1846. .onClick(async () => {
  1847. this.doSortType(3)
  1848. PreferencesUtil.put(SettingPage.SORT_TYPE, 3)
  1849. this.updateListData(this.videoLocalList, true)
  1850. })
  1851. MenuItem({
  1852. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  1853. content: $r('app.string.sort_by_name')
  1854. })
  1855. .onClick(async () => {
  1856. this.doSortType(4)
  1857. PreferencesUtil.put(SettingPage.SORT_TYPE, 4)
  1858. this.updateListData(this.videoLocalList, true)
  1859. })
  1860. MenuItem({
  1861. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  1862. content: '按名称降序'
  1863. })
  1864. .onClick(async () => {
  1865. this.doSortType(5)
  1866. PreferencesUtil.put(SettingPage.SORT_TYPE, 5)
  1867. this.updateListData(this.videoLocalList, true)
  1868. })
  1869. MenuItem({
  1870. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  1871. content: $r('app.string.sort_by_time')
  1872. })
  1873. .onClick(async () => {
  1874. this.doSortType(6)
  1875. PreferencesUtil.put(SettingPage.SORT_TYPE, 6)
  1876. this.updateListData(this.videoLocalList, true)
  1877. })
  1878. MenuItem({
  1879. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  1880. content: '按添加时间降序'
  1881. })
  1882. .onClick(async () => {
  1883. this.doSortType(7)
  1884. PreferencesUtil.put(SettingPage.SORT_TYPE, 7)
  1885. this.updateListData(this.videoLocalList, true)
  1886. })
  1887. }.attributeModifier(new MenuModifier())
  1888. }
  1889. @Builder
  1890. SortMenuForArtistAblumBuilder() {
  1891. Menu() {
  1892. MenuItem({
  1893. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  1894. content: $r('app.string.sort_by_name')
  1895. })
  1896. .onClick(async () => {
  1897. this.doSortType(4)
  1898. // PreferencesUtil.put(SettingPage.SORT_TYPE, 2)
  1899. this.updateListData(this.videoLocalList, true)
  1900. })
  1901. MenuItem({
  1902. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  1903. content: '按名称降序'
  1904. })
  1905. .onClick(async () => {
  1906. this.doSortType(5)
  1907. this.updateListData(this.videoLocalList, true)
  1908. })
  1909. MenuItem({
  1910. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  1911. content: '按数量升序'
  1912. })
  1913. .onClick(async () => {
  1914. this.doSortType(8)
  1915. this.updateListData(this.videoLocalList, true)
  1916. })
  1917. MenuItem({
  1918. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  1919. content: '按数量降序'
  1920. })
  1921. .onClick(async () => {
  1922. this.doSortType(9)
  1923. this.updateListData(this.videoLocalList, true)
  1924. })
  1925. }.attributeModifier(new MenuModifier())
  1926. }
  1927. doSortType(index: number) {
  1928. switch (index) {
  1929. case 0:
  1930. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1931. // 类型排序优先级
  1932. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1933. if (typeOrder !== 0) {
  1934. return typeOrder;
  1935. }
  1936. // 处理艺术家可能为undefined的字符串比较
  1937. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1938. const artistB = b.artist?.trim() || '';
  1939. return artistA.localeCompare(artistB);
  1940. });
  1941. break;
  1942. case 1:
  1943. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1944. // 类型排序优先级
  1945. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1946. if (typeOrder !== 0) {
  1947. return typeOrder;
  1948. }
  1949. // 处理艺术家可能为undefined的字符串比较
  1950. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1951. const artistB = b.artist?.trim() || '';
  1952. return artistB.localeCompare(artistA);
  1953. });
  1954. break;
  1955. case 2:
  1956. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1957. // 类型排序优先级
  1958. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1959. if (typeOrder !== 0) {
  1960. return typeOrder;
  1961. }
  1962. // 处理专辑可能为undefined的字符串比较
  1963. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1964. const albumB = b.album?.trim() || '';
  1965. return albumA.localeCompare(albumB);
  1966. });
  1967. break;
  1968. case 3:
  1969. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1970. // 类型排序优先级
  1971. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1972. if (typeOrder !== 0) {
  1973. return typeOrder;
  1974. }
  1975. // 处理专辑可能为undefined的字符串比较
  1976. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1977. const albumB = b.album?.trim() || '';
  1978. return albumB.localeCompare(albumA);
  1979. });
  1980. break;
  1981. case 4:
  1982. Utility.doSortListAscending(this.videoLocalList,this.isShowFileName)
  1983. break;
  1984. case 5:
  1985. Utility.doSortListDescending(this.videoLocalList,this.isShowFileName)
  1986. break;
  1987. case 6:
  1988. this.videoLocalList.sort((a, b) => {
  1989. // First, sort by type
  1990. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1991. if (typeOrder !== 0) {
  1992. return typeOrder;
  1993. }
  1994. // If types are the same, sort by cTime in ascending order
  1995. return a.cTime.localeCompare(b.cTime);
  1996. });
  1997. break;
  1998. case 7:
  1999. this.videoLocalList.sort((a, b) => {
  2000. // First, sort by type
  2001. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2002. if (typeOrder !== 0) {
  2003. return typeOrder;
  2004. }
  2005. // If types are the same, sort by cTime in descending order
  2006. return b.cTime.localeCompare(a.cTime);
  2007. });
  2008. break;
  2009. case 8:
  2010. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  2011. // 1. Sort by type first
  2012. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  2013. if (typeOrder !== 0) {
  2014. return typeOrder;
  2015. }
  2016. // 2. Then sort by artist count (numeric comparison)
  2017. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  2018. if(this.modeType === 2){
  2019. sortMap = this.artistMap
  2020. }else{
  2021. sortMap = this.albumMap
  2022. }
  2023. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  2024. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  2025. return aArtistCount - bArtistCount;
  2026. });
  2027. break;
  2028. case 9:
  2029. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  2030. // 1. Sort by type first
  2031. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  2032. if (typeOrder !== 0) {
  2033. return typeOrder;
  2034. }
  2035. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  2036. if(this.modeType === 2){
  2037. sortMap = this.artistMap
  2038. }else{
  2039. sortMap = this.albumMap
  2040. }
  2041. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  2042. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  2043. return bArtistCount - aArtistCount;
  2044. });
  2045. break;
  2046. }
  2047. }
  2048. showSheelDialog() {
  2049. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  2050. // this.showTips()
  2051. // return
  2052. // }
  2053. this.showAddDialog()
  2054. }
  2055. showAddDialog() {
  2056. if (this.modeType === 2 || this.modeType === 3) {
  2057. return
  2058. }
  2059. DialogHelper.showActionSheetDialog({
  2060. title: "请选择添加方式(建议歌词文件一起导入)",
  2061. sheets: [
  2062. { value: "新建文件夹", fontColor: $r('app.color.text_color') },
  2063. { value: "手动导入", fontColor: $r('app.color.text_color') },
  2064. { value: "自动导入", fontColor: $r('app.color.text_color') },
  2065. { value: "全选导入", fontColor: $r('app.color.text_color') },
  2066. ],
  2067. maskColor: Color.Transparent,
  2068. backgroundColor: $r('app.color.bg_card'),
  2069. transition: AnimationHelper.transitionInDown(555),
  2070. onAction: (index) => {
  2071. switch (index) {
  2072. case 0:
  2073. if (this.modeType === 0) {
  2074. this.showMkDialog()
  2075. } else {
  2076. ToastUtil.showToast('请切换到首页才能新建文件夹!')
  2077. }
  2078. break;
  2079. case 1:
  2080. this.callFilePickerSelectFile()
  2081. break;
  2082. case 2:
  2083. this.showTips()
  2084. break;
  2085. case 3:
  2086. this.goSelectMusic()
  2087. break;
  2088. }
  2089. }
  2090. })
  2091. }
  2092. //拉起音频
  2093. goSelectMusic() {
  2094. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  2095. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  2096. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  2097. ) {
  2098. ToastUtil.showToast('暂时不支持该设备')
  2099. return
  2100. }
  2101. try {
  2102. let documentSelectOptions = new picker.DocumentSelectOptions();
  2103. documentSelectOptions.authMode = true
  2104. documentSelectOptions.multiAuthMode = true
  2105. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  2106. let documentPicker = new picker.DocumentViewPicker(this.context);
  2107. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  2108. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  2109. this.saveVideoDatas(documentSelectResult)
  2110. }
  2111. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  2112. JSON.stringify(documentSelectResult));
  2113. }).catch((err: BusinessError) => {
  2114. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  2115. });
  2116. } catch (error) {
  2117. let err: BusinessError = error as BusinessError;
  2118. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2119. }
  2120. }
  2121. async showTips() {
  2122. try {
  2123. this.getUIContext().getPromptAction().showDialog({
  2124. title: '导入指南',
  2125. message:'用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2126. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2127. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2128. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  2129. buttons: [
  2130. {
  2131. text: '知道了',
  2132. color: '#000000'
  2133. },
  2134. ]
  2135. }, (err, data) => {
  2136. if (err) {
  2137. console.error('showDialog err: ' + err);
  2138. return;
  2139. }
  2140. console.info('showDialog success callback, click button: ' + data.index);
  2141. });
  2142. } catch (error) {
  2143. let message = (error as BusinessError).message;
  2144. let code = (error as BusinessError).code;
  2145. console.error(`showDialog args error code is ${code}, message is ${message}`);
  2146. };
  2147. // DialogHelper.showTipsDialog({
  2148. // title: '使用提示:自动导入教程',
  2149. //
  2150. // content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2151. // + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2152. // '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2153. // '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  2154. // onAction: (action) => {
  2155. // if (action == DialogAction.TWO) {
  2156. // PreferencesUtil.putSync('isFirstMusic', false)
  2157. // router.pushUrl({
  2158. // url: 'pages/ScanFilePage'
  2159. // });
  2160. // }
  2161. // }
  2162. // })
  2163. }
  2164. showMkDialog() {
  2165. DialogHelper.showTextInputDialog({
  2166. title: '新建歌单',
  2167. maskColor: Color.Transparent,
  2168. text: '',
  2169. transition: AnimationHelper.transitionInDown(666),
  2170. onChange: (text) => {
  2171. console.error("onChange: " + text);
  2172. },
  2173. onAction: (action, dialogId, content) => {
  2174. // ToastUtil.showToast('content = ' +content)
  2175. if (action == DialogAction.TWO) {
  2176. const newName = content
  2177. const newPath = this.currentPath + '/' + newName
  2178. FileUtil.mkdir(newPath, true).then(() => {
  2179. this.cache.delete(this.currentPath); // 删除目标路径缓存
  2180. this.getSortedFiles(this.currentPath)
  2181. }).catch((error: BusinessError) => {
  2182. console.error(error.message);
  2183. });
  2184. }
  2185. }
  2186. })
  2187. }
  2188. @State progress: number = 0;
  2189. async saveVideoDatas(uris:string[],isOpen?:boolean){
  2190. if (ArrayUtil.isEmpty(uris)) {
  2191. return;
  2192. }
  2193. console.info('onecold this.isCopyFileToDownLoad = ' + this.isCopyFileToDownLoad);
  2194. if(this.isCopyFileToDownLoad||this.currentPath==this.lockPath||isOpen){
  2195. this.saveVideoDatasToDownLoad(uris,isOpen)
  2196. return
  2197. }
  2198. // 初始化进度条
  2199. this.progress = 0;
  2200. DialogHelper.showLoadingProgress({
  2201. progress: this.progress,
  2202. backCancel: false,
  2203. autoCancel: false,
  2204. loadColor: $r('app.color.title_bar_bg'),
  2205. fontColor: $r('app.color.title_bar_bg')
  2206. });
  2207. // 计算处理总数用于进度计算
  2208. const totalItems = uris.length;
  2209. let processedItems = 0;
  2210. for (let i = 0; i < uris.length; i++) {
  2211. let filePath = uris[i];
  2212. try {
  2213. if (this.currentPath !== this.lockPath) { // 判断不是私密音乐,才入库
  2214. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2215. let mediaItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context,
  2216. filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2217. console.info('onecold saveVideoDatas filePath = ' + filePath)
  2218. if (!filePath.includes(this.rootPath)) {
  2219. console.info('onecold saveVideoDatas mediaItem.parentPath111 = ' + mediaItem.parentPath)
  2220. mediaItem.parentPath = this.currentPath;
  2221. }
  2222. console.info('onecold saveVideoDatas mediaItem.parentPath = ' + mediaItem.parentPath)
  2223. this.table.insert(mediaItem, (id: number) => {
  2224. // 插入完成回调
  2225. });
  2226. }
  2227. }
  2228. // 更新进度
  2229. processedItems++;
  2230. this.progress = Math.floor((processedItems / totalItems) * 100);
  2231. DialogHelper.updateLoading(' 正在处理', this.progress);
  2232. } catch (error) {
  2233. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2234. // 即使出错也更新进度
  2235. processedItems++;
  2236. this.progress = Math.floor((processedItems / totalItems) * 100);
  2237. DialogHelper.updateLoading(' 正在处理', this.progress);
  2238. }
  2239. }
  2240. // 关闭进度条
  2241. DialogHelper.closeLoading();
  2242. this.isZero = false
  2243. // 删除目标路径缓存
  2244. setTimeout(() => {
  2245. this.cache.delete(this.currentPath);
  2246. this.getSortedFiles(this.currentPath,false,uris[0],isOpen)
  2247. this.setButtonStatus()
  2248. }, 500);
  2249. }
  2250. async saveVideoDatasToDownLoad(uris: string[], isOpen?: boolean) {
  2251. if (ArrayUtil.isEmpty(uris)) {
  2252. return;
  2253. }
  2254. let newUris: string[] = [];
  2255. this.progress = 0
  2256. DialogHelper.showLoadingProgress({
  2257. progress: this.progress,
  2258. backCancel: false,
  2259. autoCancel: false,
  2260. loadColor: this.themeColor,
  2261. fontColor: this.themeColor
  2262. });
  2263. // 计算所有文件的总大小
  2264. let totalSize = 0;
  2265. for (let uri of uris) {
  2266. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  2267. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  2268. await fileIo.close(sourceFile.fd);
  2269. }
  2270. let totalRead = 0;
  2271. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  2272. Logger.info(TAG, 'destPath uri: ' + destPath);
  2273. for (let i = 0; i < uris.length; i++) {
  2274. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  2275. Logger.info(TAG, 'filePath uri: ' + filePath);
  2276. newUris.push(filePath);
  2277. try {
  2278. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  2279. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  2280. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  2281. const buffer = new ArrayBuffer(buffSize);
  2282. let len = await fileIo.read(sourceFile.fd, buffer);
  2283. while (len > 0) {
  2284. await fileIo.write(destFile.fd, buffer.slice(0, len));
  2285. totalRead += len;
  2286. // 计算总进度
  2287. this.progress = Math.floor((totalRead / totalSize) * 100);
  2288. DialogHelper.updateLoading('正在导入', this.progress);
  2289. len = await fileIo.read(sourceFile.fd, buffer);
  2290. }
  2291. await fileIo.close(sourceFile.fd);
  2292. await fileIo.close(destFile.fd);
  2293. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  2294. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2295. let mediaItem: VideoItem =
  2296. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2297. this.table.insert(mediaItem, (id: number) => {
  2298. // 删除目标路径缓存
  2299. this.cache.delete(this.currentPath);
  2300. this.getSortedFiles(this.currentPath, true, destPath, isOpen,mediaItem)
  2301. });
  2302. }
  2303. }
  2304. } catch (error) {
  2305. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2306. }
  2307. }
  2308. DialogHelper.closeLoading()
  2309. this.isZero = false
  2310. // setTimeout(() => {
  2311. // // 删除目标路径缓存
  2312. // this.cache.delete(this.currentPath);
  2313. // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
  2314. // }, 500);
  2315. Logger.info(TAG, 'scan select video result:' + newUris)
  2316. }
  2317. //拉起音频
  2318. // goSelectMusic(){
  2319. //
  2320. // try {
  2321. // let audioSelectOptions = new picker.AudioSelectOptions();
  2322. // let audioPicker = new picker.AudioViewPicker(this.context);
  2323. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  2324. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  2325. // this.saveVideoDatas(audioSelectResult)
  2326. // }
  2327. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  2328. // }).catch((err: BusinessError) => {
  2329. //
  2330. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  2331. // });
  2332. // } catch (error) {
  2333. // let err: BusinessError = error as BusinessError;
  2334. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2335. // }
  2336. //
  2337. //
  2338. //
  2339. // }
  2340. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  2341. if (!item) {
  2342. return undefined;
  2343. }
  2344. try {
  2345. let selectUris: Array<string> = [];
  2346. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  2347. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  2348. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  2349. photoSelectOptions.maxSelectNumber = 1;
  2350. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  2351. selectUris = photoSelectResult.photoUris;
  2352. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  2353. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  2354. console.info('file fd: ' + file.fd);
  2355. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  2356. let imagePath = this.context.filesDir + FileUtil.separator + name
  2357. imagePath = fileUri.getUriFromPath(imagePath)
  2358. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  2359. fileIo.copyFileSync(file.fd, file2.fd)
  2360. fileIo.closeSync(file);
  2361. fileIo.closeSync(file2);
  2362. if (item.filePath == this.currentSong?.filePath) {
  2363. this.cover = imagePath
  2364. }
  2365. if (item) {
  2366. item.pixelMapPath = imagePath
  2367. }
  2368. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  2369. if (success) {
  2370. this.doUpdateData()
  2371. console.log("onecold 更新音乐封面成功,数据库已同步");
  2372. } else {
  2373. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  2374. }
  2375. });
  2376. LogUtil.debug("onecold this.cover =" + this.cover)
  2377. return FileUtil.getFilePath(imagePath); // Return the image path here
  2378. } catch (err) {
  2379. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  2380. return undefined;
  2381. }
  2382. }
  2383. // 拉起picker选择文件管理器
  2384. async callFilePickerSelectFile(): Promise<void> {
  2385. try {
  2386. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  2387. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  2388. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  2389. } else {
  2390. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  2391. }
  2392. let documentPicker = new picker.DocumentViewPicker();
  2393. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  2394. Logger.info(TAG,
  2395. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  2396. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  2397. this.saveVideoDatas(DocumentSelectResult)
  2398. }
  2399. }).catch((err: BusinessError) => {
  2400. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  2401. });
  2402. } catch (err) {
  2403. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  2404. }
  2405. }
  2406. //重命名的对话框
  2407. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  2408. if(!item.filePath.includes(this.packName)){
  2409. ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限重命名')
  2410. return
  2411. }
  2412. DialogHelper.showTextInputDialog({
  2413. title: '重命名',
  2414. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  2415. maskColor: Color.Transparent,
  2416. backgroundColor: Color.Grey,
  2417. transition: AnimationHelper.transitionInDown(666),
  2418. onChange: (text) => {
  2419. console.error("onChange: " + text);
  2420. },
  2421. onAction: (action, dialogId, content) => {
  2422. // ToastUtil.showToast('content = ' +content)
  2423. if (action == DialogAction.TWO) {
  2424. const newName = content
  2425. const newPath = this.currentPath + '/' + newName
  2426. console.log("onecold item = " + item.type);
  2427. this.doReName(index, newName, filePath, newPath, item)
  2428. }
  2429. }
  2430. })
  2431. }
  2432. //剪切 移动到另个文件夹的对话框
  2433. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2434. Logger.info('onecold showCutDialog')
  2435. let mList: Array<string> = []
  2436. let rPath = this.rootPath
  2437. if (isCurrent) {
  2438. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2439. rPath = this.currentPath
  2440. } else {
  2441. mList = Utility.getNameList(this.dirList);
  2442. rPath = this.rootPath
  2443. }
  2444. let dataBean = new BubbleBean()
  2445. dataBean.data = mList
  2446. dataBean.color = this.themeColor
  2447. dataBean.onItemClick = (i) => {
  2448. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2449. Logger.info('newPath = ' + newPath)
  2450. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  2451. ToastUtil.showToast('移动成功')
  2452. this.table.deleteData(item, () => {
  2453. });
  2454. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2455. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2456. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2457. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2458. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2459. this.table.insert(newItem, (id: number) => {
  2460. //加入数据库
  2461. });
  2462. }
  2463. this.cache.delete(this.currentPath); // 删除原路径缓存
  2464. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2465. this.getSortedFiles(this.currentPath, true)
  2466. }).catch((error: BusinessError) => {
  2467. console.error(error.message);
  2468. });
  2469. XPopup.dismissTop()
  2470. }
  2471. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2472. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2473. popupPosition = PopupPosition.TOP
  2474. }
  2475. if (index <= 3) {
  2476. popupPosition = PopupPosition.BOTTOM
  2477. }
  2478. let pup: XPopup
  2479. if (this.isDarkMode) {
  2480. pup = XPopup.Builder()
  2481. .setPopupPosition(popupPosition)
  2482. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  2483. .setBackgroundColor(Color.Black)
  2484. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2485. .show()
  2486. } else {
  2487. pup = XPopup.Builder()
  2488. .setPopupPosition(popupPosition)
  2489. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  2490. .setBackgroundColor(Color.White)
  2491. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2492. .show()
  2493. }
  2494. }
  2495. //复制 到另个文件夹的对话框
  2496. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2497. Logger.info('onecoldv showCopyDialog')
  2498. let mList: Array<string> = []
  2499. let rPath = this.rootPath
  2500. if (isCurrent) {
  2501. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2502. rPath = this.currentPath
  2503. } else {
  2504. mList = Utility.getNameList(this.dirList);
  2505. rPath = this.rootPath
  2506. }
  2507. let dataBean = new BubbleBean()
  2508. dataBean.data = mList
  2509. dataBean.isCopy = true
  2510. dataBean.color = this.themeColor
  2511. dataBean.onItemClick = (i) => {
  2512. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2513. Logger.info('newPath = ' + newPath)
  2514. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2515. ToastUtil.showToast('复制成功')
  2516. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2517. this.getSortedFiles(this.currentPath)
  2518. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2519. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2520. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2521. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2522. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2523. this.table.insert(newItem, (id: number) => {
  2524. //加入数据库
  2525. });
  2526. }
  2527. }).catch((error: BusinessError) => {
  2528. console.error(error.message);
  2529. });
  2530. XPopup.dismissTop()
  2531. }
  2532. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2533. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2534. popupPosition = PopupPosition.TOP
  2535. }
  2536. if (index <= 3) {
  2537. popupPosition = PopupPosition.BOTTOM
  2538. }
  2539. let pup: XPopup
  2540. if (this.isDarkMode) {
  2541. pup = XPopup.Builder()
  2542. .setPopupPosition(popupPosition)
  2543. .atView(id)
  2544. .setMaxHeight('60%')
  2545. .setBackgroundColor(Color.Black)
  2546. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2547. .show();
  2548. } else {
  2549. pup = XPopup.Builder()
  2550. .setPopupPosition(popupPosition)
  2551. .atView(id)
  2552. .setMaxHeight('60%')
  2553. .setBackgroundColor(Color.White)
  2554. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2555. .show();
  2556. }
  2557. }
  2558. //重命名索引index的视频
  2559. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  2560. FileUtil.rename(oldPath, newPath).then(async () => {
  2561. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2562. if (info.type === CommonConstants.TYPE_IS_DIR) {
  2563. //如果是文件夹先删除源数据,再添加新数据
  2564. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  2565. if (success) {
  2566. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  2567. } else {
  2568. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  2569. }
  2570. });
  2571. this.scanDirectory(newPath)
  2572. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  2573. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  2574. if (success) {
  2575. console.log(" onecold 重命名成功,数据库已同步");
  2576. } else {
  2577. console.error(" onecold 重命名数据库失败原因: " + error);
  2578. }
  2579. });
  2580. }
  2581. let mediaItem: VideoItem =
  2582. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2583. this.videoLocalList[index] = mediaItem;
  2584. }
  2585. this.cache.delete(this.currentPath)
  2586. this.getSortedFiles(this.currentPath, true)
  2587. }).catch((error: BusinessError) => {
  2588. console.error(error.message);
  2589. });
  2590. }
  2591. build() {
  2592. Stack() {
  2593. this.ContentBuild()
  2594. Stack() {
  2595. this.PlayController()
  2596. }
  2597. .hitTestBehavior(HitTestMode.Transparent)
  2598. .opacity(this.barBottomOpacity)
  2599. .width('90%')
  2600. .borderRadius(20)
  2601. .margin({ bottom:DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_2IN1
  2602. ? 30 :this.bottomSafeHeight })
  2603. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  2604. .backgroundImage( this.cover)
  2605. .visibility(this.isMultiSelect ? Visibility.None : Visibility.Visible)
  2606. .backgroundImageSize( { width: '100%' })
  2607. .opacity(0.9)
  2608. .clickEffect({ level: ClickEffectLevel.HEAVY })
  2609. }
  2610. .alignContent(Alignment.Bottom)
  2611. .width('100%')
  2612. .height('100%')
  2613. }
  2614. @Builder
  2615. ContentBuild() {
  2616. Scroll() {
  2617. Column() {
  2618. Stack() {
  2619. //libraryname加上去后onKeyEvent监听不了,因为目前的解决方案是上面的XComponent,去掉libraryname
  2620. XComponent({ id: 'for_onKeyEvent',type: XComponentType.SURFACE,
  2621. controller: this.xcomponentController })
  2622. .onLoad(async (event?: object) => {
  2623. })
  2624. .focusable(true)
  2625. .height(0)
  2626. .focusOnTouch(true)
  2627. .defaultFocus(true) // 自动获取键盘焦点
  2628. .onKeyEvent((event?: KeyEvent) => {
  2629. console.info('onecold点击 onKeyEvent')
  2630. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  2631. if (!event || event.type !== KeyType.Down) {
  2632. return;
  2633. }
  2634. console.info('onecold点击 onKeyEvent event.keyCode: ' + event.keyCode)
  2635. //空格键 Space key controls pause/play
  2636. if (event.keyCode === KeyCode.KEYCODE_SPACE|| event.keyCode === KeyCode.KEYCODE_MEDIA_PLAY_PAUSE) {
  2637. this.playOrPause()
  2638. }
  2639. if (event.keyCode === KeyCode.KEYCODE_DPAD_UP) {
  2640. this.playPrevious()
  2641. }
  2642. if (event.keyCode === KeyCode.KEYCODE_DPAD_DOWN) {
  2643. this.playNext()
  2644. }
  2645. // Right-click to fast forward
  2646. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  2647. this.fastForward()
  2648. }
  2649. // Left-click to rewind
  2650. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  2651. this.backForward()
  2652. }
  2653. })
  2654. Column() {
  2655. XComponent({
  2656. id: 'xcomponentId',
  2657. type: 'surface',
  2658. libraryname: 'ijkplayer_napi',
  2659. controller: this.xcomponentController
  2660. })
  2661. .onLoad((event?: object) => {
  2662. if (!!event) {
  2663. this.initDelayPlay(event);
  2664. }
  2665. })
  2666. .onDestroy(() => {
  2667. })
  2668. .width('100%')// .width(this.videoWidth)
  2669. .aspectRatio(this.videoAspectRatio)
  2670. }
  2671. .aspectRatio(this.videoAspectRatio)
  2672. .justifyContent(FlexAlign.Center)
  2673. .backgroundColor(Color.Transparent)
  2674. .visibility(Visibility.Hidden)
  2675. .height(CommonConstants.FULL_PERCENT)
  2676. .width(CommonConstants.FULL_PERCENT)
  2677. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  2678. height:this.isLandscape?'80%': '43%',
  2679. dragBar: true,
  2680. showClose: true,
  2681. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  2682. blurStyle:BlurStyle.Thin,
  2683. backgroundColor:Color.Transparent,
  2684. title: { title: 'AB循环' }
  2685. })
  2686. Stack() {
  2687. Row() {
  2688. Blank()
  2689. .layoutWeight(1)
  2690. IndexerView(
  2691. {
  2692. indexArray: DEFAULT_INDEX,
  2693. selectedIndex: this.selectedIndex,
  2694. textSize: 12,
  2695. selectedColor: "#ff419ee5",
  2696. normalColor: "#ffa0a0a0",
  2697. floatSelectedTextColor: "#ffffff",
  2698. floatSelectedViewColor: "#ff419ee5",
  2699. onIndexChanged: (index) => {
  2700. this.listScroller.scrollToIndex(index)
  2701. }
  2702. })
  2703. .width(24)
  2704. .height("50%")
  2705. }.visibility(Visibility.None)
  2706. Column() {
  2707. // if (!this.isShowCoverHeader()) {
  2708. // this.tabTitle()
  2709. // }
  2710. if(this.twoFingerType==4){
  2711. this.getWaterView()
  2712. }else{
  2713. if(this.isGridMusic){
  2714. this.getGridView()
  2715. }else {
  2716. this.getList()
  2717. }
  2718. }
  2719. if (this.modeType ==0||this.modeType==4) {
  2720. Column() {
  2721. emptyView(this.themeColor)
  2722. }
  2723. .position({ top: 200 })
  2724. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  2725. .animation({ duration: 500 }),
  2726. TransitionEffect.scale({ x: 0, y: 0 })))
  2727. .justifyContent(FlexAlign.Center)
  2728. .opacity(this.isZero ? 1 : 0)
  2729. .visibility(this.isZero && !this.isFavMusic && !this.isHistory
  2730. ? Visibility.Visible : Visibility.None)
  2731. .animation({
  2732. duration: 500,
  2733. curve: 'ease-in-out' // 可选动画曲线
  2734. })
  2735. .width('100%')
  2736. }
  2737. }
  2738. .layoutWeight(1)
  2739. .height('100%')
  2740. this.topTitleBar()
  2741. }
  2742. .alignContent(Alignment.Top)
  2743. .layoutWeight(1)
  2744. .height('100%')
  2745. Row() {
  2746. Button(this.isAllSelected ? '反选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  2747. .width(45)
  2748. .height(45)
  2749. .fontSize(10)
  2750. .margin({ top: 10, bottom: 10, right: 6 })
  2751. .backgroundColor(this.themeColor)
  2752. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2753. .onClick(() => {
  2754. if (this.isAllSelected) {
  2755. // 全不选
  2756. this.selectedFiles = [];
  2757. } else {
  2758. // 全选
  2759. this.selectedFiles = [...this.getCurFileList()];
  2760. }
  2761. this.isAllSelected = !this.isAllSelected;
  2762. })
  2763. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  2764. .width(72)
  2765. .height(45)
  2766. .fontSize(10)
  2767. .margin({ top: 10, bottom: 10, right: 6 })
  2768. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2769. .backgroundColor(this.themeColor)
  2770. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  2771. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2772. })
  2773. .onClick(() => {
  2774. // if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  2775. this.isOneKeyTags = !this.isOneKeyTags
  2776. // }else{
  2777. // ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限批量内嵌')
  2778. // }
  2779. })
  2780. Button('合并', { type: ButtonType.Circle, stateEffect: true })
  2781. .width(45)
  2782. .height(45)
  2783. .fontSize(10)
  2784. .margin({ top: 10, bottom: 10, right: 6 })
  2785. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2786. .backgroundColor(this.themeColor)
  2787. .bindContentCover($$this.isMergeAudio, this.MergeAudioBuilder(), {
  2788. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2789. })
  2790. .onClick(() => {
  2791. if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  2792. this.isMergeAudio = !this.isMergeAudio
  2793. }else{
  2794. ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限合并')
  2795. }
  2796. })
  2797. Button('+歌单', { type: ButtonType.Circle, stateEffect: true })
  2798. .width(45)
  2799. .height(45)
  2800. .fontSize(10)
  2801. .margin({ top: 10, bottom: 10, right: 6 })
  2802. .backgroundColor(this.themeColor)
  2803. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2804. .onClick(async () => {
  2805. this.longItemFilePath = ''
  2806. await this.openAddToPlaylistDialog(this.selectedFiles)
  2807. })
  2808. // Button('乱码', { type: ButtonType.Circle, stateEffect: true })
  2809. // .width(45)
  2810. // .height(45)
  2811. // .fontSize(10)
  2812. // .margin({ top: 10, bottom: 10, right: 6 })
  2813. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2814. // .backgroundColor(this.themeColor)
  2815. // .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  2816. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2817. // })
  2818. // .onClick(() => {
  2819. // this.isFixMessy = !this.isFixMessy
  2820. // })
  2821. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  2822. // .width('35%')
  2823. // .height(60)
  2824. // .id('music_cut')
  2825. // .margin({ top: 10, bottom: 10, right: 6 })
  2826. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2827. // .backgroundColor(this.themeColor)
  2828. // .onClick(() => {
  2829. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  2830. // })
  2831. //
  2832. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  2833. // .width('35%')
  2834. // .height(60)
  2835. // .id('music_cut_current')
  2836. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  2837. // .margin({ top: 10, bottom: 10, right: 6 })
  2838. // .backgroundColor(this.themeColor)
  2839. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2840. // .onClick(() => {
  2841. //
  2842. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  2843. // })
  2844. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  2845. // .width('35%')
  2846. // .height(60)
  2847. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  2848. // .margin({ top: 10, bottom: 10, right: 6 })
  2849. // .backgroundColor(this.themeColor)
  2850. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2851. // .onClick(() => {
  2852. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  2853. // })
  2854. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  2855. .width(45)
  2856. .height(45)
  2857. .fontSize(10)
  2858. .margin({ top: 10, bottom: 10, right: 6 })
  2859. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  2860. .backgroundColor(this.themeColor)
  2861. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2862. .onClick(() => {
  2863. this.showWarnIsDelete()
  2864. })
  2865. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  2866. .width(45)
  2867. .height(45)
  2868. .fontSize(10)
  2869. .margin({ top: 10, bottom: 10, right: 6 })
  2870. .backgroundColor(this.themeColor)
  2871. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2872. .onClick(() => {
  2873. this.selectedFiles = [];
  2874. this.isAllSelected = false
  2875. this.isMultiSelect = false
  2876. })
  2877. }
  2878. .width('100%')
  2879. .justifyContent(FlexAlign.Center)
  2880. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2881. .opacity(this.isMultiSelect ? 1 : 0)
  2882. .animation({
  2883. duration: 666,
  2884. curve: 'ease-in-out' // 可选动画曲线
  2885. })
  2886. .position({ bottom: 20 }) // 将 Row 固定在底部
  2887. }
  2888. .width('100%')
  2889. .height('100%')
  2890. .alignContent(Alignment.Top)
  2891. }
  2892. .width('100%')
  2893. .height('100%')
  2894. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  2895. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  2896. .backgroundImagePosition(Alignment.Center)
  2897. .backdropBlur(this.blurValue)
  2898. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  2899. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  2900. }
  2901. }
  2902. @Builder
  2903. topTitleBar(){
  2904. Column() {
  2905. Row({ space: 15 }) {
  2906. if (!this.isSearchMode ) {
  2907. //左侧滑动按钮
  2908. Button({ type: ButtonType.Circle, stateEffect: true }) {
  2909. SymbolGlyph(this.rightTopImage)
  2910. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  2911. }
  2912. .attributeModifier(new ButtonFancyModifier(40, 40))
  2913. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  2914. .animation({ duration: 300, curve: Curve.Ease })
  2915. .onClick(() => {
  2916. this.doSwipBack()
  2917. })
  2918. .attributeModifier(new ShadowModifier())
  2919. .zIndex(0)
  2920. }else{
  2921. //左侧搜索返回按钮
  2922. Button({ type: ButtonType.Circle, stateEffect: true }) {
  2923. SymbolGlyph($r('sys.symbol.chevron_left'))
  2924. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  2925. }
  2926. .attributeModifier(new ButtonFancyModifier(40, 40))
  2927. .margin({bottom:5})
  2928. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  2929. .animation({ duration: 300, curve: Curve.Ease })
  2930. .onClick(() => {
  2931. this.isSearchMode = false
  2932. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  2933. this.searchText = ''
  2934. this.getSortedFiles(this.currentPath)
  2935. return
  2936. }
  2937. this.onSearchInput('')
  2938. })
  2939. .attributeModifier(new ShadowModifier())
  2940. .zIndex(0)
  2941. }
  2942. if (!this.isSearchMode) {
  2943. Text(this.titleName)
  2944. .margin({left:3,right:10})
  2945. .fontColor($r('app.color.text_color'))
  2946. .fontSize(this.twoFingerType==3?19:this.twoFingerType==2?17:15)
  2947. .maxLines(1)
  2948. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  2949. .layoutWeight(1)
  2950. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  2951. }
  2952. //搜索框
  2953. Search({ controller: this.searchController,value: this.searchText, placeholder: '搜索标题、艺术家...' })
  2954. .searchButton('搜索',{fontColor:this.themeColor})
  2955. .searchIcon({
  2956. src: $r('sys.media.ohos_ic_public_search_filled')
  2957. })
  2958. .cancelButton({
  2959. style: CancelButtonStyle.CONSTANT,
  2960. icon: {
  2961. src: $r('sys.media.ohos_ic_public_cancel_filled')
  2962. }
  2963. })
  2964. .layoutWeight(1)
  2965. .height(40)
  2966. .maxLength(20)
  2967. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  2968. .placeholderColor(Color.Grey)
  2969. .placeholderFont({ size: 14, weight: 400 })
  2970. .textFont({ size: 14, weight: 400 })
  2971. .onSubmit((value: string) => {
  2972. console.log('onecold onSubmit ='+value)
  2973. this.searchController.stopEditing()
  2974. this.onSearchInput(this.searchText);
  2975. })
  2976. .onChange((value: string) => {
  2977. console.log('onecold onChange ='+value)
  2978. this.onSearchInput(value);
  2979. })
  2980. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  2981. .animation({ duration: 300, curve: Curve.Ease })
  2982. //搜索按钮
  2983. if (!this.isSearchMode) {
  2984. Button({ type: ButtonType.Circle, stateEffect: true }) {
  2985. SymbolGlyph($r('sys.symbol.magnifyingglass'))
  2986. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  2987. }
  2988. .attributeModifier(new ButtonFancyModifier(40, 40))
  2989. .animation({ duration: 300, curve: Curve.Ease })
  2990. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  2991. .attributeModifier(new ShadowModifier())
  2992. .zIndex(0)
  2993. .onClick(()=>{
  2994. this.isSearchMode = true
  2995. })
  2996. //排序按钮
  2997. Button({ type: ButtonType.Circle, stateEffect: true }) {
  2998. SymbolGlyph($r('sys.symbol.list_number'))
  2999. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3000. }
  3001. .attributeModifier(new ButtonFancyModifier(40, 40))
  3002. .animation({ duration: 300, curve: Curve.Ease })
  3003. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3004. .bindMenu((this.modeType==2&&!this.isCanBack)||(this.modeType==3&&!this.isCanBack)
  3005. ?this.SortMenuForArtistAblumBuilder:this.SortMenuBuilder)
  3006. .attributeModifier(new ShadowModifier())
  3007. .zIndex(0)
  3008. //添加按钮
  3009. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3010. SymbolGlyph($r('sys.symbol.plus'))
  3011. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3012. }
  3013. .attributeModifier(new ButtonFancyModifier(40, 40))
  3014. .animation({ duration: 300, curve: Curve.Ease })
  3015. .visibility(this.modeType==0||this.modeType==1?Visibility.Visible:Visibility.None)
  3016. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3017. .bindSheet($$this.showAddSheet, this.addSheet(), {
  3018. height: SheetSize.FIT_CONTENT,
  3019. dragBar: true,
  3020. showClose: true,
  3021. preferType: SheetType.CENTER ,
  3022. title: {
  3023. title: '导入音乐'
  3024. }
  3025. })
  3026. .onClick(() => {
  3027. this.showAddSheet = !this.showAddSheet;
  3028. })
  3029. .attributeModifier(new ShadowModifier())
  3030. .zIndex(0)
  3031. }
  3032. }
  3033. }
  3034. .padding({ top: this.topSafeHeight+10, left: 10, right: 10 })
  3035. .width('100%')
  3036. }
  3037. @Builder
  3038. addSheet() {
  3039. Scroll() {
  3040. Column() {
  3041. Column() {
  3042. Row() {
  3043. Text('导入音乐复制到DownLoad目录')
  3044. .margin({ left: 18 })
  3045. .fontSize(14)
  3046. .fontColor($r('app.color.text_color'))
  3047. .fontWeight(480)
  3048. .layoutWeight(1)
  3049. Toggle({ type: ToggleType.Switch, isOn: this.isCopyFileToDownLoad })
  3050. .selectedColor(this.themeColor)
  3051. .switchPointColor(Color.White)
  3052. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  3053. .margin({ right: 18 })
  3054. .onChange((checked: boolean) => {
  3055. this.isCopyFileToDownLoad = checked;
  3056. PreferencesUtil.put(SettingPage.IS_COPYFILE_TO_DOWNLOAD, this.isCopyFileToDownLoad)
  3057. })
  3058. .width(50)
  3059. .height(30);
  3060. }
  3061. .height(88)
  3062. }
  3063. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3064. .backgroundColor($r('app.color.start_window_background'))
  3065. .borderRadius(15)
  3066. .margin({
  3067. left: 30,
  3068. right: 30,
  3069. top: 10,
  3070. bottom: 10
  3071. })
  3072. .padding(0)
  3073. .border({
  3074. color: Color.White,
  3075. width: 1.8
  3076. })
  3077. Menu() {
  3078. MenuItem({
  3079. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder_badge_plus')),
  3080. content: "新建文件夹"
  3081. })
  3082. .backgroundColor($r('app.color.silvery'))
  3083. .border({
  3084. width: { bottom: 1 },
  3085. color: '#12ec5c87'
  3086. })
  3087. .margin(10)
  3088. .padding({left:15,right:15})
  3089. .onClick(async () => {
  3090. this.showMkDialog()
  3091. this.showAddSheet = !this.showAddSheet
  3092. })
  3093. MenuItem({
  3094. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder')),
  3095. content: $r('app.string.import_from_files')
  3096. })
  3097. .padding({left:15,right:15})
  3098. .backgroundColor($r('app.color.silvery'))
  3099. .border({
  3100. width: { bottom: 1 },
  3101. color: '#12ec5c87'
  3102. })
  3103. .margin(10)
  3104. .onClick(async () => {
  3105. this.callFilePickerSelectFile()
  3106. this.showAddSheet = !this.showAddSheet
  3107. })
  3108. MenuItem({
  3109. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square')),
  3110. content: '全选导入'
  3111. // content: '从下载文件夹导入(路径:Download/' +
  3112. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  3113. })
  3114. .padding({left:15,right:15})
  3115. .backgroundColor($r('app.color.silvery'))
  3116. .border({
  3117. width: { bottom: 1 },
  3118. color: '#12ec5c87'
  3119. })
  3120. .margin(10)
  3121. .onClick(async () => {
  3122. this.goSelectMusic()
  3123. this.showAddSheet = !this.showAddSheet
  3124. })
  3125. MenuItem({
  3126. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.save')),
  3127. content: '自动导入教程'
  3128. // content: '从下载文件夹导入(路径:Download/' +
  3129. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  3130. })
  3131. .padding({left:15,right:15})
  3132. .backgroundColor($r('app.color.silvery'))
  3133. .border({
  3134. width: { bottom: 1 },
  3135. color: '#12ec5c87'
  3136. })
  3137. .margin(10)
  3138. .onClick(async () => {
  3139. this.showTips()
  3140. this.showAddSheet = !this.showAddSheet
  3141. })
  3142. }.attributeModifier(new MenuModifier())
  3143. .margin({bottom:30})
  3144. }
  3145. .layoutWeight(1)
  3146. }
  3147. }
  3148. @Builder
  3149. TagsContentCoverBuilder() {
  3150. Scroll() {
  3151. Column() {
  3152. TagsContentCover(
  3153. {
  3154. selectedFiles:this.selectedFiles,
  3155. isOneKeyTags:this.isOneKeyTags,
  3156. table:this.table,
  3157. onTagsResult:(result: boolean)=>{
  3158. this.isMultiSelect = false
  3159. if(result){//如果嵌入成功,更新数据
  3160. setTimeout(()=>{
  3161. this.doUpdateData()
  3162. },500)
  3163. }
  3164. }
  3165. }
  3166. )
  3167. }
  3168. }
  3169. .width('100%')
  3170. .height('100%')
  3171. }
  3172. @Builder
  3173. FixMessyViewBuilder() {
  3174. Scroll() {
  3175. Column() {
  3176. FixMessyView(
  3177. {
  3178. selectedFiles:this.selectedFiles,
  3179. isFixMessy:this.isFixMessy,
  3180. onFixResult:(result: boolean)=>{
  3181. this.isMultiSelect = false
  3182. if(result){//如果嵌入成功,更新数据
  3183. this.deleteCache(this.currentPath)
  3184. this.doUpdateData()
  3185. }
  3186. }
  3187. }
  3188. )
  3189. }
  3190. }
  3191. .width('100%')
  3192. .height('100%')
  3193. }
  3194. //剪辑音频
  3195. @Builder
  3196. EditAudioBuilder(item:VideoItem) {
  3197. Scroll() {
  3198. Column() {
  3199. EditAudio(
  3200. {
  3201. mVideoItem:item,
  3202. currentPath:this.currentPath,
  3203. videoUrl:this.videoUrl,
  3204. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3205. currentTime:this.currentTime,
  3206. progressValue:this.progressValue,
  3207. onBack:()=>{
  3208. this.isEditAudio = !this.isEditAudio
  3209. },
  3210. onSeeOutputPath:(outPutPath:string)=>{
  3211. this.isEditAudio = !this.isEditAudio
  3212. this.longItemFilePath = ''
  3213. this.modeType = 0
  3214. this.isShowFileName = true
  3215. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3216. },
  3217. onPlayOrPause:()=>{
  3218. if(this.videoUrl==item.filePath){
  3219. this.playOrPause()
  3220. }else{//如果不是当前播放的,则播放该文件
  3221. this.videoUrl==item.filePath
  3222. this.doPlay(item,0,false,true)
  3223. }
  3224. },
  3225. onSliderChange:(value:number)=>{
  3226. if(this.videoUrl!=item.filePath){
  3227. this.videoUrl==item.filePath
  3228. return
  3229. }
  3230. this.isSeekTo = true;
  3231. this.mDestroyPage = false;
  3232. this.showLoadIng();
  3233. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  3234. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3235. this.seekTo(seekValue + "");
  3236. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  3237. this.isSeekTo = false;
  3238. },
  3239. onResult:(result: boolean,outPath:string)=>{
  3240. if(result){//如果剪辑成功,更新数据
  3241. this.doUpdateData()
  3242. }else{
  3243. ToastUtil.showToast('剪辑失败')
  3244. }
  3245. }
  3246. }
  3247. )
  3248. }
  3249. }
  3250. .width('100%')
  3251. .height('100%')
  3252. }
  3253. //提取伴奏
  3254. @Builder
  3255. ConverterBuilder(item:VideoItem) {
  3256. Scroll() {
  3257. Column() {
  3258. AudioFormatConverter(
  3259. {
  3260. mVideoItem:item,
  3261. videoUrl:this.videoUrl,
  3262. currentPath:this.currentPath,
  3263. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3264. currentTime:this.currentTime,
  3265. progressValue:this.progressValue,
  3266. onBack:()=>{
  3267. this.isConverter = !this.isConverter
  3268. this.longItemFilePath = ''
  3269. },
  3270. onPlayOrPause:()=>{
  3271. if(this.videoUrl==item.filePath){
  3272. this.playOrPause()
  3273. }else{//如果不是当前播放的,则播放该文件
  3274. this.videoUrl==item.filePath
  3275. this.doPlay(item,0,false,true)
  3276. }
  3277. },
  3278. onSeeOutputPath:(outPutPath:string)=>{
  3279. this.isConverter = !this.isConverter
  3280. this.longItemFilePath = ''
  3281. this.modeType = 0
  3282. this.isShowFileName = true
  3283. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3284. },
  3285. onSliderChange:(value:number)=>{
  3286. if(this.videoUrl!=item.filePath){
  3287. this.videoUrl==item.filePath
  3288. return
  3289. }
  3290. this.isSeekTo = true;
  3291. this.mDestroyPage = false;
  3292. this.showLoadIng();
  3293. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3294. this.seekTo(seekValue + "");
  3295. this.isSeekTo = false;
  3296. },
  3297. onResult:(result: boolean,outPath:string)=>{
  3298. if(result){//如果成功,更新数据
  3299. this.doUpdateData()
  3300. }else{
  3301. ToastUtil.showToast('格式转化失败')
  3302. }
  3303. }
  3304. }
  3305. )
  3306. }
  3307. }
  3308. .width('100%')
  3309. .height('100%')
  3310. }
  3311. //提取伴奏
  3312. @Builder
  3313. ExtractAccBuilder(item:VideoItem) {
  3314. Scroll() {
  3315. Column() {
  3316. ExtractAccompaniment(
  3317. {
  3318. mVideoItem:item,
  3319. currentPath:this.currentPath,
  3320. videoUrl:this.videoUrl,
  3321. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3322. currentTime:this.currentTime,
  3323. progressValue:this.progressValue,
  3324. onBack:()=>{
  3325. this.isExtractAcc = !this.isExtractAcc
  3326. this.longItemFilePath = ''
  3327. },
  3328. onPlayOrPause:()=>{
  3329. if(this.videoUrl==item.filePath){
  3330. this.playOrPause()
  3331. }else{//如果不是当前播放的,则播放该文件
  3332. this.videoUrl==item.filePath
  3333. this.doPlay(item,0,false,true)
  3334. }
  3335. },
  3336. onSeeOutputPath:(outPutPath:string)=>{
  3337. this.isExtractAcc = !this.isExtractAcc
  3338. this.longItemFilePath = ''
  3339. this.modeType = 0
  3340. this.isShowFileName = true
  3341. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3342. },
  3343. onSliderChange:(value:number)=>{
  3344. if(this.videoUrl!=item.filePath){
  3345. this.videoUrl==item.filePath
  3346. return
  3347. }
  3348. this.isSeekTo = true;
  3349. this.mDestroyPage = false;
  3350. this.showLoadIng();
  3351. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3352. this.seekTo(seekValue + "");
  3353. this.isSeekTo = false;
  3354. },
  3355. onResult:(result: boolean,outPath:string)=>{
  3356. if(result){//如果成功,更新数据
  3357. this.doUpdateData()
  3358. }else{
  3359. ToastUtil.showToast('提取伴奏失败')
  3360. }
  3361. }
  3362. }
  3363. )
  3364. }
  3365. }
  3366. .width('100%')
  3367. .height('100%')
  3368. }
  3369. //AI人声分离
  3370. @Builder
  3371. AiBuilder(item:VideoItem) {
  3372. Scroll() {
  3373. Column() {
  3374. AIVoiceSeparation(
  3375. {
  3376. mVideoItem:item,
  3377. videoUrl:this.videoUrl,
  3378. currentPath:this.currentPath,
  3379. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3380. currentTime:this.currentTime,
  3381. progressValue:this.progressValue,
  3382. onBack:()=>{
  3383. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  3384. this.longItemFilePath = ''
  3385. },
  3386. onPlayOrPause:()=>{
  3387. if(this.videoUrl==item.filePath||this.isPlaying){
  3388. this.playOrPause()
  3389. }else{//如果不是当前播放的,则播放该文件
  3390. this.videoUrl==item.filePath
  3391. this.doPlay(item,0,false,true)
  3392. }
  3393. },
  3394. onPlayPath:(path:string)=>{
  3395. this.videoUrl==path
  3396. const itemP = Utility.getItemByFilePath(this.videoLocalList,path)
  3397. if(itemP)
  3398. this.doPlay(itemP,0,false,true)
  3399. },
  3400. onSeeOutputPath:(outPutPath:string)=>{
  3401. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  3402. this.longItemFilePath = ''
  3403. this.modeType = 0
  3404. this.isShowFileName = true
  3405. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3406. },
  3407. onSliderChange:(value:number)=>{
  3408. if(this.videoUrl!=item.filePath){
  3409. this.videoUrl==item.filePath
  3410. return
  3411. }
  3412. this.isSeekTo = true;
  3413. this.mDestroyPage = false;
  3414. this.showLoadIng();
  3415. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3416. this.seekTo(seekValue + "");
  3417. this.isSeekTo = false;
  3418. },
  3419. onResult:(result: boolean,outPath:string)=>{
  3420. if(result){//如果成功,更新数据
  3421. this.doUpdateData()
  3422. }else{
  3423. ToastUtil.showToast('Ai人声分离失败')
  3424. }
  3425. }
  3426. }
  3427. )
  3428. }
  3429. }
  3430. .width('100%')
  3431. .height('100%')
  3432. }
  3433. //提取视频中的音频
  3434. @Builder
  3435. extractAudioFromVideoBuilder(item:VideoItem) {
  3436. Scroll() {
  3437. Column() {
  3438. ExtractAudioFromVideo(
  3439. {
  3440. mVideoItem:item,
  3441. currentPath:this.currentPath,
  3442. videoUrl:this.videoUrl,
  3443. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3444. currentTime:this.currentTime,
  3445. progressValue:this.progressValue,
  3446. onBack:()=>{
  3447. this.isExtractAudio = !this.isExtractAudio
  3448. this.longItemFilePath = ''
  3449. },
  3450. onPlayOrPause:()=>{
  3451. if(this.videoUrl==item.filePath){
  3452. this.playOrPause()
  3453. }else{//如果不是当前播放的,则播放该文件
  3454. this.videoUrl==item.filePath
  3455. this.doPlay(item,0,false,true)
  3456. }
  3457. },
  3458. onSeeOutputPath:(outPutPath:string)=>{
  3459. this.isExtractAudio = !this.isExtractAudio
  3460. this.longItemFilePath = ''
  3461. this.modeType = 0
  3462. this.isShowFileName = true
  3463. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3464. },
  3465. onSliderChange:(value:number)=>{
  3466. if(this.videoUrl!=item.filePath){
  3467. this.videoUrl==item.filePath
  3468. return
  3469. }
  3470. this.isSeekTo = true;
  3471. this.mDestroyPage = false;
  3472. this.showLoadIng();
  3473. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3474. this.seekTo(seekValue + "");
  3475. this.isSeekTo = false;
  3476. },
  3477. onResult:(result: boolean,outPath:string)=>{
  3478. if(result){//如果成功,更新数据
  3479. this.doUpdateData()
  3480. }else{
  3481. ToastUtil.showToast('提取音频失败')
  3482. }
  3483. }
  3484. }
  3485. )
  3486. }
  3487. }
  3488. .width('100%')
  3489. .height('100%')
  3490. }
  3491. //合并音频
  3492. @Builder
  3493. MergeAudioBuilder() {
  3494. Scroll() {
  3495. Column() {
  3496. MergeAudio(
  3497. {
  3498. videoUrl:this.videoUrl,
  3499. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3500. currentPath:this.currentPath,
  3501. selectedFiles:this.selectedFiles,
  3502. currentTime:this.currentTime,
  3503. progressValue:this.progressValue,
  3504. onBack:()=>{
  3505. this.isMergeAudio = !this.isMergeAudio
  3506. this.longItemFilePath = ''
  3507. },
  3508. // onPlayPath:(path:string)=>{
  3509. // if(this.videoUrl==item.filePath){
  3510. // this.playOrPause()
  3511. // }else{//如果不是当前播放的,则播放该文件
  3512. // this.videoUrl==item.filePath
  3513. // this.doPlay(item,0,false,true)
  3514. // }
  3515. //
  3516. // },
  3517. onSeeOutputPath:(outPutPath:string)=>{
  3518. this.isMergeAudio = !this.isMergeAudio
  3519. this.longItemFilePath = ''
  3520. this.modeType = 0
  3521. this.isShowFileName = true
  3522. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3523. },
  3524. onResult:(result: boolean,outPath:string)=>{
  3525. if(result){//如果成功,更新数据
  3526. this.doUpdateData()
  3527. }else{
  3528. if(this.selectedFiles.length>=3){
  3529. ToastUtil.showToast('合并数量太多导致失败')
  3530. }else{
  3531. ToastUtil.showToast('合并失败')
  3532. }
  3533. }
  3534. }
  3535. }
  3536. )
  3537. }
  3538. }
  3539. .width('100%')
  3540. .height('100%')
  3541. }
  3542. asyncCurrentPathData() {
  3543. if (this.modeType == 0) {
  3544. workerInstance.postMessage({
  3545. code: 1,
  3546. data1: this.context,
  3547. data2: this.currentPath,
  3548. data3: this.lockPath,
  3549. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  3550. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  3551. });
  3552. }
  3553. }
  3554. // 处理文件选择的函数
  3555. handleFileSelection(item: VideoItem, checked: boolean) {
  3556. if (checked) {
  3557. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  3558. this.selectedFiles.push(item);
  3559. }
  3560. } else {
  3561. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  3562. if (index > -1) {
  3563. this.selectedFiles.splice(index, 1);
  3564. }
  3565. }
  3566. }
  3567. private deleteComponentId: number = 0
  3568. //多选删除文件
  3569. showWarnIsDelete(){
  3570. this.getUIContext().getPromptAction().openCustomDialog({
  3571. builder: () => {
  3572. this.deleteComptentBuilder()
  3573. },
  3574. isModal:true,
  3575. showInSubWindow:false,
  3576. maskColor: Color.Transparent,
  3577. dialogTransition: // 设置弹窗内容显示的过渡效果
  3578. TransitionEffect.translate({ x: 0, y: 290, z: 0 })
  3579. .animation({ duration: 600, curve: Curve.Smooth }),
  3580. maskTransition: // 设置蒙层显示的过渡效果
  3581. TransitionEffect.opacity(0)
  3582. .animation({ duration: 600, curve: Curve.Smooth })
  3583. }).then((dialogId: number) => {
  3584. this.deleteComponentId = dialogId
  3585. })
  3586. .catch((error: BusinessError) => {
  3587. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  3588. })
  3589. }
  3590. @Builder
  3591. deleteComptentBuilder(){
  3592. DeleteComptent({
  3593. selectedFiles:this.selectedFiles,
  3594. onCancel:()=>{
  3595. this.isMultiSelect = false
  3596. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  3597. },
  3598. onDeleteResult:(result: boolean)=>{
  3599. this.isMultiSelect = false
  3600. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  3601. if(result){//如果删除成功,更新数据
  3602. this.selectedFiles = [];
  3603. this.isAllSelected = false
  3604. this.cache.delete(this.currentPath);
  3605. this.getSortedFiles(this.currentPath, true);
  3606. }
  3607. }
  3608. })
  3609. }
  3610. //多选移动文件
  3611. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  3612. Logger.info('onecold showCutDialogForMultipleFiles')
  3613. let mList: Array<string> = []
  3614. let rPath = this.rootPath
  3615. if (isCurrent) {
  3616. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  3617. rPath = this.currentPath
  3618. } else {
  3619. mList = Utility.getNameList(this.dirList);
  3620. rPath = this.rootPath
  3621. }
  3622. let dataBean = new BubbleBean();
  3623. dataBean.data = mList;
  3624. dataBean.color = this.themeColor
  3625. dataBean.onItemClick = (i) => {
  3626. const newDirPath = rPath + '/' + mList[i];
  3627. // Logger.info('newDirPath = ' + newDirPath)
  3628. this.selectedFiles.forEach((item) => {
  3629. const newPath = newDirPath + '/' + item.fileName;
  3630. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  3631. ToastUtil.showToast('移动成功');
  3632. this.table.deleteData(item, () => {
  3633. this.cache.delete(this.currentPath); // 删除原路径缓存
  3634. this.cache.delete(newDirPath); // 删除目标路径缓存
  3635. this.getSortedFiles(this.currentPath, true);
  3636. });
  3637. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  3638. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  3639. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  3640. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3641. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  3642. this.table.insert(newItem, (id: number) => {
  3643. //加入数据库
  3644. });
  3645. }
  3646. }).catch((error: Error) => {
  3647. console.error(error.message);
  3648. });
  3649. });
  3650. this.isMultiSelect = false
  3651. this.selectedFiles = [];
  3652. this.isAllSelected = false
  3653. XPopup.dismissTop();
  3654. };
  3655. let pup: XPopup
  3656. if (this.isDarkMode) {
  3657. pup = XPopup.Builder()
  3658. .setPopupPosition(PopupPosition.TOP)
  3659. .atView(viewId)
  3660. .setBackgroundColor(Color.Black)
  3661. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3662. .show();
  3663. } else {
  3664. pup = XPopup.Builder()
  3665. .setPopupPosition(PopupPosition.TOP)
  3666. .atView(viewId)
  3667. .setBackgroundColor(Color.White)
  3668. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3669. .show();
  3670. }
  3671. }
  3672. /**
  3673. * 加载所有歌单
  3674. */
  3675. async loadAllPlaylists() {
  3676. try {
  3677. this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
  3678. LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
  3679. } catch (error) {
  3680. LogUtil.error('heaunp Failed to load playlists: ' + error.message)
  3681. }
  3682. }
  3683. /**
  3684. * 显示添加到歌单对话框
  3685. */
  3686. async openAddToPlaylistDialog(items: VideoItem | VideoItem[]) {
  3687. const songs = Array.isArray(items) ? items : [items]
  3688. const musicItems = songs.filter(song => song.type !== CommonConstants.TYPE_IS_DIR)
  3689. if (musicItems.length === 0) {
  3690. ToastUtil.showToast('请选择要添加的歌曲')
  3691. return
  3692. }
  3693. // 加载最新的歌单列表
  3694. await this.loadAllPlaylists()
  3695. showAddToPlaylistDialog(
  3696. musicItems,
  3697. this.allPlaylists,
  3698. async (playlistId: string) => {
  3699. // 添加歌曲到歌单
  3700. const success = await this.playlistTable?.addSongsToPlaylist(playlistId,
  3701. musicItems.map(song => song.filePath))
  3702. if (success) {
  3703. const count = musicItems.length
  3704. ToastUtil.showToast(count > 1 ? `已添加 ${count} 首歌曲` : '已添加到歌单')
  3705. // 重新加载歌单列表
  3706. await this.loadAllPlaylists()
  3707. } else {
  3708. ToastUtil.showToast(musicItems.length > 1 ? '选中的歌曲已在该歌单中' : '歌曲已在该歌单中')
  3709. }
  3710. this.longItemFilePath = ''
  3711. if (this.isMultiSelect) {
  3712. this.isMultiSelect = false
  3713. this.isAllSelected = false
  3714. this.selectedFiles = []
  3715. }
  3716. },
  3717. () => {
  3718. LogUtil.info('取消添加到歌单')
  3719. },
  3720. () => {
  3721. // 创建新歌单
  3722. showCreatePlaylistDialog(
  3723. async (name: string, description: string, coverPath?: string) => {
  3724. const success = await this.playlistTable?.createPlaylist(name, description, coverPath)
  3725. if (success) {
  3726. ToastUtil.showToast('歌单创建成功')
  3727. // 重新加载歌单列表并打开添加对话框
  3728. await this.loadAllPlaylists()
  3729. await this.openAddToPlaylistDialog(musicItems)
  3730. } else {
  3731. ToastUtil.showToast('歌单创建失败')
  3732. }
  3733. },
  3734. () => {
  3735. // 取消创建歌单
  3736. }
  3737. )
  3738. }
  3739. )
  3740. }
  3741. doFav(item: VideoItem) {
  3742. LogUtil.info('onecold doFav isFav=' + item.isFav)
  3743. let isFav = 0
  3744. if (Utility.getIsFav(this.favList, item)) {
  3745. isFav = 0
  3746. } else {
  3747. isFav = 1
  3748. }
  3749. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  3750. if (result) {
  3751. if (isFav === 1) {
  3752. ToastUtil.showToast('收藏成功');
  3753. } else {
  3754. ToastUtil.showToast('取消收藏成功');
  3755. }
  3756. this.deleteCache(this.currentPath)
  3757. this.getFavList(false)
  3758. if (this.modeType === 0 && !this.isFavMusic) {
  3759. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  3760. this.getSortedFiles(this.currentPath)
  3761. }
  3762. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  3763. workerInstance.postMessage({ code: 3, data: this.context });
  3764. workerInstance.postMessage({ code: 4, data: this.context });
  3765. }
  3766. })
  3767. }
  3768. //多选复制文件
  3769. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  3770. console.log('onecold showCopyDialogForMultipleFiles');
  3771. let mList: Array<string> = []
  3772. let rPath = this.rootPath
  3773. if (isCurrent) {
  3774. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  3775. rPath = this.currentPath
  3776. } else {
  3777. mList = Utility.getNameList(this.dirList);
  3778. rPath = this.rootPath
  3779. }
  3780. let dataBean = new BubbleBean();
  3781. dataBean.data = mList;
  3782. dataBean.isCopy = true
  3783. dataBean.color = this.themeColor
  3784. dataBean.onItemClick = (i) => {
  3785. const newDirPath = rPath + '/' + mList[i];
  3786. // Logger.info('newDirPath = ' + newDirPath)
  3787. this.selectedFiles.forEach((item) => {
  3788. const newPath = newDirPath + '/' + item.fileName;
  3789. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  3790. ToastUtil.showToast('复制成功');
  3791. this.cache.delete(newDirPath); // 删除目标路径缓存
  3792. this.getSortedFiles(this.currentPath);
  3793. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  3794. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  3795. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  3796. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3797. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  3798. this.table.insert(newItem, (id: number) => {
  3799. //加入数据库
  3800. });
  3801. }
  3802. }).catch((error: Error) => {
  3803. console.error(error.message);
  3804. });
  3805. });
  3806. this.isMultiSelect = false
  3807. this.selectedFiles = [];
  3808. this.isAllSelected = false
  3809. XPopup.dismissTop();
  3810. };
  3811. let pup: XPopup
  3812. if (this.isDarkMode) {
  3813. pup = XPopup.Builder()
  3814. .setPopupPosition(PopupPosition.TOP)
  3815. .atView(viewId)
  3816. .setBackgroundColor(Color.Black)
  3817. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3818. .show();
  3819. } else {
  3820. pup = XPopup.Builder()
  3821. .setPopupPosition(PopupPosition.TOP)
  3822. .atView(viewId)
  3823. .setBackgroundColor(Color.White)
  3824. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3825. .show();
  3826. }
  3827. }
  3828. @Builder
  3829. private DirItem(item: VideoItem, index?: number) {
  3830. Button({ type: ButtonType.Normal, stateEffect: true }) {
  3831. Row() {
  3832. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  3833. $r('app.media.music_group'))
  3834. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  3835. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  3836. .fillColor(this.themeColor)// .fontSize(33)
  3837. .alt($r('app.media.music_group'))
  3838. .borderRadius('100%')
  3839. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  3840. // .autoResize(true) // 重采样,可减少内存占用
  3841. .clip(true)
  3842. .sourceSize({width:38, height:38})
  3843. .margin({ left: 20, top: 8, bottom: 8 })
  3844. Column() {
  3845. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  3846. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  3847. .maxLines(1)// .width('88%')
  3848. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  3849. .animation({
  3850. duration: 555,
  3851. curve: 'ease-in-out',
  3852. })
  3853. .transition({
  3854. type: TransitionType.Insert,
  3855. opacity: 0,
  3856. translate: { x: 160 }
  3857. })
  3858. .margin({ left: 10, right: 20 })
  3859. .fontColor($r('app.color.text_color'))
  3860. Row() {
  3861. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  3862. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  3863. .padding({ top: 8 })
  3864. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  3865. .fontColor($r('app.color.text_color'))
  3866. .margin({ left: 10 })
  3867. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  3868. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  3869. .padding({ top: 8 })
  3870. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  3871. .fontColor($r('app.color.text_color'))
  3872. .margin({ left: 10 })
  3873. Blank()
  3874. }
  3875. }
  3876. .height('100%')
  3877. .layoutWeight(1)
  3878. .justifyContent(FlexAlign.Center)
  3879. .alignItems(HorizontalAlign.Start)
  3880. Blank()
  3881. Image($r('app.media.arrow_right'))
  3882. .height(25)
  3883. .margin({ right: 10 })
  3884. .alignSelf(ItemAlign.Center)
  3885. .id(item.filePath)
  3886. }
  3887. }
  3888. .backgroundColor(Color.Transparent)
  3889. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  3890. .width('100%')
  3891. .reuseId('dir_item')
  3892. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  3893. .opacity(this.opacityItem) // 绑定透明度
  3894. }
  3895. isShowDir(dirName: string) {
  3896. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  3897. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  3898. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  3899. if (dirName === undefined) {
  3900. return true
  3901. }
  3902. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  3903. return this.isShowSimi
  3904. }
  3905. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  3906. return this.isShowFAV
  3907. }
  3908. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  3909. return this.isShowHistory
  3910. }
  3911. return true
  3912. }
  3913. @State opacityItem: number = 1; // 控制透明度的状态变量
  3914. @Builder
  3915. private MusicItem(item: VideoItem, index?: number) {
  3916. Button({ type: ButtonType.Normal, stateEffect: true }) {
  3917. Row() {
  3918. Stack() {
  3919. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  3920. .fillColor(this.themeColor)
  3921. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  3922. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  3923. .alt($r('app.media.music_red'))
  3924. .borderRadius(this.isCoverRectangle?13:'100%')
  3925. .clip(true)
  3926. .draggable(false)
  3927. .sourceSize({width:38, height:38})
  3928. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  3929. // .autoResize(true) // 重采样,可减少内存占用
  3930. .opacity(this.opacityItem)// 绑定透明度
  3931. .margin({ left: 20 })
  3932. .gesture(LongPressGesture()
  3933. .onAction(async () => {
  3934. //如果是专辑和艺术家的首页,不能长按
  3935. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  3936. return
  3937. //如果是我的收藏 最近播放等也不能长按
  3938. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3939. item.name === LocalMusic.STR_HISTORY_MUSIC
  3940. )
  3941. return
  3942. this.longItemFilePath = item.filePath
  3943. this.tempLyricContent = await this.getLyricContent(item)
  3944. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  3945. })
  3946. .onActionEnd((event: GestureEvent) => {
  3947. }))
  3948. .onClick(()=>{
  3949. if (this.isMultiSelect) {
  3950. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3951. this.handleFileSelection(item, !isChecked);
  3952. } else {
  3953. this.doPlay(item,index)
  3954. this.setShowPlayTrue()
  3955. }
  3956. })
  3957. }
  3958. Column() {
  3959. Column() {
  3960. Text(this.isShowFileName?item.fileName :item.name)
  3961. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  3962. .maxLines(1)
  3963. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  3964. .animation({
  3965. duration: 555,
  3966. curve: 'Linear',
  3967. })
  3968. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3969. $r('app.color.text_color'))
  3970. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  3971. .padding({right:25})
  3972. .bindPopup(this.longItemFilePath === item.filePath, {
  3973. builder: this.MenuBuilder(item,index,item.filePath),
  3974. placement: Placement.Top,
  3975. // autoCancel: true,
  3976. mask: {color:'#33000000'},
  3977. // popupColor: Color.Yellow,
  3978. enableArrow: false,//是否显示箭头
  3979. showInSubWindow: false,
  3980. onStateChange: (e) => {
  3981. if (!e.isVisible) {
  3982. this.longItemFilePath = ''
  3983. this.tempLyricContent = ''
  3984. }
  3985. }
  3986. })
  3987. .gesture(LongPressGesture()
  3988. .onAction(async () => {
  3989. //如果是专辑和艺术家的首页,不能长按
  3990. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  3991. return
  3992. //如果是我的收藏 最近播放等也不能长按
  3993. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3994. item.name === LocalMusic.STR_HISTORY_MUSIC
  3995. )
  3996. return
  3997. this.longItemFilePath = item.filePath
  3998. this.tempLyricContent = await this.getLyricContent(item)
  3999. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4000. })
  4001. .onActionEnd((event: GestureEvent) => {
  4002. })
  4003. )
  4004. Row() {
  4005. Column(){
  4006. Text(item.md5Str?.includes('Lossless')?
  4007. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4008. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  4009. .padding({ top: 3,right:6,left:6,bottom:3 })
  4010. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4011. $r('app.color.text_color'))
  4012. .fontWeight(500)
  4013. .borderRadius(12)
  4014. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  4015. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4016. .backgroundColor('#FFC107')
  4017. }
  4018. .padding({ top: 8 })
  4019. Text(StrUtil.isEmpty(item.artist) ? item.duration
  4020. :this.twoFingerType==2? item.artist +' ' + item.duration
  4021. : item.artist + ' ' + item?.duration)
  4022. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4023. .padding({ top: 8 ,right:25})
  4024. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  4025. .maxLines(1)
  4026. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4027. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4028. Color.Gray)
  4029. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4030. Blank()
  4031. Text(this.isShowFileName?item.duration:item.size)
  4032. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4033. .padding({ top: 8 })
  4034. .maxLines(1)
  4035. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  4036. ? Visibility.Visible : Visibility.None)
  4037. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4038. Color.Gray)
  4039. .margin({ left: StrUtil.isEmpty(item.artist) ?0:10 })
  4040. }
  4041. .gesture(LongPressGesture()
  4042. .onAction(async () => {
  4043. //如果是专辑和艺术家的首页,不能长按
  4044. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4045. return
  4046. //如果是我的收藏 最近播放等也不能长按
  4047. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4048. item.name === LocalMusic.STR_HISTORY_MUSIC
  4049. )
  4050. return
  4051. this.longItemFilePath = item.filePath
  4052. this.tempLyricContent = await this.getLyricContent(item)
  4053. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4054. })
  4055. .onActionEnd((event: GestureEvent) => {
  4056. })
  4057. )
  4058. }
  4059. .height('100%')
  4060. .width('100%')
  4061. .margin({ right: 10 })
  4062. .justifyContent(FlexAlign.Center)
  4063. .alignItems(HorizontalAlign.Start)
  4064. }
  4065. .height('100%')
  4066. .margin({ left: 5 })
  4067. .layoutWeight(1)
  4068. Column() {
  4069. Checkbox({ name: 'checkbox' + index })
  4070. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  4071. .selectedColor(this.themeColor)
  4072. .shape(CheckBoxShape.CIRCLE)
  4073. .opacity(this.isMultiSelect ? 1 : 0)
  4074. .animation({
  4075. duration: 666,
  4076. curve: 'Smooth' // 可选动画曲线
  4077. })
  4078. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  4079. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  4080. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  4081. .width(22)
  4082. .height(22)
  4083. ImageAnimator()
  4084. .images(this.imagesF)// 动画数组
  4085. .duration(1000)// 持续
  4086. .state(this.animationState)// 动画状态
  4087. .fillMode(FillMode.Forwards)
  4088. .width(18)
  4089. .margin({ right: 20, top: 8, bottom: 8 })
  4090. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  4091. Visibility.None)
  4092. .height(18)
  4093. .iterations(-1) // 播放次数
  4094. }
  4095. }
  4096. }
  4097. .backgroundColor(Color.Transparent)
  4098. .width('100%')
  4099. .reuseId('file_item')
  4100. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  4101. }
  4102. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  4103. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  4104. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  4105. direction: Direction.Ltr,
  4106. buttonPadding:{top:12,bottom:12},
  4107. backgroundColor: Color.Transparent,
  4108. fontSize:14,
  4109. selectedFontSize:15,
  4110. selectedFontColor:Color.White,
  4111. selectedBackgroundColor: this.themeColor,
  4112. localizedTextPadding: {
  4113. end: LengthMetrics.vp(20),
  4114. start: LengthMetrics.vp(20)
  4115. }
  4116. })
  4117. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  4118. //当胶囊按钮的选择发生变化时调用此函数
  4119. capsuleSelectedIndexesChanged() {
  4120. this.modeType = this.tabSelectedIndexes[0]
  4121. }
  4122. @Builder
  4123. tabTitle() {
  4124. Column({ space: 2 }) {
  4125. SegmentButton({ options: this.tabOptions, selectedIndexes: $tabSelectedIndexes })
  4126. Line()
  4127. .width('100%')
  4128. .height(1)
  4129. .backgroundColor($r('app.color.index_background'))
  4130. .opacity(this.barOpacity)
  4131. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  4132. }
  4133. .width('100%')
  4134. .height(this.topBarHeight)
  4135. .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  4136. }
  4137. // @Builder
  4138. // tabTitle() {
  4139. // Column() {
  4140. // // 使用 Stack 布局来实现绝对定位效果
  4141. // Stack() {
  4142. // // 背景动画容器
  4143. // Row() {
  4144. // ForEach(this.tabs, (i: string, index) => {
  4145. // Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  4146. // Flex()
  4147. // .backgroundColor(this.isDarkMode ? $r('app.color.tab_item_bg') : this.themeColor)
  4148. // .borderRadius(20)
  4149. // .padding(10)
  4150. // .margin(6)
  4151. // .width('100%')
  4152. // .height('100%')
  4153. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  4154. // .visibility(this.modeType === index ? Visibility.Visible : Visibility.None)
  4155. // .opacity(this.modeType === index ? 1 : 0)
  4156. // .animation({
  4157. // duration: 666,
  4158. // playMode: PlayMode.Normal,
  4159. // curve: 'ease-in-out'
  4160. // });
  4161. // }
  4162. // .layoutWeight(1)
  4163. // .margin({
  4164. // left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5,
  4165. // right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5, bottom: 1
  4166. // });
  4167. // });
  4168. // }
  4169. // .width('100%')
  4170. // .height(50);
  4171. //
  4172. // // 导航栏容器
  4173. // Row() {
  4174. // ForEach(this.tabs, (item: string, index) => {
  4175. // Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  4176. // Text(item)
  4177. // .fontSize(16)
  4178. // .fontColor(this.modeType === index ? Color.White : $r('app.color.text_color'))
  4179. // .padding(15)
  4180. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  4181. // .onClick(() => {
  4182. // this.modeType = index;
  4183. // // this.onModeChange();
  4184. // });
  4185. // }
  4186. // .layoutWeight(1)
  4187. // .stateStyles({
  4188. // pressed: { opacity: 0.6 } // 按压反馈
  4189. // });
  4190. // });
  4191. // }
  4192. // .width('100%')
  4193. // .height(this.topBarHeight)
  4194. // .opacity(this.barOpacity)
  4195. // .backgroundColor(Color.Transparent);
  4196. //
  4197. // }
  4198. // .width('100%')
  4199. // .height(this.topBarHeight)
  4200. // .opacity(this.barOpacity)
  4201. //
  4202. // Line()
  4203. // .width('100%')
  4204. // .height(1)
  4205. // .backgroundColor($r('app.color.index_background'))
  4206. // .opacity(this.barOpacity)
  4207. // .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  4208. // }
  4209. // .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  4210. // }
  4211. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  4212. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  4213. isShowCoverHeader() {
  4214. if (!this.isShowHeader) {
  4215. return false
  4216. }
  4217. if (this.modeType == 0) {
  4218. if (this.isHistory || this.isFavMusic) {
  4219. return true
  4220. }
  4221. if (this.currentPath != this.rootPath) {
  4222. return true
  4223. }
  4224. }
  4225. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  4226. }
  4227. getCoverTitleBg(): ResourceStr | image.PixelMap {
  4228. if (this.isCustomizeBg) {
  4229. return ('rgba(255,255,255,0.2)')
  4230. }
  4231. if (this.isDarkMode) {
  4232. return $r('app.color.user_center_card_background')
  4233. }
  4234. return this.currentTitleCover
  4235. }
  4236. // 第二步:popup构造器定义弹框内容
  4237. @Builder popupBuilder() {
  4238. Column({ space: 2 }) {
  4239. Text('友情提示:双指缩放可以放大缩小列表')
  4240. .fontSize(12)
  4241. .fontWeight(FontWeight.Regular)
  4242. .fontColor($r('app.color.text_color'))
  4243. }
  4244. .justifyContent(FlexAlign.SpaceAround)
  4245. .width(220)
  4246. .height(55)
  4247. .padding(15)
  4248. }
  4249. //搜索功能的实现
  4250. @State searchText: string = ''; // 用户输入内容
  4251. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  4252. @State isSearchMode: boolean = false
  4253. // 实时搜索逻辑(带防抖)
  4254. private onSearchInput(value: string) {
  4255. this.searchText = value.trim();
  4256. let mSearchList: Array<VideoItem> = []
  4257. switch (this.modeType) {
  4258. case 0:
  4259. case 1:
  4260. mSearchList = this.mediaKuList
  4261. break;
  4262. case 2:
  4263. mSearchList = this.artistList
  4264. break;
  4265. case 3:
  4266. mSearchList = this.albumList
  4267. break;
  4268. default :
  4269. mSearchList = this.videoLocalList
  4270. break;
  4271. }
  4272. // 新增条件判断:空输入时显示所有数据
  4273. if (this.searchText === '') {
  4274. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  4275. } else {
  4276. this.filteredList = mSearchList.filter((item: VideoItem) => {
  4277. //支持模糊匹配和艺术家 专辑匹配
  4278. const regex = new RegExp(this.searchText.toLowerCase().replace(/\s+/g, '.*'), 'i');
  4279. return regex.test(item.name.toLowerCase())||
  4280. regex.test(item.fileName?.toLowerCase() ?? "") ||
  4281. regex.test(item.artist?.toLowerCase() ?? "") ||
  4282. regex.test(item.album?.toLowerCase() ?? "")
  4283. });
  4284. }
  4285. this.updateListData(this.filteredList);
  4286. // this.isSearchMode = false; // 根据业务需求决定是否启用
  4287. }
  4288. @State dragItem: number = -1
  4289. @State scaleItem: number = -1
  4290. @State neighborItem: number = -1
  4291. @State neighborScale: number = -1
  4292. @State offsetY: number = 0
  4293. private dragRefOffset: number = 0
  4294. private ITEM_INTV: number = 78
  4295. scaleSelect(item: number): number {
  4296. if (this.scaleItem === item) {
  4297. return 1.05
  4298. } else if (this.neighborItem === item) {
  4299. return this.neighborScale
  4300. } else {
  4301. return 1
  4302. }
  4303. }
  4304. itemMove(index: number, newIndex: number): void {
  4305. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  4306. return;
  4307. }
  4308. let tmp = this.videoLocalList.splice(index, 1);
  4309. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  4310. this.dataSource.pushArrayData(this.videoLocalList)
  4311. if(this.modeType==4&&this.playlistTable){
  4312. updateAllSongsSortOrder(this.playlistTable, this.videoLocalList,this.currentSongListID)
  4313. }
  4314. }
  4315. //瀑布流布局 支持双指缩放
  4316. @State columns: number = 2;
  4317. @State waterFlowScale: number = 1;
  4318. @State imageScale: number = 1;
  4319. @State waterFlowOpacity: number = 1;
  4320. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  4321. private columnChanged: boolean = false;
  4322. private oldColumn: number = this.columns;
  4323. private pinchTime: number = 0;
  4324. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  4325. changeColumns(scale: number) {
  4326. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  4327. this.columns--;
  4328. this.columnChanged = true;
  4329. } else if (scale < 1 && this.columns < 4) {
  4330. this.columns++;
  4331. this.columnChanged = true;
  4332. }
  4333. }
  4334. @Builder
  4335. getWaterView(){
  4336. Scroll(this.scroller) {
  4337. Column() {
  4338. Blank().height(this.topSafeHeight + 55)
  4339. WaterFlow({
  4340. scroller:this.waterScroller,
  4341. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  4342. }) {
  4343. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  4344. FlowItem() {
  4345. this.MusicWaterCardItem(item,index)
  4346. }
  4347. .width('100%')
  4348. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  4349. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  4350. {
  4351. preview: MenuPreviewMode.IMAGE,
  4352. previewAnimationOptions: { scale: [0.8, 1.0] },
  4353. })
  4354. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  4355. {
  4356. preview: MenuPreviewMode.IMAGE,
  4357. previewAnimationOptions: { scale: [0.8, 1.0] },
  4358. })
  4359. .transition(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }))
  4360. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  4361. TransitionEffect.scale({ x: 0, y: 0 })))
  4362. .gesture(
  4363. GestureGroup(GestureMode.Exclusive,
  4364. SwipeGesture({ direction: SwipeDirection.Horizontal })
  4365. .onAction((event: GestureEvent) => {
  4366. if (event) {
  4367. // this.sideBarController.openSideBar()
  4368. }
  4369. }),
  4370. TapGesture({ count: 1, fingers: 1 })
  4371. .onAction(async () => {
  4372. })
  4373. )
  4374. )
  4375. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  4376. }
  4377. // .columnsTemplate('repeat(auto-fit, 160)')
  4378. .id('waterflow') // 设置id用于截图
  4379. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  4380. .columnsGap(12) // 列间距
  4381. .rowsGap(16) // 行间距
  4382. .cachedCount(6)
  4383. .padding({bottom:this.bottomBarHeight+10})
  4384. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4385. .animation({ duration: 500, curve: Curve.Ease }))
  4386. .scrollBar(BarState.Off)
  4387. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  4388. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  4389. .edgeEffect(EdgeEffect.Spring, { alwaysEnabled: true })
  4390. .width('90%')
  4391. .height('100%')
  4392. .opacity(this.waterFlowOpacity)
  4393. .scale({
  4394. x: this.waterFlowScale,
  4395. y: this.waterFlowScale,
  4396. centerX: 0,
  4397. centerY: 0
  4398. })
  4399. .onAppear(() => {
  4400. this.scroller.scrollEdge(Edge.Top)
  4401. })
  4402. .nestedScroll({
  4403. scrollForward: NestedScrollMode.PARENT_FIRST,
  4404. scrollBackward: NestedScrollMode.SELF_FIRST
  4405. })
  4406. .priorityGesture(
  4407. PinchGesture()
  4408. .onActionStart((event: GestureEvent) => {
  4409. // 双指捏合手势识别成功时截图
  4410. this.pinchTime = event.timestamp;
  4411. this.columnChanged = false;
  4412. this.oldColumn = this.columns;
  4413. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  4414. if (error) {
  4415. console.info('error:' + JSON.stringify(error));
  4416. return;
  4417. }
  4418. this.waterFlowSnapshot = pixmap;
  4419. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  4420. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  4421. if (this.oldColumn ===4) {
  4422. this.twoFingerType =3
  4423. this.isGridMusic = true
  4424. }else if (this.oldColumn ===1) {
  4425. this.twoFingerType =1
  4426. this.isGridMusic = false
  4427. }
  4428. return;
  4429. }
  4430. })
  4431. })
  4432. .onActionUpdate((event: GestureEvent) => {
  4433. // 手势更新:处理缩放逻辑和视觉效果
  4434. // 边界限制:防止超出列数范围时继续缩放
  4435. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  4436. return;
  4437. }
  4438. // 节流处理:避免过于频繁的更新,提升性能
  4439. if (event.timestamp - this.pinchTime < 10000000) {
  4440. return;
  4441. }
  4442. this.pinchTime = event.timestamp;
  4443. this.waterFlowScale = event.scale;
  4444. this.imageScale = event.scale;
  4445. // 根据缩放比例设置WaterFlow透明度
  4446. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  4447. this.waterFlowOpacity *= 3;
  4448. if (!this.columnChanged) {
  4449. this.changeColumns(event.scale);
  4450. }
  4451. // 列数改变后的缩放比例调整:避免出现空白区域
  4452. if (this.columnChanged) {
  4453. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  4454. // 限制缩放范围,确保视觉效果自然
  4455. if (event.scale < 1) {
  4456. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  4457. } else {
  4458. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  4459. }
  4460. }
  4461. })
  4462. .onActionEnd((event: GestureEvent) => {
  4463. // 手势结束:执行归位动画并保存状态
  4464. // 执行归位动画:平滑过渡到正常状态
  4465. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  4466. this.waterFlowScale = 1;
  4467. this.waterFlowOpacity = 1;
  4468. })
  4469. // 持久化保存当前列数:下次启动时恢复
  4470. PreferencesUtil.putSync('lastColumns', this.columns);
  4471. })
  4472. )
  4473. //允许拖拽音乐和视频到List或Grid上自动导入视频
  4474. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  4475. .onDrop((event?: DragEvent) => {
  4476. try {
  4477. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  4478. if (dragData !== undefined) {
  4479. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  4480. if (records.length > 0) {
  4481. for (let i = 0; i < records.length; i++) {
  4482. let types = records[i].getTypes();
  4483. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  4484. const fileUriUds =
  4485. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  4486. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  4487. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  4488. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  4489. this.targetFile = fileUriUds.oriUri;
  4490. this.saveVideoDatas([this.targetFile])
  4491. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  4492. }
  4493. }
  4494. }
  4495. } else {
  4496. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  4497. }
  4498. } else {
  4499. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  4500. }
  4501. } catch (error) {
  4502. const err = error as BusinessError;
  4503. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  4504. }
  4505. })
  4506. }
  4507. }
  4508. .scrollBar(BarState.Off)
  4509. }
  4510. //瀑布流卡片布局
  4511. @Builder
  4512. private MusicWaterCardItem(item: VideoItem, index: number) {
  4513. Button({ type: ButtonType.Normal, stateEffect: false }) {
  4514. Stack() {
  4515. Column() {
  4516. Image(item.pixelMapPath)
  4517. .backgroundImageSize(ImageSize.Auto)
  4518. .borderRadius({
  4519. topLeft: 12,
  4520. topRight : 12,
  4521. bottomLeft: 0,
  4522. bottomRight: 0
  4523. })
  4524. .draggable(false)// 禁止长按手势拖动
  4525. .autoResize(true) // 重采样,可减少内存占用
  4526. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4527. .width('100%')
  4528. .height('auto')
  4529. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  4530. .objectFit(ImageFit.Auto)
  4531. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  4532. height: '99%' ,
  4533. dragBar: true,
  4534. onDisappear: () => {
  4535. this.longItemFilePath = '';
  4536. this.tempLyricContent = ''
  4537. },
  4538. showClose: true,
  4539. preferType: SheetType.CENTER ,
  4540. title: { title: '编辑标签' }
  4541. })
  4542. .draggable(false)
  4543. .opacity(this.opacityItem)// 绑定透明度
  4544. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4545. // .animation({ duration: 500, curve: Curve.Ease }))
  4546. .animation({
  4547. duration: 666,
  4548. curve: 'ease-in-out' // 可选动画曲线
  4549. })
  4550. .margin({
  4551. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4552. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4553. })
  4554. Column() {
  4555. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4556. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  4557. .maxLines(1)
  4558. .fontWeight(FontWeight.Bold)
  4559. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4560. .animation({
  4561. duration: 555,
  4562. curve: 'Linear',
  4563. })
  4564. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  4565. height: '95%',
  4566. dragBar: true,
  4567. showClose: true,
  4568. onDisappear: () => {
  4569. this.longItemFilePathDetail = '';
  4570. },
  4571. blurStyle:BlurStyle.Thin,
  4572. backgroundColor:Color.Transparent,
  4573. preferType: SheetType.CENTER ,
  4574. title: { title: '详情' }
  4575. })
  4576. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4577. $r('app.color.text_color'))
  4578. Column() {
  4579. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  4580. .fontSize(11)
  4581. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  4582. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4583. .fontColor($r('app.color.text_color'))
  4584. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  4585. .fontSize(11)
  4586. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  4587. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4588. .fontColor($r('app.color.text_color'))
  4589. Row(){
  4590. Column(){
  4591. Text(item.md5Str?.includes('Lossless')?
  4592. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4593. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  4594. .padding({ top: 3,right:6,left:6,bottom:3 })
  4595. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4596. $r('app.color.text_color'))
  4597. .fontWeight(500)
  4598. .borderRadius(12)
  4599. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4600. .backgroundColor('#FFC107')
  4601. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  4602. }
  4603. .margin({ top: 2 ,right:6})
  4604. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  4605. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  4606. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  4607. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  4608. .maxLines(1)
  4609. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4610. .margin({ top: 2})
  4611. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  4612. || item.type == CommonConstants.TYPE_IS_ALBUM
  4613. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4614. .fontWeight(FontWeight.Medium)
  4615. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4616. $r('app.color.text_color'))
  4617. }
  4618. }
  4619. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  4620. }
  4621. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  4622. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  4623. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  4624. .width('100%')
  4625. .justifyContent(FlexAlign.Center)
  4626. .margin({
  4627. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4628. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4629. })
  4630. }
  4631. .width('100%')
  4632. .borderRadius(12)
  4633. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  4634. .backgroundImageSize({ height: '100%', width: '100%' })
  4635. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  4636. .animation({ curve: Curve.Sharp, duration: 300 })
  4637. Checkbox({ name: 'checkbox' + index })
  4638. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  4639. .selectedColor(this.themeColor)
  4640. .shape(CheckBoxShape.CIRCLE)
  4641. .opacity(this.isMultiSelect ? 1 : 0)
  4642. .animation({
  4643. duration: 666,
  4644. curve: 'Smooth' // 可选动画曲线
  4645. })
  4646. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  4647. Visibility.None)
  4648. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  4649. .margin({ left: 20, top: 8, bottom: 8 })
  4650. .width(38)
  4651. .height(38)
  4652. }
  4653. }
  4654. .backgroundColor(Color.Transparent)
  4655. .width('100%')
  4656. .height('auto')
  4657. .padding({top:2})
  4658. .shadow({
  4659. radius: 10,
  4660. type: ShadowType.BLUR,
  4661. color: 'on_primary'
  4662. })
  4663. .reuseId('card_item')
  4664. .onClick(() => {
  4665. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  4666. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4667. this.handleFileSelection(item, !isChecked);
  4668. } else {
  4669. this.doPlay(item, index)
  4670. }
  4671. })
  4672. }
  4673. // Grid布局的开始
  4674. private dragRefOffSetX: number = 0;
  4675. private dragRefOffSetY: number = 0;
  4676. private FIX_VP_X: number = 180;
  4677. private FIX_VP_Y: number = 84;
  4678. isDraggable(index: number): boolean {
  4679. return index >= 0;
  4680. }
  4681. getRowEnd(item: number) {
  4682. if (item.toString() === '0') {
  4683. return 1;
  4684. } else {
  4685. return 0;
  4686. }
  4687. }
  4688. isInLeft(index: number) {
  4689. return index % 2 == 0;
  4690. }
  4691. down(index: number): void {
  4692. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  4693. return;
  4694. }
  4695. this.offsetY -= this.FIX_VP_Y;
  4696. this.dragRefOffSetY += this.FIX_VP_Y;
  4697. this.itemMove(index, index + 1);
  4698. }
  4699. up(index: number): void {
  4700. if (!this.isDraggable(index - 2)) {
  4701. return;
  4702. }
  4703. this.offsetY += this.FIX_VP_Y;
  4704. this.dragRefOffSetY -= this.FIX_VP_Y;
  4705. this.itemMove(index, index - 1);
  4706. }
  4707. left(index: number): void {
  4708. if (this.isInLeft(index)) {
  4709. return;
  4710. }
  4711. if (!this.isDraggable(index - 1)) {
  4712. return;
  4713. }
  4714. this.offsetX += this.FIX_VP_X;
  4715. this.dragRefOffSetX -= this.FIX_VP_X;
  4716. this.itemMove(index, index - 1)
  4717. }
  4718. right(index: number): void {
  4719. if (!this.isInLeft(index)) {
  4720. return;
  4721. }
  4722. if (!this.isDraggable(index + 1)) {
  4723. return;
  4724. }
  4725. this.offsetX -= this.FIX_VP_X;
  4726. this.dragRefOffSetX += this.FIX_VP_X;
  4727. this.itemMove(index, index + 1)
  4728. }
  4729. private scroller: Scroller = new Scroller();
  4730. private waterScroller: Scroller = new Scroller();
  4731. @State startIndex: number = 0
  4732. @State endIndex: number = 0
  4733. @State scaleValue: number = 1
  4734. @State pinchValue: number = 1
  4735. layoutOptionsForHeader: GridLayoutOptions = {
  4736. regularSize: [1, 1], // 只支持[1, 1]
  4737. irregularIndexes: [0], // 索引为0的GridItem占用一行
  4738. };
  4739. @Builder
  4740. getGridView() {
  4741. Grid(this.scroller, this.layoutOptionsForHeader) {
  4742. GridItem() {
  4743. Column(){
  4744. Blank().height(this.topSafeHeight + 45)
  4745. }
  4746. }
  4747. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  4748. GridItem() {
  4749. Stack({ alignContent: Alignment.Center }) {
  4750. this.MusicItemGrid(item, index)
  4751. }
  4752. }
  4753. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  4754. {
  4755. preview: MenuPreviewMode.IMAGE,
  4756. previewAnimationOptions: { scale: [0.8, 1.0] },
  4757. })
  4758. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  4759. {
  4760. preview: MenuPreviewMode.IMAGE,
  4761. previewAnimationOptions: { scale: [0.8, 1.0] },
  4762. })
  4763. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  4764. TransitionEffect.scale({ x: 0, y: 0 })))
  4765. .clickEffect({ level: ClickEffectLevel.LIGHT })
  4766. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  4767. .zIndex(this.dragItem === index ? 1 : 0)
  4768. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  4769. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  4770. }
  4771. .width('94%')
  4772. .height('100%')
  4773. .editMode(true)
  4774. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4775. .animation({ duration: 500, curve: Curve.Ease }))
  4776. .padding({bottom:this.bottomBarHeight+this.bottomSafeHeight+10})
  4777. .reuseId('grid_item')
  4778. .layoutWeight(1)
  4779. .scrollBar(BarState.Off)
  4780. .supportAnimation(true)
  4781. .cachedCount(this.twoFingerType==1?5:this.twoFingerType==2?4:3)
  4782. .columnsTemplate(
  4783. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  4784. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  4785. )
  4786. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  4787. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  4788. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  4789. .gesture(PinchGesture({ fingers: 2 })
  4790. .onActionEnd((event: GestureEvent) => {
  4791. this.setGridTwoFingers()
  4792. })
  4793. .onActionUpdate(e => {
  4794. this.scaleValue = this.pinchValue * e.scale
  4795. })
  4796. .onActionStart(e => {
  4797. }))
  4798. .enableScrollInteraction(true)
  4799. .onScrollIndex((start: number, end: number) => {
  4800. this.startIndex = start
  4801. this.endIndex = end
  4802. })
  4803. .onScrollFrameBegin((offset: number) => {
  4804. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  4805. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  4806. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  4807. if (this.isScrollHide) {
  4808. this.setBarHeightHide2(offset)
  4809. } else {
  4810. this.setBarHeightNormal()
  4811. }
  4812. } else {
  4813. this.setBarHeightHide(offset)
  4814. }
  4815. return { offsetRemain: offset };
  4816. })
  4817. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  4818. .onDrop((event?: DragEvent) => {
  4819. try {
  4820. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  4821. if (dragData !== undefined) {
  4822. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  4823. if (records.length > 0) {
  4824. for (let i = 0; i < records.length; i++) {
  4825. let types = records[i].getTypes();
  4826. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  4827. const fileUriUds =
  4828. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  4829. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  4830. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  4831. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  4832. this.targetFile = fileUriUds.oriUri;
  4833. this.saveVideoDatas([this.targetFile])
  4834. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  4835. }
  4836. }
  4837. }
  4838. } else {
  4839. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  4840. }
  4841. } else {
  4842. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  4843. }
  4844. } catch (error) {
  4845. const err = error as BusinessError;
  4846. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  4847. }
  4848. })
  4849. }
  4850. @State targetFile: string = '';
  4851. setGridTwoFingers() {
  4852. this.pinchValue = this.scaleValue;
  4853. Logger.info('this.pinchValue = ' + this.pinchValue);
  4854. if (this.pinchValue >= 1) {
  4855. this.twoFingerType++
  4856. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  4857. if(this.twoFingerType >= 4){
  4858. this.twoFingerType = 4//切换成瀑布流
  4859. this.columns = 4
  4860. }
  4861. } else {
  4862. this.twoFingerType--
  4863. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  4864. if (this.twoFingerType < 1) {
  4865. this.twoFingerType = 3
  4866. this.isGridMusic = false
  4867. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4868. }
  4869. }
  4870. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  4871. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4872. this.pinchValue = 1;
  4873. this.scaleValue = 1;
  4874. }
  4875. @State longItemFilePath: string = ''
  4876. @State tempLyricContent: string = ''
  4877. @Builder
  4878. private MusicItemGrid(item: VideoItem, index: number) {
  4879. Button({ type: ButtonType.Normal, stateEffect: false }) {
  4880. Stack() {
  4881. Column() {
  4882. Image(item.pixelMapPath)
  4883. .height(this.getGridHeight())
  4884. .width(this.getGridWight())
  4885. .draggable(false)
  4886. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4887. .autoResize(true) // 重采样,可减少内存占用
  4888. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  4889. .clip(true)
  4890. .borderRadius({
  4891. topLeft: 12,
  4892. topRight: 12,
  4893. bottomLeft: 0,
  4894. bottomRight: 0
  4895. })
  4896. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  4897. height: '99%' ,
  4898. dragBar: true,
  4899. onDisappear: () => {
  4900. this.longItemFilePath = '';
  4901. this.tempLyricContent = ''
  4902. },
  4903. showClose: true,
  4904. preferType: SheetType.CENTER ,
  4905. title: { title: '编辑标签' }
  4906. })
  4907. .draggable(false)
  4908. .opacity(this.opacityItem)// 绑定透明度
  4909. .animation({
  4910. duration: 666,
  4911. curve: 'ease-in-out' // 可选动画曲线
  4912. })
  4913. .margin({
  4914. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4915. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4916. })
  4917. Column() {
  4918. Text(this.isShowFileName&&item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4919. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4920. .maxLines(1)
  4921. .fontWeight(FontWeight.Bold)
  4922. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4923. .animation({
  4924. duration: 555,
  4925. curve: 'Linear',
  4926. })
  4927. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  4928. height: '95%',
  4929. dragBar: true,
  4930. showClose: true,
  4931. onDisappear: () => {
  4932. this.longItemFilePathDetail = '';
  4933. },
  4934. blurStyle:BlurStyle.Thin,
  4935. backgroundColor:Color.Transparent,
  4936. preferType: SheetType.CENTER ,
  4937. title: { title: '详情' }
  4938. })
  4939. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4940. $r('app.color.text_color'))
  4941. Column() {
  4942. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  4943. .fontSize(11)
  4944. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  4945. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4946. .fontColor($r('app.color.text_color'))
  4947. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  4948. .fontSize(11)
  4949. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  4950. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4951. .fontColor($r('app.color.text_color'))
  4952. Row(){
  4953. Column(){
  4954. Text(item.md5Str?.includes('Lossless')?
  4955. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4956. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  4957. .padding({ top: 3,right:6,left:6,bottom:3 })
  4958. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4959. $r('app.color.text_color'))
  4960. .fontWeight(500)
  4961. .borderRadius(12)
  4962. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4963. .backgroundColor('#FFC107')
  4964. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  4965. }
  4966. .margin({ top: 2 ,right:6})
  4967. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  4968. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  4969. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  4970. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  4971. .maxLines(1)
  4972. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4973. .margin({ top: 2})
  4974. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  4975. || item.type == CommonConstants.TYPE_IS_ALBUM
  4976. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4977. .fontWeight(FontWeight.Medium)
  4978. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4979. $r('app.color.text_color'))
  4980. }
  4981. }
  4982. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  4983. }
  4984. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  4985. .width(this.getGridWight())
  4986. .justifyContent(FlexAlign.Center)
  4987. .margin({
  4988. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4989. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4990. })
  4991. }
  4992. .width(this.getGridWight())
  4993. .borderRadius(12)
  4994. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?undefined:item.pixelMapPath)
  4995. .backgroundImageSize({ height: '100%', width: '100%' })
  4996. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  4997. .animation({ curve: Curve.Sharp, duration: 300 })
  4998. Checkbox({ name: 'checkbox' + index })
  4999. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  5000. .selectedColor(this.themeColor)
  5001. .shape(CheckBoxShape.CIRCLE)
  5002. .opacity(this.isMultiSelect ? 1 : 0)
  5003. .animation({
  5004. duration: 666,
  5005. curve: 'Smooth' // 可选动画曲线
  5006. })
  5007. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  5008. Visibility.None)
  5009. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5010. .margin({ left: 20, top: 8, bottom: 8 })
  5011. .width(38)
  5012. .height(38)
  5013. }
  5014. }
  5015. .backgroundColor(Color.Transparent)
  5016. .width('100%')
  5017. .padding({ top: 15 })
  5018. .height(this.getGridAllHeight())
  5019. .onClick(() => {
  5020. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5021. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5022. this.handleFileSelection(item, !isChecked);
  5023. } else {
  5024. this.doPlay(item, index)
  5025. }
  5026. })
  5027. }
  5028. getGridAllHeight() {
  5029. let heightG = 222
  5030. switch (this.twoFingerType) {
  5031. case 1:
  5032. heightG = 143
  5033. break;
  5034. case 2:
  5035. heightG = 178
  5036. break;
  5037. case 3:
  5038. heightG = 222
  5039. break;
  5040. }
  5041. return heightG
  5042. }
  5043. getGridHeight() {
  5044. let heightG = 150
  5045. switch (this.twoFingerType) {
  5046. case 1:
  5047. heightG = 80
  5048. break;
  5049. case 2:
  5050. heightG = 110
  5051. break;
  5052. case 3:
  5053. heightG = 150
  5054. break;
  5055. }
  5056. return heightG
  5057. }
  5058. getGridWight() {
  5059. let wightG = 158
  5060. switch (this.twoFingerType) {
  5061. case 1:
  5062. wightG = 80
  5063. break;
  5064. case 2:
  5065. wightG = 110
  5066. break;
  5067. case 3:
  5068. wightG = 158
  5069. break;
  5070. }
  5071. return wightG
  5072. }
  5073. @State isShowDetail:boolean = false
  5074. @State longItemFilePathDetail:string =''
  5075. @Builder
  5076. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  5077. if(
  5078. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  5079. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5080. item.name === LocalMusic.STR_HISTORY_MUSIC)
  5081. ){
  5082. //如果是专辑和艺术家的首页,不能长按
  5083. //如果是我的收藏 最近播放等也不能长按
  5084. }else{
  5085. Scroll() {
  5086. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  5087. Menu() {
  5088. MenuItem({
  5089. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  5090. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  5091. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  5092. })
  5093. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5094. .onClick(() => {
  5095. if (item) {
  5096. this.doFav(item)
  5097. }
  5098. this.longItemFilePath = ''
  5099. })
  5100. MenuItem({
  5101. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  5102. content: '下一首播放'
  5103. })
  5104. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5105. .onClick(() => {
  5106. this.addToNextPlay(item);
  5107. this.longItemFilePath = ''
  5108. })
  5109. MenuItem({
  5110. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  5111. content: '添加到歌单'
  5112. })
  5113. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5114. .onClick(async () => {
  5115. this.longItemFilePath = ''
  5116. await this.openAddToPlaylistDialog(item)
  5117. })
  5118. MenuItem({
  5119. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  5120. content: '编辑标签'
  5121. })
  5122. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  5123. height: '99%',
  5124. dragBar: true,
  5125. showClose: true,
  5126. preferType: SheetType.CENTER ,
  5127. title: { title: '编辑标签' }
  5128. })
  5129. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5130. .onClick(async() => {
  5131. this.initEditFields(item)
  5132. this.tempLyricContent = await this.getLyricContent(item);
  5133. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  5134. this.lyricConStr = this.tempLyricContent
  5135. }
  5136. if(this.isGridMusic||this.twoFingerType==4){
  5137. this.longItemFilePath = item.filePath
  5138. }else{
  5139. this.isShowEdit = !this.isShowEdit;
  5140. }
  5141. })
  5142. MenuItem({
  5143. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  5144. content: $r('app.string.select_all')
  5145. })
  5146. .onClick(() => {
  5147. this.isMultiSelect = !this.isMultiSelect
  5148. this.longItemFilePath = ''
  5149. this.selectedFiles.push(item)
  5150. })
  5151. MenuItem({
  5152. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.cut')),
  5153. content: $r('app.string.edit_audio')
  5154. })
  5155. .bindContentCover($$this.isEditAudio, this.EditAudioBuilder(item), {
  5156. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5157. })
  5158. .onClick(() => {
  5159. this.isEditAudio = !this.isEditAudio
  5160. })
  5161. MenuItem({
  5162. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  5163. content: $r('app.string.extract_accompaniment')
  5164. })
  5165. .bindContentCover($$this.isExtractAcc, this.ExtractAccBuilder(item), {
  5166. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5167. })
  5168. .onClick(() => {
  5169. if (!Utility.isNoble()) {
  5170. this.showVipDialog()
  5171. return
  5172. }
  5173. this.isExtractAcc = !this.isExtractAcc
  5174. })
  5175. MenuItem({
  5176. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.repeat')),
  5177. content: $r('app.string.converter_audio')
  5178. })
  5179. .bindContentCover($$this.isConverter, this.ConverterBuilder(item), {
  5180. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5181. })
  5182. .onClick(() => {
  5183. if (!Utility.isNoble()) {
  5184. this.showVipDialog()
  5185. return
  5186. }
  5187. this.isConverter = !this.isConverter
  5188. })
  5189. MenuItem({
  5190. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.ai_edit')),
  5191. content: $r('app.string.vocal_separation')
  5192. })
  5193. .bindContentCover($$this.isAIVoiceSeparation, this.AiBuilder(item), {
  5194. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5195. })
  5196. .onClick(() => {
  5197. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  5198. })
  5199. if(Utility.isVideoByExtension(item.filePath)){
  5200. MenuItem({
  5201. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.identify_song')),
  5202. content: $r('app.string.extract_audio')
  5203. })
  5204. .bindContentCover($$this.isExtractAudio, this.extractAudioFromVideoBuilder(item), {
  5205. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5206. })
  5207. .onClick(() => {
  5208. this.isExtractAudio = !this.isExtractAudio
  5209. })
  5210. }
  5211. MenuItem({
  5212. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.phone')),
  5213. content: $r('app.string.set_ring')
  5214. })
  5215. .onClick(async () => {
  5216. await PermissionUtil.activatePermission(item.filePath)
  5217. // if(item.filePath.includes(this.packName)){
  5218. setRingTone(this.context, item.filePath,item.name)
  5219. // }else{
  5220. // ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限设置铃声')
  5221. // }
  5222. this.longItemFilePath = ''
  5223. })
  5224. MenuItem({
  5225. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  5226. content: $r('app.string.rename')
  5227. })
  5228. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  5229. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5230. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  5231. .onClick(() => {
  5232. this.showReNameDialog(item, index + '', filePath)
  5233. this.longItemFilePath = ''
  5234. })
  5235. MenuItem({
  5236. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  5237. content: $r('app.string.delete')
  5238. })
  5239. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  5240. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5241. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  5242. .onClick(() => {
  5243. this.selectedFiles.push(item)
  5244. this.showWarnIsDelete()
  5245. this.longItemFilePath = ''
  5246. })
  5247. MenuItem({
  5248. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  5249. content: $r('app.string.detail')
  5250. })
  5251. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  5252. height:'95%',
  5253. dragBar: true,
  5254. showClose: true,
  5255. blurStyle:BlurStyle.Thin,
  5256. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  5257. backgroundColor:Color.Transparent,
  5258. title: { title: '详情信息' }
  5259. })
  5260. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5261. .onClick(() => {
  5262. if(this.isGridMusic||this.twoFingerType==4){
  5263. this.longItemFilePathDetail = item.filePath
  5264. }else{
  5265. this.isShowDetail = !this.isShowDetail
  5266. }
  5267. })
  5268. MenuItem({
  5269. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  5270. content: $r('app.string.share')
  5271. })
  5272. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5273. .onClick(() => {
  5274. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  5275. this.longItemFilePath = ''
  5276. })
  5277. }
  5278. .font({ size: 15, weight: FontWeight.Normal })
  5279. }
  5280. .width(180)
  5281. }
  5282. .height('auto')
  5283. }
  5284. }
  5285. private listMaxScrollOffsetY: number = 0
  5286. @State selectedIndex: number = -1
  5287. setlistTwoFingers() {
  5288. this.pinchValue = this.scaleValue;
  5289. Logger.info('this.pinchValue = ' + this.pinchValue);
  5290. if (this.pinchValue >= 1) {
  5291. this.twoFingerType++
  5292. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  5293. if (this.twoFingerType > 3) {
  5294. this.twoFingerType = 1
  5295. this.isGridMusic = true
  5296. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5297. }
  5298. } else {
  5299. this.twoFingerType--
  5300. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  5301. if (this.twoFingerType < 1) {
  5302. this.twoFingerType = 4
  5303. this.columns = 1
  5304. }
  5305. }
  5306. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5307. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5308. this.pinchValue = 1;
  5309. this.scaleValue = 1;
  5310. }
  5311. @Builder
  5312. getList(){
  5313. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  5314. this.getListView()
  5315. }
  5316. .pullDownRatio(this.ratioL)
  5317. .pullToRefresh(true)
  5318. .refreshOffset(0)
  5319. .onOffsetChange((offset: number) => {
  5320. // 越接近最大距离,下拉跟手系数越小。
  5321. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  5322. })
  5323. .onStateChange((refreshStatus: RefreshStatus) => {
  5324. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  5325. })
  5326. .onRefreshing(async () => {
  5327. if(this.modeType==0){
  5328. this.getHistoryList(false)
  5329. this.asyncCurrentPathOnlyFile()
  5330. }else if(this.modeType == 1){
  5331. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  5332. }else if(this.modeType == 2){
  5333. workerInstance.postMessage({ code: 3, data: this.context });
  5334. }else if(this.modeType == 3){
  5335. workerInstance.postMessage({ code: 4, data: this.context });
  5336. }else if(this.modeType == 4){
  5337. this.doSongListTask()
  5338. }
  5339. console.log('onRefreshing test');
  5340. })
  5341. }
  5342. // 扫描当前目录下的文件,不扫描子目录
  5343. asyncCurrentPathOnlyFile(){
  5344. if(this.modeType==0){
  5345. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  5346. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  5347. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  5348. if(this.modeType==0){
  5349. setTimeout(()=>{
  5350. this.isRefreshing =false
  5351. this.deleteCache(this.currentPath)
  5352. this.getSortedFiles(this.currentPath)
  5353. },500)
  5354. }
  5355. }).catch((e:object)=>{
  5356. this.isRefreshing =false
  5357. console.info("onecold task1 catch e: " + e);
  5358. })
  5359. }
  5360. }
  5361. @Builder
  5362. getListView() {
  5363. List({ scroller: this.listScroller }) {
  5364. // ListItemGroup({ header: this.coverHeader() }) {
  5365. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5366. ListItem() {
  5367. Column() {
  5368. if (item.type === CommonConstants.TYPE_IS_DIR
  5369. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  5370. this.DirItem(item, index)
  5371. } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
  5372. } else {
  5373. this.MusicItem(item, index)
  5374. }
  5375. }
  5376. .shadow(this.scaleItem === index ? {
  5377. radius: 70,
  5378. color: '#15000000',
  5379. offsetX: 0,
  5380. offsetY: 0
  5381. } :
  5382. {
  5383. radius: 0,
  5384. color: '#15000000',
  5385. offsetX: 0,
  5386. offsetY: 0
  5387. })
  5388. .animation({ curve: Curve.Sharp, duration: 300 })
  5389. }
  5390. // .transition(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }))
  5391. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.9, y: 0.9 })
  5392. .animation({ duration: 500 }),
  5393. TransitionEffect.scale({ x: 0, y: 0 })))
  5394. .clickEffect({ level: ClickEffectLevel.LIGHT })
  5395. .swipeAction((
  5396. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  5397. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  5398. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  5399. start:null,edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  5400. .onClick(() => {
  5401. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5402. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5403. this.handleFileSelection(item, !isChecked);
  5404. } else {
  5405. this.doPlay(item, index)
  5406. }
  5407. })
  5408. //拖动List关键代码开始
  5409. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  5410. .zIndex(this.dragItem === index ? 1 : 0)
  5411. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  5412. .gesture(
  5413. GestureGroup(GestureMode.Sequence,
  5414. LongPressGesture({ repeat: true })
  5415. .onAction((event?: GestureEvent) => {
  5416. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5417. this.scaleItem = index
  5418. })
  5419. })
  5420. .onActionEnd(() => {
  5421. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5422. this.scaleItem = -1
  5423. })
  5424. }),
  5425. PanGesture({ fingers: 1, direction: null, distance: 0 })
  5426. .onActionStart(() => {
  5427. this.dragItem = index // 记录当前拖动项索引
  5428. this.dragRefOffset = 0 // 重置偏移基准
  5429. })
  5430. .onActionUpdate((event: GestureEvent) => {
  5431. this.offsetY = event.offsetY - this.dragRefOffset;
  5432. this.neighborItem = -1;
  5433. let indexA = this.videoLocalList.indexOf(item);
  5434. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  5435. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  5436. let value: number = 0;
  5437. if (this.offsetY < 0) {
  5438. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  5439. this.neighborItem = indexA - 1;
  5440. this.neighborScale = 1 - value / 20;
  5441. } else if (this.offsetY > 0) {
  5442. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  5443. this.neighborItem = indexA + 1;
  5444. this.neighborScale = 1 - value / 20;
  5445. }
  5446. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  5447. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5448. this.offsetY -= this.ITEM_INTV;
  5449. this.dragRefOffset += this.ITEM_INTV;
  5450. this.itemMove(indexA, indexA + 1);
  5451. });
  5452. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  5453. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5454. this.offsetY += this.ITEM_INTV;
  5455. this.dragRefOffset -= this.ITEM_INTV;
  5456. this.itemMove(indexA, indexA - 1);
  5457. });
  5458. }
  5459. let curListOffset = this.listScroller.currentOffset()
  5460. // 获取手指信息
  5461. let fingerInfo = event.fingerList[0]
  5462. let clickPercentY =
  5463. (fingerInfo.globalY - Number(this.listArea.globalPosition.y)) / Number(this.listArea.height)
  5464. if (clickPercentY > 0.8 && !this.listScroller.isAtEnd()) {
  5465. let scrollVelocity = clickPercentY > 0.9 ? 4 : 2
  5466. if (this.listMaxScrollOffsetY - curListOffset.yOffset > scrollVelocity + 5) {
  5467. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset += scrollVelocity })
  5468. }
  5469. } else if (clickPercentY < 0.2 && curListOffset.yOffset >= 0) {
  5470. let scrollVelocity = clickPercentY < 0.1 ? 4 : 2
  5471. if (curListOffset.yOffset > scrollVelocity + 5) {
  5472. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset -= scrollVelocity })
  5473. }
  5474. }
  5475. })
  5476. .onActionEnd((event: GestureEvent) => {
  5477. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5478. this.dragItem = -1
  5479. this.neighborItem = -1
  5480. })
  5481. animateTo({
  5482. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5483. }, () => {
  5484. this.scaleItem = -1
  5485. })
  5486. })
  5487. )
  5488. .onCancel(() => {
  5489. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5490. this.dragItem = -1
  5491. this.neighborItem = -1
  5492. })
  5493. animateTo({
  5494. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5495. }, () => {
  5496. this.scaleItem = -1
  5497. })
  5498. })
  5499. ) //拖动List关键代码结束
  5500. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5501. // }
  5502. }
  5503. .scrollBar(BarState.Off)
  5504. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5505. .gesture(PinchGesture({ fingers: 2 })
  5506. .onActionEnd((event: GestureEvent) => {
  5507. this.setlistTwoFingers()
  5508. })
  5509. .onActionUpdate(e => {
  5510. this.scaleValue = this.pinchValue * e.scale
  5511. })
  5512. .onActionStart(e => {
  5513. }))
  5514. .contentStartOffset(this.topSafeHeight + 55)
  5515. .scrollBar(BarState.Off)
  5516. .contentEndOffset(this.bottomBarHeight+this.bottomSafeHeight)
  5517. .cachedCount(10)
  5518. // .reuseId('list_item')
  5519. .borderRadius(20)
  5520. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.9, y: 0.9 }).animation({ duration: 400 }),
  5521. // TransitionEffect.scale({ x: 0, y: 0 })))
  5522. .layoutWeight(1)
  5523. .onScrollIndex((start) => {
  5524. this.selectedIndex = start
  5525. })
  5526. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  5527. .lanes(
  5528. new BreakpointType<number>({
  5529. sm: 1,
  5530. md: 2,
  5531. lg: 2,
  5532. xl: 3,
  5533. xxl: 4
  5534. }).getValue(this.currentBreakpoint),
  5535. new BreakpointType<number>({
  5536. sm: 0,
  5537. md: 12,
  5538. lg: 12,
  5539. xl: 16,
  5540. xxl: 20
  5541. }).getValue(this.currentBreakpoint)
  5542. )
  5543. .onAreaChange((oldValue: Area, newValue: Area) => {
  5544. this.listArea = newValue
  5545. if (this.twoFingerType == 3) {
  5546. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  5547. } else if (this.twoFingerType == 2) {
  5548. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  5549. } else if (this.twoFingerType == 1) {
  5550. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  5551. }
  5552. })
  5553. .onScrollFrameBegin((offset: number) => {
  5554. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  5555. // if (this.isPhoneLan()) {
  5556. // this.setBarHeightHide(offset)
  5557. // } else
  5558. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  5559. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  5560. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  5561. if (this.isScrollHide) {
  5562. this.setBarHeightHide2(offset)
  5563. } else {
  5564. this.setBarHeightNormal()
  5565. }
  5566. } else {
  5567. this.setBarHeightHide(offset)
  5568. }
  5569. return { offsetRemain: offset };
  5570. })
  5571. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  5572. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  5573. .onDrop((event?: DragEvent) => {
  5574. try {
  5575. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  5576. if (dragData !== undefined) {
  5577. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  5578. if (records.length > 0) {
  5579. for (let i = 0; i < records.length; i++) {
  5580. let types = records[i].getTypes();
  5581. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  5582. const fileUriUds =
  5583. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  5584. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  5585. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  5586. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  5587. this.targetFile = fileUriUds.oriUri;
  5588. this.saveVideoDatas([this.targetFile])
  5589. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  5590. }
  5591. }
  5592. }
  5593. } else {
  5594. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  5595. }
  5596. } else {
  5597. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  5598. }
  5599. } catch (error) {
  5600. const err = error as BusinessError;
  5601. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  5602. }
  5603. })
  5604. }
  5605. setBarHeightNormal() {
  5606. this.hideDone = false;
  5607. this.getUIContext().animateTo({
  5608. duration: 300
  5609. }, () => {
  5610. this.bottomBarHeight = 68 + 0;
  5611. this.topBarHeight = 50 + 0;
  5612. this.barOpacity = 1;
  5613. this.barBottomOpacity = 1
  5614. this.currentYOffset = 0;
  5615. this.isHiding = false;
  5616. });
  5617. }
  5618. setBarHeightHide(offset: number) {
  5619. if (offset > 0 && !this.hideDone) {
  5620. this.currentYOffset += offset;
  5621. if (this.currentYOffset <= 100) {
  5622. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  5623. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  5624. this.barOpacity = 1 - this.currentYOffset / 100;
  5625. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  5626. } else {
  5627. this.topBarHeight = 0;
  5628. this.bottomBarHeight = 0;
  5629. this.barBottomOpacity = 0
  5630. this.barOpacity = 0;
  5631. this.hideDone = true;
  5632. }
  5633. this.isHiding = true;
  5634. }
  5635. if (offset < 0 && this.isHiding) {
  5636. this.hideDone = false;
  5637. this.getUIContext().animateTo({
  5638. duration: 300
  5639. }, () => {
  5640. this.bottomBarHeight = 68 + 0;
  5641. this.topBarHeight = 50 + 0;
  5642. this.barOpacity = 1;
  5643. this.barBottomOpacity = 1
  5644. this.currentYOffset = 0;
  5645. this.isHiding = false;
  5646. });
  5647. }
  5648. }
  5649. //这个方法没隐藏bottomBar,只隐藏topbar
  5650. setBarHeightHide2(offset: number) {
  5651. if (offset > 0 && !this.hideDone) {
  5652. this.currentYOffset += offset;
  5653. if (this.currentYOffset <= 100) {
  5654. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  5655. this.barOpacity = 1 - this.currentYOffset / 100;
  5656. } else {
  5657. this.topBarHeight = 0;
  5658. this.barOpacity = 0;
  5659. this.hideDone = true;
  5660. }
  5661. this.isHiding = true;
  5662. }
  5663. if (offset < 0 && this.isHiding) {
  5664. this.hideDone = false;
  5665. this.getUIContext().animateTo({
  5666. duration: 300
  5667. }, () => {
  5668. this.topBarHeight = 50 + 0;
  5669. this.barOpacity = 1;
  5670. this.currentYOffset = 0;
  5671. this.isHiding = false;
  5672. });
  5673. }
  5674. }
  5675. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  5676. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  5677. switch (item.type) {
  5678. case CommonConstants.TYPE_IS_DIR:
  5679. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  5680. let offsetB = 0
  5681. if(this.twoFingerType==4){
  5682. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  5683. let cur = this.waterScroller.currentOffset()
  5684. if (cur && typeof cur.yOffset === 'number') {
  5685. offsetB = cur.yOffset
  5686. }
  5687. }
  5688. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  5689. }else
  5690. if (this.isGridMusic) {
  5691. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  5692. let cur = this.scroller.currentOffset()
  5693. if (cur && typeof cur.yOffset === 'number') {
  5694. offsetB = cur.yOffset
  5695. }
  5696. }
  5697. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  5698. } else {
  5699. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  5700. let cur = this.listScroller.currentOffset()
  5701. if (cur && typeof cur.yOffset === 'number') {
  5702. offsetB = cur.yOffset
  5703. }
  5704. }
  5705. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  5706. }
  5707. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  5708. this.showVerifyDialog()
  5709. this.currentTitleName = '私密音频'
  5710. this.currentTitleCover = $r('app.media.ic_avatar1')
  5711. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  5712. this.titleName = '最近播放'
  5713. this.currentTitleCover = $r('app.media.alt')
  5714. this.currentTitleName = '最近播放'
  5715. //加载动画效果
  5716. this.updateListData(this.historyList, true)
  5717. // this.videoLocalList = this.historyList
  5718. if (ArrayUtil.isEmpty(this.historyList)) {
  5719. ToastUtil.showToast('最近播放记录空空如也')
  5720. } else {
  5721. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  5722. }
  5723. this.isHistory = true
  5724. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  5725. this.titleName = '我的收藏'
  5726. this.currentTitleName = '我的收藏'
  5727. this.currentTitleCover = $r('app.media.ic_avatar1')
  5728. //加载动画效果
  5729. this.updateListData(this.favList)
  5730. if (ArrayUtil.isEmpty(this.favList)) {
  5731. ToastUtil.showToast('无音乐收藏记录')
  5732. } else {
  5733. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  5734. }
  5735. this.isFavMusic = true
  5736. } else {
  5737. this.currentTitleName = item.name
  5738. this.currentPath = item.filePath
  5739. this.currentTitleCover = $r('app.media.ic_avatar1')
  5740. this.getSortedFiles(this.currentPath)
  5741. }
  5742. //进入歌单的时候的滚动位置在顶部
  5743. if(this.twoFingerType==4){
  5744. setTimeout(() => {
  5745. this.waterScroller.scrollEdge(Edge.Top)
  5746. this.scroller.scrollEdge(Edge.Top)
  5747. }, 380)
  5748. }else{
  5749. if (this.isGridMusic) {
  5750. this.scroller.scrollEdge(Edge.Top)
  5751. }else{
  5752. this.listScroller.scrollEdge(Edge.Top)
  5753. }
  5754. }
  5755. this.rightTopImage = $r('sys.symbol.chevron_left')
  5756. break;
  5757. case CommonConstants.TYPE_IS_ARTIST:
  5758. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  5759. let offsetA = 0
  5760. if(this.twoFingerType==4){
  5761. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  5762. let cur = this.waterScroller.currentOffset()
  5763. if (cur && typeof cur.yOffset === 'number') {
  5764. offsetA = cur.yOffset
  5765. }
  5766. }
  5767. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  5768. }else
  5769. if (this.isGridMusic) {
  5770. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  5771. let cur = this.scroller.currentOffset()
  5772. if (cur && typeof cur.yOffset === 'number') {
  5773. offsetA = cur.yOffset
  5774. }
  5775. }
  5776. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  5777. } else {
  5778. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  5779. let cur = this.listScroller.currentOffset()
  5780. if (cur && typeof cur.yOffset === 'number') {
  5781. offsetA = cur.yOffset
  5782. }
  5783. }
  5784. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  5785. }
  5786. let mList = this.artistMap.get(item.name)
  5787. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  5788. Utility.doSortListAscending(mList)
  5789. this.isCanBack = true
  5790. this.titleName = item.name
  5791. this.currentTitleName = '艺术家:' + item.name
  5792. if (item.pixelMapPath) {
  5793. this.currentTitleCover = item.pixelMapPath
  5794. }
  5795. this.updateListData(mList)
  5796. }
  5797. this.rightTopImage = $r('sys.symbol.chevron_left')
  5798. //进入歌单的时候的滚动位置在顶部
  5799. if(this.twoFingerType==4){
  5800. setTimeout(() => {
  5801. this.waterScroller.scrollEdge(Edge.Top)
  5802. this.scroller.scrollEdge(Edge.Top)
  5803. }, 380)
  5804. }else{
  5805. if (this.isGridMusic) {
  5806. this.scroller.scrollEdge(Edge.Top)
  5807. }else{
  5808. this.listScroller.scrollEdge(Edge.Top)
  5809. }
  5810. }
  5811. break;
  5812. case CommonConstants.TYPE_IS_ALBUM:
  5813. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  5814. let offset = 0
  5815. if(this.twoFingerType==4){
  5816. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  5817. let cur = this.waterScroller.currentOffset()
  5818. if (cur && typeof cur.yOffset === 'number') {
  5819. offset = cur.yOffset
  5820. }
  5821. }
  5822. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  5823. }else
  5824. if (this.isGridMusic) {
  5825. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  5826. let cur = this.scroller.currentOffset()
  5827. if (cur && typeof cur.yOffset === 'number') {
  5828. offset = cur.yOffset
  5829. }
  5830. }
  5831. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  5832. } else {
  5833. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  5834. let cur = this.listScroller.currentOffset()
  5835. if (cur && typeof cur.yOffset === 'number') {
  5836. offset = cur.yOffset
  5837. }
  5838. }
  5839. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  5840. }
  5841. let albumList = this.albumMap.get(item.name)
  5842. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  5843. Utility.doSortListAscending(albumList)
  5844. this.isCanBack = true
  5845. this.titleName = item.name
  5846. this.currentTitleName = '专辑:' + item.name
  5847. if (item.pixelMapPath) {
  5848. this.currentTitleCover = item.pixelMapPath
  5849. }
  5850. this.updateListData(albumList)
  5851. this.mScrollMap.set(item.name, this.selectedIndex)
  5852. this.rightTopImage = $r('sys.symbol.chevron_left')
  5853. }
  5854. //进入歌单的时候的滚动位置在顶部
  5855. if(this.twoFingerType==4){
  5856. setTimeout(() => {
  5857. this.waterScroller.scrollEdge(Edge.Top)
  5858. this.scroller.scrollEdge(Edge.Top)
  5859. }, 380)
  5860. }else{
  5861. if (this.isGridMusic) {
  5862. this.scroller.scrollEdge(Edge.Top)
  5863. }else{
  5864. this.listScroller.scrollEdge(Edge.Top)
  5865. }
  5866. }
  5867. break;
  5868. case CommonConstants.TYPE_IS_CSJAD:
  5869. return
  5870. break;
  5871. case CommonConstants.TYPE_LOCAL:
  5872. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  5873. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  5874. const cueTracks:CueTrack[] = cueinfo.tracks
  5875. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  5876. if(ArrayUtil.isNotEmpty(cueTracks)){
  5877. this.showCueDialog(cueTracks,cueinfo)
  5878. }
  5879. // this.showCueSheet = !this.showCueSheet
  5880. return
  5881. }
  5882. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  5883. this.stop();
  5884. }
  5885. if (isOpen) {
  5886. this.currentSong = item
  5887. if (index !== undefined) {
  5888. this.curIndex = index
  5889. }
  5890. this.songList = []
  5891. this.songList.push(item)
  5892. this.sonDataSource.pushArrayData(this.songList)
  5893. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  5894. this.currentSong = item
  5895. if (index !== undefined) {
  5896. this.curIndex = index
  5897. }
  5898. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  5899. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  5900. }else {
  5901. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  5902. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  5903. this.songList = globalVideoList
  5904. this.sonDataSource.pushArrayData(this.songList)
  5905. this.currentSong = globalVideoList[this.curIndex]
  5906. }
  5907. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  5908. this.videoUrl = this.currentSong.filePath
  5909. this.name = this.currentSong.name
  5910. this.cover = this.currentSong.pixelMapPath
  5911. this.artist = this.currentSong.artist
  5912. LogUtil.info('onecold this.currentSong.cover =' + this.currentSong.pixelMapPath)
  5913. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  5914. this.startPlayOrResumePlay()
  5915. break;
  5916. case CommonConstants.TYPE_WEBDAV:
  5917. case CommonConstants.TYPE_SMB:
  5918. case CommonConstants.TYPE_NAVIDROME:
  5919. // 处理网络音频播放(WebDAV/SMB)
  5920. Logger.info(`heanup 处理云端音频播放: ${item.name}, URL: ${item.filePath}`)
  5921. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  5922. this.stop();
  5923. }
  5924. if (isOpen) {
  5925. this.currentSong = item
  5926. if (index !== undefined) {
  5927. this.curIndex = index
  5928. }
  5929. this.songList = []
  5930. this.songList.push(item)
  5931. this.sonDataSource.pushArrayData(this.songList)
  5932. } else if (isFromSonPlayList) {
  5933. // 点击来自右下角的播放列表
  5934. this.currentSong = item
  5935. if (index !== undefined) {
  5936. this.curIndex = index
  5937. }
  5938. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  5939. Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  5940. } else {
  5941. // 从全局网络音频列表中查找
  5942. let globalVideoList = this.videoLocalList.filter(video => isRemoteCloudType(video.type)) as VideoItem[];
  5943. this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
  5944. if (this.curIndex === -1 && index !== undefined) {
  5945. this.curIndex = index;
  5946. }
  5947. this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
  5948. this.currentSong = this.songList[this.curIndex];
  5949. this.sonDataSource.pushArrayData(this.songList)
  5950. }
  5951. await this.hydrateRemoteSongFromDb(this.currentSong);
  5952. await this.hydrateRemoteSongFromDb(this.currentSong);
  5953. AppStorage.setOrCreate('currentSong', this.currentSong);
  5954. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  5955. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  5956. context: this.context,
  5957. autoParseMusicName: this.autoParseMusicName
  5958. });
  5959. Logger.info(TAG, `WebDAV URL同步构建完成(分支2): ${this.videoUrl}`);
  5960. this.name = this.currentSong.name
  5961. this.cover = this.currentSong.pixelMapPath
  5962. this.artist = this.currentSong.artist
  5963. Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 完整URL: ${this.videoUrl}`)
  5964. this.startPlayOrResumePlay()
  5965. break;
  5966. }
  5967. }
  5968. private cueComponentId: number = 0
  5969. //显示cue分轨列表对话框
  5970. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  5971. this.getUIContext().getPromptAction().openCustomDialog({
  5972. builder: () => {
  5973. this.cueComptentBuilder(cueTracks,cueinfo)
  5974. },
  5975. isModal:true,
  5976. showInSubWindow:false,
  5977. maskColor: Color.Transparent,
  5978. dialogTransition: // 设置弹窗内容显示的过渡效果
  5979. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  5980. .animation({ duration: 600, curve: Curve.Smooth }),
  5981. maskTransition: // 设置蒙层显示的过渡效果
  5982. TransitionEffect.opacity(0.5)
  5983. .animation({ duration: 600, curve: Curve.Smooth })
  5984. }).then((dialogId: number) => {
  5985. this.cueComponentId = dialogId
  5986. })
  5987. .catch((error: BusinessError) => {
  5988. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  5989. })
  5990. }
  5991. @Builder
  5992. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  5993. CueComptent({
  5994. title:cueinfo.title,
  5995. cueTracks:cueTracks,
  5996. isLongNameRoLL:this.isLongNameRoLL,
  5997. onCancel:()=>{
  5998. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  5999. },
  6000. onDoItemClick: async (item: CueTrack, index: number)=>{
  6001. //获取cueinfo对应的filePath
  6002. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  6003. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  6004. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  6005. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  6006. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  6007. if (this.currentSong){
  6008. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6009. this.stop();//播放之前先停止之前播放。
  6010. }
  6011. this.songList = globalVideoList
  6012. this.sonDataSource.pushArrayData(this.songList)
  6013. if (this.currentSong) {
  6014. try {
  6015. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  6016. context: this.context,
  6017. autoParseMusicName: this.autoParseMusicName
  6018. });
  6019. } catch (error) {
  6020. Logger.error(TAG, `CUE 点播构建播放地址失败: ${(error as Error).message}`);
  6021. this.videoUrl = this.currentSong.filePath;
  6022. }
  6023. }
  6024. this.name = item.title||this.currentSong.name
  6025. this.cover = this.currentSong.pixelMapPath
  6026. this.artist = item.performer||this.currentSong.artist
  6027. this.currentSong.name = this.name
  6028. this.currentSong.artist = this.artist
  6029. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  6030. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  6031. }
  6032. }
  6033. })
  6034. }
  6035. @Builder
  6036. PlayController() {
  6037. Row() {
  6038. if(this.isHiCar()){
  6039. this.playConRigth()
  6040. Column(){
  6041. this.centerName()
  6042. }.layoutWeight(1)
  6043. .onClick(()=>{
  6044. this.showPlayerView()
  6045. })
  6046. this.playConLeft(false)
  6047. }else{
  6048. this.playConLeft()
  6049. this.playConRigth()
  6050. }
  6051. }
  6052. .width('100%')
  6053. .height(this.bottomBarHeight)
  6054. .hitTestBehavior(HitTestMode.Transparent)
  6055. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  6056. modalTransition: ModalTransition.NONE,
  6057. onWillDisappear: () => {
  6058. this.setShowPlayFalse()
  6059. },
  6060. // backgroundColor: 'rgba(0, 0, 0, 0.9)',
  6061. })
  6062. .padding({
  6063. left: 16,
  6064. right: 16
  6065. })
  6066. }
  6067. @State isFrontWhite: boolean = false
  6068. @Builder
  6069. centerName() {
  6070. Column() {
  6071. Text(this.currentSong?.name)
  6072. .fontSize(16)
  6073. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  6074. .maxLines(1)
  6075. .fontColor(Color.White)
  6076. .fontWeight(500);
  6077. Row() {
  6078. Text(this.currentSong?.artist)
  6079. .margin({ top: 2 })
  6080. .fontSize(13)
  6081. .textAlign(TextAlign.Start)
  6082. .maxLines(1)
  6083. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  6084. .fontColor(Color.White)
  6085. }
  6086. .visibility(this.currentSong?.artist? Visibility.Visible:Visibility.None)
  6087. }
  6088. .geometryTransition('name', { follow: true }) // 绑定标识符
  6089. .alignItems(HorizontalAlign.Center)
  6090. }
  6091. @Builder
  6092. playConLeft(isLeft: boolean = true) {
  6093. Row() {
  6094. // RotatingCover({ songLabel: this.currentSong?.pixelMapPath })
  6095. Image( StrUtil.isNotEmpty(this.currentSong?.pixelMapPath)?
  6096. this.currentSong?.pixelMapPath:$r('app.media.music_red'))
  6097. .height(45)
  6098. .objectFit(ImageFit.Contain)
  6099. .alt( $r('app.media.music_red'))
  6100. .fillColor(this.themeColor)
  6101. .borderRadius(8)
  6102. .shadow({
  6103. radius: 10,
  6104. type: ShadowType.BLUR,
  6105. color: 'on_primary'
  6106. })
  6107. .geometryTransition('cover', { follow: true }) // 绑定标识符
  6108. Column() {
  6109. Text(this.currentSong?.name)
  6110. .fontSize(16)
  6111. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  6112. .maxLines(1)
  6113. .fontColor(Color.White)
  6114. .fontWeight(500);
  6115. Row() {
  6116. Text(this.currentSong?.artist)
  6117. .margin({ top: 2 })
  6118. .fontSize(13)
  6119. .textAlign(TextAlign.Start)
  6120. .maxLines(1)
  6121. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  6122. .fontColor(Color.White)
  6123. }
  6124. .visibility(this.currentSong?.artist? Visibility.Visible:Visibility.None)
  6125. }
  6126. .padding({left:8})
  6127. .geometryTransition('name', { follow: true }) // 绑定标识符
  6128. .alignItems(isLeft?HorizontalAlign.Start:HorizontalAlign.End)
  6129. .margin({ right: isLeft?22:10 })
  6130. .visibility(isLeft? Visibility.Visible:Visibility.None)
  6131. }
  6132. .padding({ right: 18 })
  6133. .layoutWeight(isLeft?1:0)
  6134. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  6135. .onClick(() => {
  6136. this.showPlayerView()
  6137. })
  6138. }
  6139. setShowPlayTrue(){
  6140. this.getUIContext()?.animateTo({
  6141. duration: 500,
  6142. curve: Curve.Friction
  6143. }, () => {
  6144. this.isShowPlay = true;
  6145. });
  6146. }
  6147. setShowPlayFalse(){
  6148. this.getUIContext()?.animateTo({
  6149. duration: 500,
  6150. curve: Curve.Friction
  6151. }, () => {
  6152. this.isShowPlay = false;
  6153. });
  6154. }
  6155. //打开播放页
  6156. showPlayerView() {
  6157. if (ArrayUtil.isNotEmpty(this.songList)) {
  6158. this.setShowPlayTrue()
  6159. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  6160. this.initLyric(lyricPath);
  6161. this.startAutoHide();
  6162. } else {
  6163. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  6164. }
  6165. }
  6166. @Builder
  6167. playConRigth() {
  6168. Row() {
  6169. SymbolGlyph($r('sys.symbol.backward_end_fill'))
  6170. .fontSize(28)
  6171. .fontColor([this.themeColor])
  6172. .alignSelf(ItemAlign.Center)
  6173. .visibility(this.isShowPrecious? Visibility.Visible:Visibility.None)
  6174. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  6175. .margin({ left: 8, right: 14 })
  6176. .displayPriority(2)
  6177. .onClick(() => {
  6178. if (ArrayUtil.isNotEmpty(this.songList)) {
  6179. this.playPrevious()
  6180. } else {
  6181. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6182. }
  6183. })
  6184. //播放进度条
  6185. Stack() {
  6186. Progress({
  6187. value: Math.floor(this.progressValue),
  6188. type: ProgressType.Ring,
  6189. })
  6190. .color(this.themeColor)// 进度条前景色为灰色
  6191. .height(38)
  6192. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6193. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ? $r('app.media.hm_pause') : $r('app.media.hm_play2'))
  6194. .height(36)
  6195. .width(36)
  6196. .displayPriority(3)
  6197. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  6198. .fillColor(this.themeColor)
  6199. .onClick(() => {
  6200. if (ArrayUtil.isNotEmpty(this.songList)) {
  6201. console.info('onecold playOrPause 4642')
  6202. this.playOrPause()
  6203. } else {
  6204. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6205. }
  6206. })
  6207. }
  6208. SymbolGlyph($r('sys.symbol.forward_end_fill'))
  6209. .fontSize(28)
  6210. .fontColor([this.themeColor])
  6211. .alignSelf(ItemAlign.Center)
  6212. .margin({
  6213. right: 14,
  6214. left: 14
  6215. })
  6216. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  6217. .displayPriority(2)
  6218. .onClick(() => {
  6219. if (ArrayUtil.isNotEmpty(this.songList)) {
  6220. this.playNext()
  6221. } else {
  6222. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6223. }
  6224. })
  6225. Image($r('app.media.hm_playlist'))
  6226. .height(26)
  6227. .width(26)
  6228. .displayPriority(1)
  6229. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  6230. .fillColor(this.themeColor)
  6231. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  6232. height: '95%',
  6233. dragBar: true,
  6234. showClose: true,
  6235. blurStyle: BlurStyle.Thin,
  6236. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6237. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  6238. title: {
  6239. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  6240. + `(${this.songList.length}首)`
  6241. }
  6242. })
  6243. .onClick(() => {
  6244. if (ArrayUtil.isNotEmpty(this.songList)) {
  6245. this.isShowSheet = !this.isShowSheet;
  6246. this.isFrontWhite = false
  6247. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  6248. this.scrollIndex()
  6249. } else {
  6250. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6251. }
  6252. })
  6253. }
  6254. }
  6255. scrollIndex(){
  6256. try {
  6257. setTimeout(() => {
  6258. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  6259. if(this.curIndex>60){
  6260. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  6261. }else{
  6262. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  6263. }
  6264. })
  6265. }, 123)
  6266. }catch (error) {
  6267. console.error(`onecold scrollIndex出错: ${error}`);
  6268. }
  6269. }
  6270. //播放列表布局
  6271. @Builder
  6272. PlayListSheet() {
  6273. Column() {
  6274. this.PlayList()
  6275. }
  6276. .width('100%')
  6277. .height('100%')
  6278. }
  6279. @State titleStr: string = ''
  6280. @State ablumStr: string = ''
  6281. @State artistStr: string = ''
  6282. @State lyricConStr: string = ''
  6283. @State currentEditItem: string = ''
  6284. @State yearStr: string = ''
  6285. @State trackStr: string = ''
  6286. @State genreStr: string = ''
  6287. @State imagePathStr: string = ''
  6288. @State albumArtistStr: string = ''
  6289. @State composerStr: string = ''
  6290. @State lyricistStr: string = ''
  6291. @State commentStr: string = ''
  6292. @State discStr: string = ''
  6293. doUpdateData() {
  6294. setTimeout(() => {
  6295. if (this.modeType === 0) {
  6296. this.deleteCache(this.currentPath)
  6297. this.getSortedFiles(this.currentPath)
  6298. }else if (this.modeType === 1){
  6299. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6300. }
  6301. }, 500)
  6302. }
  6303. doAllUpdateData() {
  6304. setTimeout(() => {
  6305. if (this.modeType === 0) {
  6306. this.deleteCache(this.currentPath)
  6307. this.getSortedFiles(this.currentPath)
  6308. }
  6309. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6310. workerInstance.postMessage({ code: 3, data: this.context });
  6311. workerInstance.postMessage({ code: 4, data: this.context });
  6312. }, 999)
  6313. }
  6314. //编辑信息
  6315. async doEdit(item: VideoItem) {
  6316. if (!item) {
  6317. return
  6318. }
  6319. if (StrUtil.isEmpty(this.titleStr)) {
  6320. ToastUtil.showToast('标题不能为空')
  6321. return
  6322. }
  6323. DialogHelper.showLoadingDialog()
  6324. await PermissionUtil.activatePermission(item.filePath)
  6325. let tempOutPath = ''
  6326. // 如果不是 packName 包下的文件,则直接路径用this.currentPath
  6327. if(!item.filePath.toLowerCase().includes(this.packName)){
  6328. tempOutPath = this.currentPath + '/' + item.fileName
  6329. }
  6330. console.info('onecold tempOutPath ='+tempOutPath)
  6331. //用户更改了封面,那就内嵌下封面
  6332. if(StrUtil.isNotEmpty(this.imagePathStr)){
  6333. const resultCover:boolean = await changeMusicCover(this.context,
  6334. item.filePath,this.imagePathStr,true,tempOutPath);
  6335. this.imagePathStr = ''
  6336. if(resultCover){
  6337. ToastUtil.showToast('内嵌封面成功')
  6338. }
  6339. }
  6340. const metadata:FFMpegTags = {
  6341. title: this.titleStr,
  6342. artist: this.artistStr,
  6343. album: this.ablumStr,
  6344. TYER:this.yearStr,
  6345. genre:this.genreStr,
  6346. track:this.trackStr,
  6347. album_artist:this.albumArtistStr,
  6348. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  6349. COMPOSER:this.composerStr,
  6350. lyricist:this.lyricistStr,
  6351. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  6352. comment:this.commentStr,
  6353. disc:this.discStr,
  6354. };
  6355. let newInput = item.filePath
  6356. //内嵌标签歌路径如果不是包含包名,输入newInput要赋值tempOutPath,然后tempOutPath为空
  6357. if(!item.filePath.toLowerCase().includes(this.packName)&&FileUtil.accessSync(tempOutPath)){
  6358. newInput = tempOutPath
  6359. tempOutPath = ''
  6360. }
  6361. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  6362. const result:boolean = await repairAudioMetadata(
  6363. newInput,
  6364. this.lyricConStr,
  6365. metadata,
  6366. true,
  6367. tempOutPath
  6368. );
  6369. if (result) {
  6370. if(!item.filePath.includes(this.packName)){
  6371. //内嵌成功的歌路径如果不是包含包名,则要入库
  6372. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newInput,
  6373. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  6374. this.table.insert(newItem, (id: number) => {
  6375. //加入数据库
  6376. if(this.modeType==0){
  6377. this.deleteCache(this.currentPath)
  6378. this.getSortedFiles(this.currentPath)
  6379. }
  6380. });
  6381. }
  6382. const task = new taskpool.Task(
  6383. updateInfoDb,
  6384. this.context,
  6385. item.filePath,
  6386. this.titleStr,
  6387. this.artistStr,
  6388. this.ablumStr,
  6389. this.lyricConStr,
  6390. this.yearStr,this.genreStr,
  6391. this.trackStr,this.albumArtistStr,
  6392. this.composerStr, this.lyricistStr,
  6393. this.commentStr,this.discStr
  6394. );
  6395. taskpool.execute(task, taskpool.Priority.HIGH).then((result) => {
  6396. if (result) {
  6397. console.log(" onecold 编辑信息成功,数据库已同步");
  6398. ToastUtil.showToast('内嵌音乐标签成功')
  6399. this.isShowMoreView = false
  6400. this.name = this.titleStr
  6401. this.syncEditedFields(item)
  6402. if (item.filePath == this.currentSong?.filePath) {
  6403. this.currentSong.name = this.titleStr
  6404. this.artist = this.artistStr
  6405. this.currentSong.artist = this.artistStr
  6406. this.currentSong.album = this.ablumStr
  6407. this.currentSong.year = this.yearStr
  6408. this.currentSong.genre = this.genreStr
  6409. this.currentSong.track = this.trackStr
  6410. this.currentSong.lyricContent = this.lyricConStr
  6411. this.initLyric(item.filePath)
  6412. this.currentSong.ALBUMARTIST = this.albumArtistStr
  6413. this.currentSong.COMPOSER = this.composerStr
  6414. this.currentSong.LYRICIST = this.lyricistStr
  6415. this.currentSong.COMMENT = this.commentStr
  6416. }
  6417. this.syncListsAfterEdit(item.filePath)
  6418. this.doUpateEditedFields(item)
  6419. //this.doUpdateData()
  6420. } else {
  6421. // ToastUtil.showToast('保存失败' + error?.toString())
  6422. console.error(" onecold 编辑信息数据库失败 ");
  6423. }
  6424. }).catch((error: Error) => {
  6425. // 关闭进度条
  6426. DialogHelper.closeLoading();
  6427. console.error('onecold Subtitle sync failed:', error);
  6428. });
  6429. console.log(' onecold 元数据标签更新成功,');
  6430. } else {
  6431. // 关闭进度条
  6432. DialogHelper.closeLoading();
  6433. ToastUtil.showToast('内嵌音乐标签失败')
  6434. console.log('onecold 内嵌音乐标签失败');
  6435. }
  6436. this.longItemFilePath = ''
  6437. this.tempLyricContent = ''
  6438. this.isShowEdit = false
  6439. }
  6440. // 内嵌标签更新当前内嵌的Item
  6441. async doUpateEditedFields(item: VideoItem) {
  6442. // 找到当前项在 videoLocalList 中的索引
  6443. const index = this.videoLocalList.findIndex(video => video.filePath === item.filePath);
  6444. if (index !== -1) {
  6445. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  6446. const updatedItem = await this.table.queryVideoByFilePath(item.filePath)
  6447. // 只有当查询结果不为 null 时才更新列表
  6448. if (updatedItem !== null) {
  6449. // 更新 videoLocalList 中的项(通过创建新数组触发响应式更新)
  6450. this.videoLocalList = [
  6451. ...this.videoLocalList.slice(0, index),
  6452. updatedItem,
  6453. ...this.videoLocalList.slice(index + 1)
  6454. ];
  6455. // 同步更新 LazyDataSource
  6456. this.dataSource.pushArrayData(this.videoLocalList)
  6457. } else {
  6458. ToastUtil.showToast('未找到更新的数据');
  6459. }
  6460. }
  6461. DialogHelper.closeLoading();
  6462. }
  6463. @Builder
  6464. editSheet(item: VideoItem) {
  6465. Scroll() {
  6466. Column() {
  6467. this.editDetail(item)
  6468. }
  6469. }
  6470. .width('100%')
  6471. .height('100%')
  6472. }
  6473. @Builder
  6474. editDetail(item: VideoItem) {
  6475. Column() {
  6476. if (item) {
  6477. Row() {
  6478. Stack() {
  6479. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  6480. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  6481. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  6482. item.pixelMapPath)
  6483. .fillColor(this.themeColor)
  6484. .height(88)
  6485. .width(88)
  6486. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  6487. .borderRadius(12)
  6488. .clip(true)
  6489. .opacity(this.opacityItem)// 绑定透明度
  6490. .margin({ left: 25 })
  6491. }
  6492. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  6493. .onClick(async () => {
  6494. const imagePath:string | undefined = await this.goSelectImage(item);
  6495. if (imagePath) {
  6496. //用户更改过图片
  6497. this.imagePathStr = imagePath
  6498. }
  6499. })
  6500. .width('28%')
  6501. Row() {
  6502. Column() {
  6503. Text(item.name)
  6504. .fontSize(17)
  6505. .maxLines(1)
  6506. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6507. .animation({
  6508. duration: 555,
  6509. curve: 'Linear',
  6510. })
  6511. .fontColor(this.themeColor)
  6512. .margin({ left: 8 })
  6513. Row() {
  6514. Text(item.artist)
  6515. .fontSize(14)
  6516. .maxLines(1)
  6517. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6518. .padding({ top: 8 })
  6519. .fontColor(this.themeColor)
  6520. .margin({ left: 8 })
  6521. }
  6522. }
  6523. .height('100%')
  6524. .width(100)
  6525. .layoutWeight(1)
  6526. .justifyContent(FlexAlign.Center)
  6527. .alignItems(HorizontalAlign.Start)
  6528. Column() {
  6529. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6530. Row(){
  6531. SymbolGlyph($r('sys.symbol.picture'))
  6532. .fontSize(18)
  6533. .fontColor([Color.White])
  6534. Text('获取封面')
  6535. .margin({ left: 4 })
  6536. .fontSize(11)
  6537. .fontColor(Color.White)
  6538. .fontWeight(480)
  6539. .textAlign(TextAlign.Center)
  6540. }
  6541. .justifyContent(FlexAlign.Center)
  6542. }
  6543. .height(38)
  6544. .width(100)
  6545. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6546. .backgroundColor(this.themeColor)
  6547. .stateEffect(true)
  6548. .margin({ right: 35 })
  6549. .onClick(async () => {
  6550. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  6551. this.showTipsDialog();
  6552. return; // Return empty string when no API is configured
  6553. }
  6554. const imagePath:string | undefined = await this.doSearchCover(item);
  6555. console.info('onecold imagePath = '+imagePath)
  6556. if (StrUtil.isNotEmpty(imagePath)) {
  6557. //用户更改过图片
  6558. this.imagePathStr = imagePath
  6559. ToastUtil.showToast('获取封面成功')
  6560. }else{
  6561. ToastUtil.showToast('获取封面失败,请重试')
  6562. }
  6563. })
  6564. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6565. Row(){
  6566. SymbolGlyph($r('sys.symbol.input_mode'))
  6567. .fontSize(18)
  6568. .fontColor([Color.White])
  6569. Text('获取歌词')
  6570. .margin({ left: 4 })
  6571. .fontSize(11)
  6572. .fontColor(Color.White)
  6573. .fontWeight(480)
  6574. .textAlign(TextAlign.Center)
  6575. }
  6576. .justifyContent(FlexAlign.Center)
  6577. }
  6578. .height(38)
  6579. .width(100)
  6580. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6581. .backgroundColor(this.themeColor)
  6582. .stateEffect(true)
  6583. .margin({ top: 9, right: 35 })
  6584. .onClick(async () => {
  6585. //判断有没有设置api
  6586. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  6587. if (StrUtil.isEmpty(apiUrl)) {
  6588. this.isLyricSetting = false
  6589. this.showTipsDialog()
  6590. return
  6591. }
  6592. let artist = item.artist
  6593. let title = item.name
  6594. if(!artist)
  6595. artist = ''
  6596. if(!title)
  6597. title = ''
  6598. let res: string | undefined = await getApiLyric(apiUrl,title, artist, false);
  6599. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  6600. this.lyricConStr = res;
  6601. ToastUtil.showToast('获取歌词成功')
  6602. }else{
  6603. ToastUtil.showToast('获取歌词失败,请重试')
  6604. }
  6605. })
  6606. }
  6607. .justifyContent(FlexAlign.Start)
  6608. }
  6609. .height('100%')
  6610. .justifyContent(FlexAlign.Start)
  6611. .layoutWeight(1)
  6612. }
  6613. .width('100%')
  6614. .height(98)
  6615. Row() {
  6616. Text('标题:')
  6617. .fontSize(14)
  6618. .fontColor($r('app.color.text_color'))
  6619. .margin({ left: 22 })
  6620. TextInput({ text: item.name })
  6621. .height(40)
  6622. .maxLines(1)
  6623. .fontSize(14)
  6624. .layoutWeight(1)
  6625. .fontColor($r('app.color.text_color'))
  6626. .margin({ right: 20, left: 10 })
  6627. .onChange((val: string) => {
  6628. this.titleStr = val
  6629. })
  6630. }
  6631. .width('100%')
  6632. .margin({ top: 10, bottom: 10 })
  6633. .justifyContent(FlexAlign.Start)
  6634. Row() {
  6635. Text('艺术家:')
  6636. .fontSize(14)
  6637. .fontColor($r('app.color.text_color'))
  6638. .margin({ left: 22 })
  6639. TextInput({ text: item.artist })
  6640. .height(40)
  6641. .maxLines(1)
  6642. .fontSize(14)
  6643. .layoutWeight(1)
  6644. .fontColor($r('app.color.text_color'))
  6645. .margin({ right: 20, left: 10 })
  6646. .onChange((val: string) => {
  6647. this.artistStr = val
  6648. })
  6649. }
  6650. .width('100%')
  6651. .margin({ top: 10, bottom: 10 })
  6652. .justifyContent(FlexAlign.Start)
  6653. Row() {
  6654. Text('专辑名:')
  6655. .fontSize(14)
  6656. .fontColor($r('app.color.text_color'))
  6657. .margin({ left: 22 })
  6658. TextInput({ text: item.album })
  6659. .height(40)
  6660. .maxLines(1)
  6661. .fontSize(14)
  6662. .layoutWeight(1)
  6663. .fontColor($r('app.color.text_color'))
  6664. .margin({ right: 20, left: 10 })
  6665. .onChange((val: string) => {
  6666. this.ablumStr = val
  6667. })
  6668. }
  6669. .width('100%')
  6670. .margin({ top: 10, bottom: 10 })
  6671. .justifyContent(FlexAlign.Start)
  6672. Row() {
  6673. Column(){
  6674. Column(){
  6675. Text('歌词:')
  6676. .fontSize(14)
  6677. .fontColor($r('app.color.text_color'))
  6678. .margin({ top:9,left: 22 })
  6679. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6680. SymbolGlyph($r('sys.symbol.trash_fill'))
  6681. .fontSize(25)
  6682. .alignSelf(ItemAlign.Center)
  6683. .margin({ left: 22,top:25})
  6684. }
  6685. .backgroundColor(Color.Transparent)
  6686. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  6687. Visibility.None:Visibility.Visible)
  6688. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6689. .onClick(()=>{
  6690. this.lyricConStr = ''
  6691. this.lyricContent = ''
  6692. this.tempLyricContent = ''
  6693. })
  6694. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6695. SymbolGlyph($r('sys.symbol.plus'))
  6696. .fontSize(25)
  6697. .alignSelf(ItemAlign.Center)
  6698. .margin({ left: 22,top:25})
  6699. }
  6700. .backgroundColor(Color.Transparent)
  6701. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6702. .onClick( ()=>{
  6703. this.callFilePickerSelectFileForLyric()
  6704. })
  6705. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6706. SymbolGlyph($r('sys.symbol.traditional_square'))
  6707. .fontSize(25)
  6708. .alignSelf(ItemAlign.Center)
  6709. .margin({ left: 22,top:25})
  6710. }
  6711. .backgroundColor(Color.Transparent)
  6712. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  6713. Visibility.None:Visibility.Visible)
  6714. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6715. .onClick( ()=>{
  6716. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  6717. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  6718. })
  6719. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6720. Image($r('app.media.jianti'))
  6721. .height(25)
  6722. .fillColor($r('app.color.text_color'))
  6723. .alignSelf(ItemAlign.Center)
  6724. .margin({ left: 22,top:25})
  6725. }
  6726. .backgroundColor(Color.Transparent)
  6727. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  6728. Visibility.None:Visibility.Visible)
  6729. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6730. .onClick( ()=>{
  6731. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  6732. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  6733. })
  6734. }
  6735. .layoutWeight(1)
  6736. }
  6737. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  6738. this.tempLyricContent })
  6739. .type(TextAreaType.NORMAL)
  6740. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  6741. .fontSize(14)
  6742. .layoutWeight(1)
  6743. .fontColor($r('app.color.text_color'))
  6744. .margin({ right: 20, left: 10 })
  6745. .onChange((val: string) => {
  6746. this.lyricConStr = val
  6747. })
  6748. }
  6749. .width('100%')
  6750. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  6751. .margin({ top: 10, bottom: 10 })
  6752. .justifyContent(FlexAlign.Start)
  6753. Row() {
  6754. Text('年份:')
  6755. .fontSize(14)
  6756. .fontColor($r('app.color.text_color'))
  6757. .margin({ left: 22 })
  6758. TextInput({ text: item.year })
  6759. .height(40)
  6760. .maxLines(1)
  6761. .fontSize(14)
  6762. .type(InputType.Number)
  6763. .layoutWeight(1)
  6764. .fontColor($r('app.color.text_color'))
  6765. .margin({ right: 20, left: 10 })
  6766. .onChange((val: string) => {
  6767. this.yearStr = val
  6768. })
  6769. }
  6770. .width('100%')
  6771. .margin({ top: 10, bottom: 10 })
  6772. .justifyContent(FlexAlign.Start)
  6773. Row() {
  6774. Text('音轨号:')
  6775. .fontSize(14)
  6776. .fontColor($r('app.color.text_color'))
  6777. .margin({ left: 22 })
  6778. TextInput({ text:item.track=='未知'?'': item.track })
  6779. .height(40)
  6780. .maxLines(1)
  6781. .fontSize(14)
  6782. .type(InputType.Number)
  6783. .layoutWeight(1)
  6784. .fontColor($r('app.color.text_color'))
  6785. .margin({ right: 20, left: 10 })
  6786. .onChange((val: string) => {
  6787. this.trackStr = val
  6788. })
  6789. }
  6790. .width('100%')
  6791. .margin({ top: 10, bottom: 10 })
  6792. .justifyContent(FlexAlign.Start)
  6793. Row() {
  6794. Text('碟号:')
  6795. .fontSize(14)
  6796. .fontColor($r('app.color.text_color'))
  6797. .margin({ left: 22 })
  6798. TextInput({ text:item.disc })
  6799. .height(40)
  6800. .maxLines(1)
  6801. .fontSize(14)
  6802. .type(InputType.Number)
  6803. .layoutWeight(1)
  6804. .fontColor($r('app.color.text_color'))
  6805. .margin({ right: 20, left: 10 })
  6806. .onChange((val: string) => {
  6807. this.discStr = val
  6808. })
  6809. }
  6810. .width('100%')
  6811. .margin({ top: 10, bottom: 10 })
  6812. .justifyContent(FlexAlign.Start)
  6813. Row() {
  6814. Text('风格:')
  6815. .fontSize(14)
  6816. .fontColor($r('app.color.text_color'))
  6817. .margin({ left: 22 })
  6818. TextInput({ text: item.genre })
  6819. .height(40)
  6820. .maxLines(1)
  6821. .fontSize(14)
  6822. .layoutWeight(1)
  6823. .fontColor($r('app.color.text_color'))
  6824. .margin({ right: 20, left: 10 })
  6825. .onChange((val: string) => {
  6826. this.genreStr = val
  6827. })
  6828. }
  6829. .width('100%')
  6830. .margin({ top: 10, bottom: 10 })
  6831. .justifyContent(FlexAlign.Start)
  6832. Row() {
  6833. Text('专辑艺术家:')
  6834. .fontSize(14)
  6835. .fontColor($r('app.color.text_color'))
  6836. .margin({ left: 22 })
  6837. TextInput({ text: item.ALBUMARTIST })
  6838. .height(40)
  6839. .maxLines(1)
  6840. .fontSize(14)
  6841. .layoutWeight(1)
  6842. .fontColor($r('app.color.text_color'))
  6843. .margin({ right: 20, left: 10 })
  6844. .onChange((val: string) => {
  6845. this.albumArtistStr = val
  6846. })
  6847. }
  6848. .width('100%')
  6849. .margin({ top: 10, bottom: 10 })
  6850. .justifyContent(FlexAlign.Start)
  6851. Row() {
  6852. Text('作曲:')
  6853. .fontSize(14)
  6854. .fontColor($r('app.color.text_color'))
  6855. .margin({ left: 22 })
  6856. TextInput({ text: item.COMPOSER })
  6857. .height(40)
  6858. .maxLines(1)
  6859. .fontSize(14)
  6860. .layoutWeight(1)
  6861. .fontColor($r('app.color.text_color'))
  6862. .margin({ right: 20, left: 10 })
  6863. .onChange((val: string) => {
  6864. this.composerStr = val
  6865. })
  6866. }
  6867. .width('100%')
  6868. .margin({ top: 10, bottom: 10 })
  6869. .justifyContent(FlexAlign.Start)
  6870. Row() {
  6871. Text('作词:')
  6872. .fontSize(14)
  6873. .fontColor($r('app.color.text_color'))
  6874. .margin({ left: 22 })
  6875. TextInput({ text: item.LYRICIST })
  6876. .height(40)
  6877. .maxLines(1)
  6878. .fontSize(14)
  6879. .layoutWeight(1)
  6880. .fontColor($r('app.color.text_color'))
  6881. .margin({ right: 20, left: 10 })
  6882. .onChange((val: string) => {
  6883. this.lyricistStr = val
  6884. })
  6885. }
  6886. .width('100%')
  6887. .margin({ top: 10, bottom: 10 })
  6888. .justifyContent(FlexAlign.Start)
  6889. Row() {
  6890. Text('注释:')
  6891. .fontSize(14)
  6892. .fontColor($r('app.color.text_color'))
  6893. .margin({ left: 22 })
  6894. TextInput({ text: item.COMMENT })
  6895. .height(40)
  6896. .maxLines(1)
  6897. .fontSize(14)
  6898. .layoutWeight(1)
  6899. .fontColor($r('app.color.text_color'))
  6900. .margin({ right: 20, left: 10 })
  6901. .onChange((val: string) => {
  6902. this.commentStr = val
  6903. })
  6904. }
  6905. .width('100%')
  6906. .margin({ top: 10, bottom: 10 })
  6907. .justifyContent(FlexAlign.Start)
  6908. Row() {
  6909. Button('保存')
  6910. .fontColor(Color.White)
  6911. .layoutWeight(1)
  6912. .height(50)
  6913. .width(100)
  6914. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6915. .backgroundColor(this.themeColor)
  6916. .stateEffect(true)
  6917. .margin({ right: 20, bottom: 20 })
  6918. .onClick(async () => {
  6919. this.doEdit(item)
  6920. })
  6921. Button('取消')
  6922. .fontColor(Color.White)
  6923. .layoutWeight(1)
  6924. .height(50)
  6925. .width(100)
  6926. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6927. .backgroundColor(this.themeColor)
  6928. .stateEffect(true)
  6929. .margin({ left: 20, bottom: 20 })
  6930. .onClick(async () => {
  6931. if(this.isGridMusic){
  6932. this.longItemFilePath =''
  6933. }else{
  6934. this.isShowEdit = false
  6935. }
  6936. this.setEditStrEmpty()
  6937. if(this.isShowPlay){
  6938. this.isShowEdit = false
  6939. }
  6940. })
  6941. }
  6942. .margin({
  6943. left: 38,
  6944. right: 38,
  6945. top: 10,
  6946. bottom: 10
  6947. })
  6948. .width(250)
  6949. .height(60)
  6950. }
  6951. }
  6952. .margin({ bottom: 20 })
  6953. }
  6954. setEditStrEmpty(){
  6955. this.imagePathStr = ''
  6956. this.lyricConStr = ''
  6957. this.artistStr = ''
  6958. this.titleStr = ''
  6959. this.ablumStr = ''
  6960. this.genreStr = ''
  6961. this.yearStr = ''
  6962. this.trackStr = ''
  6963. this.albumArtistStr = ''
  6964. this.composerStr = ''
  6965. this.lyricistStr = ''
  6966. this.commentStr = ''
  6967. this.discStr = ''
  6968. }
  6969. initEditFields(item?: VideoItem) {
  6970. if (!item) {
  6971. this.setEditStrEmpty()
  6972. return
  6973. }
  6974. this.imagePathStr = ''
  6975. this.titleStr = item.name ?? ''
  6976. this.artistStr = item.artist ?? ''
  6977. this.ablumStr = item.album ?? ''
  6978. this.genreStr = item.genre ?? ''
  6979. this.yearStr = item.year ?? ''
  6980. this.trackStr = item.track ?? ''
  6981. this.albumArtistStr = item.ALBUMARTIST ?? ''
  6982. this.composerStr = item.COMPOSER ?? ''
  6983. this.lyricistStr = item.LYRICIST ?? ''
  6984. this.commentStr = item.COMMENT ?? ''
  6985. this.discStr = item.disc ?? ''
  6986. this.lyricConStr = item.lyricContent ?? ''
  6987. }
  6988. private syncEditedFields(target?: VideoItem) {
  6989. if (!target) {
  6990. return
  6991. }
  6992. target.name = this.titleStr
  6993. target.artist = this.artistStr
  6994. target.album = this.ablumStr
  6995. target.lyricContent = this.lyricConStr
  6996. target.year = this.yearStr
  6997. target.genre = this.genreStr
  6998. target.track = this.trackStr
  6999. target.ALBUMARTIST = this.albumArtistStr
  7000. target.COMPOSER = this.composerStr
  7001. target.LYRICIST = this.lyricistStr
  7002. target.COMMENT = this.commentStr
  7003. target.disc = this.discStr
  7004. }
  7005. private replaceItemInList(list: Array<VideoItem> | undefined, filePath: string,
  7006. apply?: (next: Array<VideoItem>) => void) {
  7007. if (!list || ArrayUtil.isEmpty(list)) {
  7008. return
  7009. }
  7010. const index = list.findIndex((video: VideoItem) => video.filePath === filePath)
  7011. if (index < 0) {
  7012. return
  7013. }
  7014. const nextList = [...list]
  7015. this.syncEditedFields(nextList[index])
  7016. apply?.(nextList)
  7017. }
  7018. private syncListsAfterEdit(filePath: string) {
  7019. this.replaceItemInList(this.videoLocalList, filePath, (next: Array<VideoItem>) => {
  7020. this.videoLocalList = next
  7021. this.dataSource.pushArrayData(next)
  7022. })
  7023. this.replaceItemInList(this.songList, filePath, (next: Array<VideoItem>) => {
  7024. this.songList = next
  7025. this.sonDataSource.pushArrayData(next)
  7026. })
  7027. this.replaceItemInList(this.favList, filePath, (next: Array<VideoItem>) => {
  7028. this.favList = next
  7029. })
  7030. this.replaceItemInList(this.historyList, filePath, (next: Array<VideoItem>) => {
  7031. this.historyList = next
  7032. })
  7033. this.replaceItemInList(this.currentSongList, filePath, (next: Array<VideoItem>) => {
  7034. this.currentSongList = next
  7035. })
  7036. this.replaceItemInList(this.mediaKuList, filePath, (next: Array<VideoItem>) => {
  7037. this.mediaKuList = next
  7038. })
  7039. this.replaceItemInList(this.filteredList, filePath, (next: Array<VideoItem>) => {
  7040. this.filteredList = next
  7041. })
  7042. this.replaceItemInList(this.artistList, filePath, (next: Array<VideoItem>) => {
  7043. this.artistList = next
  7044. })
  7045. this.replaceItemInList(this.albumList, filePath, (next: Array<VideoItem>) => {
  7046. this.albumList = next
  7047. })
  7048. this.listRefreshKey++
  7049. }
  7050. @Builder
  7051. detailSheet(item:VideoItem) {
  7052. Scroll() {
  7053. Column() {
  7054. this.songDetail(item)
  7055. }
  7056. }
  7057. .width('100%')
  7058. .height('100%')
  7059. }
  7060. @Builder
  7061. songDetail(currentItem:VideoItem) {
  7062. Column() {
  7063. if (currentItem) {
  7064. Row() {
  7065. Stack() {
  7066. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.music_red') :
  7067. currentItem.pixelMapPath)
  7068. .fillColor(this.themeColor)
  7069. .height(80)
  7070. .width(80)
  7071. .borderRadius(10)
  7072. .opacity(this.opacityItem)// 绑定透明度
  7073. .margin({ left: 22 })
  7074. }
  7075. Column() {
  7076. Column() {
  7077. Text(currentItem.name)
  7078. .fontSize(16)
  7079. .maxLines(1)
  7080. .animation({
  7081. duration: 555,
  7082. curve: 'Linear',
  7083. })
  7084. .fontColor($r('app.color.text_color'))
  7085. .margin({ left: 15 })
  7086. }
  7087. .height('100%')
  7088. .width('100%')
  7089. .justifyContent(FlexAlign.Center)
  7090. .alignItems(HorizontalAlign.Start)
  7091. }
  7092. .height('100%')
  7093. }
  7094. .width('100%')
  7095. .height(90)
  7096. .justifyContent(FlexAlign.SpaceBetween)
  7097. Row() {
  7098. Text('艺术家:')
  7099. .fontSize(14)
  7100. .fontColor($r('app.color.text_color'))
  7101. .margin({ left: 22 })
  7102. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  7103. .fontSize(14)
  7104. .fontColor($r('app.color.text_color'))
  7105. .margin({ left: 10 })
  7106. .layoutWeight(1)
  7107. }
  7108. .width('100%')
  7109. .margin({ top: 10, bottom: 10 })
  7110. .justifyContent(FlexAlign.Start)
  7111. Row() {
  7112. Text('专辑名:')
  7113. .fontSize(14)
  7114. .fontColor($r('app.color.text_color'))
  7115. .margin({ left: 22 })
  7116. Text(currentItem?.album ?currentItem.album : '未知专辑')
  7117. .fontSize(14)
  7118. .margin({ left: 10 })
  7119. .fontColor($r('app.color.text_color'))
  7120. .layoutWeight(1)
  7121. }
  7122. .width('100%')
  7123. .margin({ top: 10, bottom: 10 })
  7124. .justifyContent(FlexAlign.Start)
  7125. Row() {
  7126. Text('时长:')
  7127. .fontSize(14)
  7128. .fontColor($r('app.color.text_color'))
  7129. .margin({ left: 22 })
  7130. Text(StrUtil.isEmpty(currentItem.duration)?
  7131. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  7132. .fontSize(14)
  7133. .margin({ left: 10 })
  7134. .fontColor($r('app.color.text_color'))
  7135. .layoutWeight(1)
  7136. }
  7137. .width('100%')
  7138. .margin({ top: 10, bottom: 10 })
  7139. .justifyContent(FlexAlign.Start)
  7140. Row() {
  7141. Text('采样率:')
  7142. .fontSize(14)
  7143. .fontColor($r('app.color.text_color'))
  7144. .margin({ left: 22 })
  7145. Text(Utility.convertToKHz(currentItem.sampleRate))
  7146. .fontSize(14)
  7147. .margin({ left: 10 })
  7148. .fontColor($r('app.color.text_color'))
  7149. .layoutWeight(1)
  7150. }
  7151. .width('100%')
  7152. .margin({ top: 10, bottom: 10 })
  7153. .justifyContent(FlexAlign.Start)
  7154. Row() {
  7155. Text('比特率:')
  7156. .fontSize(14)
  7157. .fontColor($r('app.color.text_color'))
  7158. .margin({ left: 22 })
  7159. Text(currentItem.bit_rate)
  7160. .fontSize(14)
  7161. .margin({ left: 10 })
  7162. .fontColor($r('app.color.text_color'))
  7163. .layoutWeight(1)
  7164. }
  7165. .width('100%')
  7166. .margin({ top: 10, bottom: 10 })
  7167. .justifyContent(FlexAlign.Start)
  7168. Row() {
  7169. Text('位深:')
  7170. .fontSize(14)
  7171. .fontColor($r('app.color.text_color'))
  7172. .margin({ left: 22 })
  7173. Text(`${currentItem.bits_per_raw_sample} bits`)
  7174. .fontSize(14)
  7175. .margin({ left: 10 })
  7176. .fontColor($r('app.color.text_color'))
  7177. .layoutWeight(1)
  7178. }
  7179. .width('100%')
  7180. .margin({ top: 10, bottom: 10 })
  7181. .justifyContent(FlexAlign.Start)
  7182. Row() {
  7183. Text('声道:')
  7184. .fontSize(14)
  7185. .fontColor($r('app.color.text_color'))
  7186. .margin({ left: 22 })
  7187. Text(`${currentItem.channels}`)
  7188. .fontSize(14)
  7189. .margin({ left: 10 })
  7190. .fontColor($r('app.color.text_color'))
  7191. .layoutWeight(1)
  7192. }
  7193. .width('100%')
  7194. .margin({ top: 10, bottom: 10 })
  7195. .justifyContent(FlexAlign.Start)
  7196. Row() {
  7197. Text('声道布局:')
  7198. .fontSize(14)
  7199. .fontColor($r('app.color.text_color'))
  7200. .margin({ left: 22 })
  7201. Text(`${currentItem.channel_layout}`)
  7202. .fontSize(14)
  7203. .margin({ left: 10 })
  7204. .fontColor($r('app.color.text_color'))
  7205. .layoutWeight(1)
  7206. }
  7207. .width('100%')
  7208. .margin({ top: 10, bottom: 10 })
  7209. .justifyContent(FlexAlign.Start)
  7210. Row() {
  7211. Text('起始播放点:')
  7212. .fontSize(14)
  7213. .fontColor($r('app.color.text_color'))
  7214. .margin({ left: 22 })
  7215. Text(`${currentItem.start_time}`)
  7216. .fontSize(14)
  7217. .margin({ left: 10 })
  7218. .fontColor($r('app.color.text_color'))
  7219. .layoutWeight(1)
  7220. }
  7221. .width('100%')
  7222. .margin({ top: 10, bottom: 10 })
  7223. .justifyContent(FlexAlign.Start)
  7224. Row() {
  7225. Text('风格:')
  7226. .fontSize(14)
  7227. .fontColor($r('app.color.text_color'))
  7228. .margin({ left: 22 })
  7229. Text(currentItem.genre)
  7230. .fontSize(14)
  7231. .margin({ left: 10 })
  7232. .fontColor($r('app.color.text_color'))
  7233. .layoutWeight(1)
  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. Text(currentItem.year)
  7244. .fontSize(14)
  7245. .margin({ left: 10 })
  7246. .fontColor($r('app.color.text_color'))
  7247. .layoutWeight(1)
  7248. }
  7249. .width('100%')
  7250. .margin({ top: 10, bottom: 10 })
  7251. .justifyContent(FlexAlign.Start)
  7252. Row() {
  7253. Text('质量评分:')
  7254. .fontSize(14)
  7255. .fontColor($r('app.color.text_color'))
  7256. .margin({ left: 22 })
  7257. Text(currentItem.probe_score+"")
  7258. .fontSize(14)
  7259. .margin({ left: 10 })
  7260. .fontColor($r('app.color.text_color'))
  7261. .layoutWeight(1)
  7262. }
  7263. .width('100%')
  7264. .margin({ top: 10, bottom: 10 })
  7265. .justifyContent(FlexAlign.Start)
  7266. Row() {
  7267. Text('音轨号:')
  7268. .fontSize(14)
  7269. .fontColor($r('app.color.text_color'))
  7270. .margin({ left: 22 })
  7271. Text(currentItem.track)
  7272. .fontSize(14)
  7273. .margin({ left: 10 })
  7274. .fontColor($r('app.color.text_color'))
  7275. .layoutWeight(1)
  7276. }
  7277. .width('100%')
  7278. .margin({ top: 10, bottom: 10 })
  7279. .justifyContent(FlexAlign.Start)
  7280. Row() {
  7281. Text('碟号:')
  7282. .fontSize(14)
  7283. .fontColor($r('app.color.text_color'))
  7284. .margin({ left: 22 })
  7285. Text(currentItem.disc)
  7286. .fontSize(14)
  7287. .margin({ left: 10 })
  7288. .fontColor($r('app.color.text_color'))
  7289. .layoutWeight(1)
  7290. }
  7291. .width('100%')
  7292. .margin({ top: 10, bottom: 10 })
  7293. .justifyContent(FlexAlign.Start)
  7294. Row() {
  7295. Text('专辑艺术家:')
  7296. .fontSize(14)
  7297. .fontColor($r('app.color.text_color'))
  7298. .margin({ left: 22 })
  7299. Text(currentItem.ALBUMARTIST)
  7300. .fontSize(14)
  7301. .margin({ left: 10 })
  7302. .fontColor($r('app.color.text_color'))
  7303. .layoutWeight(1)
  7304. }
  7305. .width('100%')
  7306. .margin({ top: 10, bottom: 10 })
  7307. .justifyContent(FlexAlign.Start)
  7308. Row() {
  7309. Text('作曲家:')
  7310. .fontSize(14)
  7311. .fontColor($r('app.color.text_color'))
  7312. .margin({ left: 22 })
  7313. Text(currentItem.COMPOSER)
  7314. .fontSize(14)
  7315. .margin({ left: 10 })
  7316. .fontColor($r('app.color.text_color'))
  7317. .layoutWeight(1)
  7318. }
  7319. .width('100%')
  7320. .margin({ top: 10, bottom: 10 })
  7321. .justifyContent(FlexAlign.Start)
  7322. Row() {
  7323. Text('作词家:')
  7324. .fontSize(14)
  7325. .fontColor($r('app.color.text_color'))
  7326. .margin({ left: 22 })
  7327. Text(currentItem.LYRICIST)
  7328. .fontSize(14)
  7329. .margin({ left: 10 })
  7330. .fontColor($r('app.color.text_color'))
  7331. .layoutWeight(1)
  7332. }
  7333. .width('100%')
  7334. .margin({ top: 10, bottom: 10 })
  7335. .justifyContent(FlexAlign.Start)
  7336. Row() {
  7337. Text('注释:')
  7338. .fontSize(14)
  7339. .fontColor($r('app.color.text_color'))
  7340. .margin({ left: 22 })
  7341. Text(currentItem.COMMENT)
  7342. .fontSize(14)
  7343. .margin({ left: 10 })
  7344. .fontColor($r('app.color.text_color'))
  7345. .layoutWeight(1)
  7346. }
  7347. .width('100%')
  7348. .margin({ top: 10, bottom: 10 })
  7349. .justifyContent(FlexAlign.Start)
  7350. Row() {
  7351. Text('格式:')
  7352. .fontSize(14)
  7353. .fontColor($r('app.color.text_color'))
  7354. .margin({ left: 22 })
  7355. Text(Utility.formatMimeType(currentItem.mimeType))
  7356. .fontSize(14)
  7357. .margin({ left: 10 })
  7358. .fontColor($r('app.color.text_color'))
  7359. .layoutWeight(1)
  7360. }
  7361. .width('100%')
  7362. .margin({ top: 10, bottom: 10 })
  7363. .justifyContent(FlexAlign.Start)
  7364. Row() {
  7365. Text('播放次数:')
  7366. .fontSize(14)
  7367. .fontColor($r('app.color.text_color'))
  7368. .margin({ left: 22 })
  7369. Text(currentItem.playCount?.toString())
  7370. .fontSize(14)
  7371. .margin({ left: 10 })
  7372. .fontColor($r('app.color.text_color'))
  7373. .layoutWeight(1)
  7374. }
  7375. .width('100%')
  7376. .margin({ top: 10, bottom: 10 })
  7377. .justifyContent(FlexAlign.Start)
  7378. Row() {
  7379. Text('流数量:')
  7380. .fontSize(14)
  7381. .fontColor($r('app.color.text_color'))
  7382. .margin({ left: 22 })
  7383. Text(currentItem.nb_streams?.toString())
  7384. .fontSize(14)
  7385. .margin({ left: 10 })
  7386. .fontColor($r('app.color.text_color'))
  7387. .layoutWeight(1)
  7388. }
  7389. .width('100%')
  7390. .margin({ top: 10, bottom: 10 })
  7391. .justifyContent(FlexAlign.Start)
  7392. Row() {
  7393. Text('文件大小:')
  7394. .fontSize(14)
  7395. .fontColor($r('app.color.text_color'))
  7396. .margin({ left: 22 })
  7397. Text(currentItem.size)
  7398. .fontSize(14)
  7399. .margin({ left: 10 })
  7400. .fontColor($r('app.color.text_color'))
  7401. .layoutWeight(1)
  7402. }
  7403. .width('100%')
  7404. .margin({ top: 10, bottom: 10 })
  7405. .justifyContent(FlexAlign.Start)
  7406. Row() {
  7407. Text('文件名:')
  7408. .fontSize(14)
  7409. .fontColor($r('app.color.text_color'))
  7410. .margin({ left: 22 })
  7411. Text(currentItem.fileName)
  7412. .fontSize(14)
  7413. .margin({ left: 10 })
  7414. .fontColor($r('app.color.text_color'))
  7415. .layoutWeight(1)
  7416. }
  7417. .width('100%')
  7418. .margin({ top: 10, bottom: 10 })
  7419. .justifyContent(FlexAlign.Start)
  7420. Row() {
  7421. Text('修改时间:')
  7422. .fontSize(14)
  7423. .fontColor($r('app.color.text_color'))
  7424. .margin({ left: 22 })
  7425. Text(currentItem.cTime)
  7426. .fontSize(14)
  7427. .margin({ left: 10 })
  7428. .fontColor($r('app.color.text_color'))
  7429. .layoutWeight(1)
  7430. }
  7431. .width('100%')
  7432. .margin({ top: 10, bottom: 10 })
  7433. .justifyContent(FlexAlign.Start)
  7434. Row() {
  7435. Text('存放目录:')
  7436. .fontSize(14)
  7437. .fontColor($r('app.color.text_color'))
  7438. .margin({ left: 22 })
  7439. Text(currentItem.filePath)
  7440. .fontSize(12)
  7441. .margin({ left: 10 })
  7442. .fontColor($r('app.color.text_color'))
  7443. .layoutWeight(1)
  7444. }
  7445. .margin({ top: 10, bottom: 10 })
  7446. .width('100%')
  7447. .justifyContent(FlexAlign.Start)
  7448. Row() {
  7449. Text('内嵌歌词:')
  7450. .fontSize(14)
  7451. .fontColor($r('app.color.text_color'))
  7452. .margin({ left: 22 })
  7453. Text(currentItem.lyricContent)
  7454. .fontSize(12)
  7455. .copyOption(CopyOptions.InApp)
  7456. .margin({ left: 10 })
  7457. .fontColor($r('app.color.text_color'))
  7458. .layoutWeight(1)
  7459. }
  7460. .margin({ top: 10, bottom: 10 })
  7461. .width('100%')
  7462. .justifyContent(FlexAlign.Start)
  7463. }
  7464. }
  7465. .margin({ bottom: 20 })
  7466. }
  7467. //定时关闭布局
  7468. @Builder
  7469. TimeCloseSheet() {
  7470. Scroll() {
  7471. Column() {
  7472. this.TimeClose()
  7473. }
  7474. }
  7475. .width('100%')
  7476. .height('100%')
  7477. }
  7478. //倒计时关闭音乐,退出App功能实现。
  7479. @State selectedMinutes: number = 0 // 0表示未开启
  7480. @State remainingSeconds: number = 0
  7481. // 预设时间选项
  7482. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  7483. private formatTime(seconds: number): string {
  7484. const mins = Math.floor(seconds / 60)
  7485. const secs = seconds % 60
  7486. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  7487. }
  7488. // 开始倒计时
  7489. private handleTimeSelect(minutes: number) {
  7490. if (minutes === this.selectedMinutes) {
  7491. this.stopCountdown();
  7492. this.selectedMinutes = 0;
  7493. return;
  7494. }
  7495. this.selectedMinutes = minutes;
  7496. this.remainingSeconds = minutes * 60;
  7497. this.startCountdown(); // 新增调用
  7498. }
  7499. @Builder
  7500. TimeClose() {
  7501. Column() {
  7502. // 倒计时显示区域
  7503. Text(this.selectedMinutes > 0 ?
  7504. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  7505. "定时关闭未开启")
  7506. .fontSize(17)
  7507. .fontColor($r('app.color.text_color'))
  7508. .margin({ top: 2, bottom: 8 });
  7509. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  7510. ForEach(this.presetTimes, (minutes: number, index: number) => {
  7511. // 单行时间选项容器
  7512. Row() {
  7513. // 文字描述区域
  7514. Text(this.getDisplayText(minutes))
  7515. .fontSize(15)
  7516. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  7517. $r('app.color.text_color'))// 选中态颜色变化
  7518. .textAlign(TextAlign.Start)
  7519. .layoutWeight(1); // 占据剩余空间
  7520. // 复选框样式的选择器
  7521. Row() {
  7522. if (minutes === this.selectedMinutes) {
  7523. // 选中状态 - 带勾号的圆形复选框
  7524. Row() {
  7525. // 使用系统内置的勾号图标
  7526. Image($r('sys.media.ohos_ic_public_ok'))
  7527. .width(14)
  7528. .height(14)
  7529. .fillColor(Color.White)
  7530. }
  7531. .width(24)
  7532. .height(24)
  7533. .borderRadius(12)
  7534. .backgroundColor(this.themeColor)
  7535. .justifyContent(FlexAlign.Center)
  7536. .alignItems(VerticalAlign.Center)
  7537. } else {
  7538. // 未选中状态的圆形边框
  7539. Row()
  7540. .width(24)
  7541. .height(24)
  7542. .borderRadius(12)
  7543. .border({
  7544. width: 2,
  7545. color: $r('app.color.text_color'),
  7546. style: BorderStyle.Solid
  7547. })
  7548. .backgroundColor(Color.Transparent)
  7549. }
  7550. }
  7551. .width(24)
  7552. .height(24)
  7553. .margin({ left: 20 })
  7554. .justifyContent(FlexAlign.Center)
  7555. .alignItems(VerticalAlign.Center)
  7556. }
  7557. .width('100%')
  7558. .padding({
  7559. top: 18,
  7560. bottom: 18,
  7561. left: 18,
  7562. right: 18
  7563. })
  7564. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  7565. $r('app.color.bottom_control_background')) // 选中背景高亮
  7566. .borderRadius(12)
  7567. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7568. .margin({ bottom: 18 })
  7569. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  7570. });
  7571. }
  7572. .width('100%')
  7573. .padding(16)
  7574. }
  7575. }
  7576. // 获取显示文本
  7577. private getDisplayText(minutes: number): string {
  7578. if (minutes === -1) {
  7579. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  7580. }
  7581. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  7582. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  7583. }
  7584. // 处理选择事件
  7585. private handleSelect(minutes: number): void {
  7586. if (minutes === -1) { // 自定义
  7587. // 弹出自定义时间对话框
  7588. DialogHelper.showTextInputDialog({
  7589. title: '自定义时间',
  7590. maskColor: Color.Transparent,
  7591. inputType: InputType.Number,
  7592. text: '',
  7593. onChange: (text) => {
  7594. console.error("onChange: " + text);
  7595. },
  7596. onAction: (action, dialogId, content) => {
  7597. if (action == DialogAction.TWO) {
  7598. const customMinutes = Number(content);
  7599. if (customMinutes > 0) {
  7600. this.handleTimeSelect(customMinutes); // 设置自定义时间
  7601. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  7602. }
  7603. }
  7604. }
  7605. });
  7606. } else {
  7607. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  7608. }
  7609. }
  7610. // 添加定时器引用
  7611. private timerId: number = -1;
  7612. // 启动/重置倒计时
  7613. private startCountdown() {
  7614. // 清除旧定时器
  7615. if (this.timerId !== -1) {
  7616. clearInterval(this.timerId);
  7617. }
  7618. // 创建新定时器
  7619. if (this.selectedMinutes > 0) {
  7620. this.timerId = setInterval(() => {
  7621. if (this.remainingSeconds === 15) {
  7622. this.showConfirmationDialog();
  7623. }
  7624. if (this.remainingSeconds > 0) {
  7625. this.remainingSeconds -= 1;
  7626. } else {
  7627. this.stopCountdown();
  7628. this.handleTimeout();
  7629. }
  7630. }, 1000);
  7631. }
  7632. }
  7633. // 15倒计时后再次提示显示确认是否关闭App对话框
  7634. private showConfirmationDialog() {
  7635. DialogHelper.showAlertDialog({
  7636. backgroundColor: $r('app.color.btn_green'),
  7637. title: '确认关闭',
  7638. maskColor: Color.Transparent,
  7639. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  7640. borderStyle: BorderStyle.Dashed,
  7641. primaryButton: '暂不关闭',
  7642. secondaryButton: '确定',
  7643. onAction: (action) => {
  7644. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  7645. this.stopCountdown();
  7646. this.selectedMinutes = 0
  7647. } else if (action == DialogAction.TWO) {
  7648. }
  7649. }
  7650. })
  7651. }
  7652. // 停止倒计时
  7653. private stopCountdown() {
  7654. if (this.timerId !== -1) {
  7655. clearInterval(this.timerId);
  7656. this.timerId = -1;
  7657. }
  7658. }
  7659. // 超时处理
  7660. private handleTimeout() {
  7661. // 执行播放器关闭逻辑
  7662. this.selectedMinutes = 0;
  7663. ToastUtil.showToast(" 定时关闭已完成");
  7664. this.stop(); // 假设存在的播放器实例
  7665. //退出APP
  7666. const mContext = getContext(this) as common.UIAbilityContext
  7667. mContext.terminateSelf();
  7668. AvSessionController.getInstance(true).unregisterSessionListener()
  7669. }
  7670. //倒计时关闭音乐,退出App功能实现结束。
  7671. //播放列表的拖动List 重新排序
  7672. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  7673. //左滑操作 移动文件 重命名 删除等操作
  7674. @Builder
  7675. sonButton(item: VideoItem, index: number, filePath: string) {
  7676. Row() {
  7677. //加入下一首播放
  7678. Button() {
  7679. Image($r('app.media.next_to_play'))
  7680. .fillColor(Color.White)
  7681. .width(20)
  7682. }
  7683. .width(40)
  7684. .height(40)
  7685. .type(ButtonType.Circle)
  7686. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  7687. .backgroundColor(this.themeColor)
  7688. .margin(5)
  7689. .onClick(() => {
  7690. this.addToNextPlay(item);
  7691. })
  7692. Button() {
  7693. Image($r('app.media.close'))
  7694. .fillColor(Color.White)
  7695. .width(20)
  7696. }
  7697. .width(40)
  7698. .height(40)
  7699. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  7700. .type(ButtonType.Circle)
  7701. .backgroundColor(this.themeColor)
  7702. .margin(5)
  7703. .onClick(() => {
  7704. this.songList.splice(Number(index), 1)
  7705. this.sonDataSource.pushArrayData(this.songList)
  7706. })
  7707. Button() {
  7708. Image($r('app.media.share2'))
  7709. .fillColor(Color.White)
  7710. .width(20)
  7711. }
  7712. .width(40)
  7713. .height(40)
  7714. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  7715. .type(ButtonType.Circle)
  7716. .backgroundColor(this.themeColor)
  7717. .margin(5)
  7718. .onClick(() => {
  7719. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  7720. })
  7721. }
  7722. }
  7723. itemMoveSon(index: number, newIndex: number): void {
  7724. if (newIndex < 0 || newIndex >= this.songList.length) {
  7725. return;
  7726. }
  7727. let tmp = this.songList.splice(index, 1);
  7728. this.songList.splice(newIndex, 0, tmp[0]);
  7729. this.sonDataSource.pushArrayData(this.songList)
  7730. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  7731. if(this.modeType==4&&this.playlistTable){
  7732. updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
  7733. }
  7734. }
  7735. @Builder
  7736. PlayList() {
  7737. List({ scroller: this.playListScroller }) {
  7738. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  7739. ListItem() {
  7740. this.MusicItemSon(item, index)
  7741. }
  7742. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  7743. .animation({
  7744. duration: 666,
  7745. curve: 'ease-in-out' // 可选动画曲线
  7746. })
  7747. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  7748. TransitionEffect.scale({ x: 0, y: 0 })))
  7749. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  7750. //拖动List关键代码开始
  7751. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  7752. .zIndex(this.dragItem === index ? 1 : 0)
  7753. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  7754. .gesture(
  7755. GestureGroup(GestureMode.Sequence,
  7756. LongPressGesture({ repeat: true })
  7757. .onAction((event?: GestureEvent) => {
  7758. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  7759. this.scaleItem = index
  7760. })
  7761. })
  7762. .onActionEnd(() => {
  7763. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  7764. this.scaleItem = -1
  7765. })
  7766. }),
  7767. PanGesture({ fingers: 1, direction: null, distance: 0 })
  7768. .onActionStart(() => {
  7769. this.dragItem = index // 记录当前拖动项索引
  7770. this.dragRefOffset = 0 // 重置偏移基准
  7771. })
  7772. .onActionUpdate((event: GestureEvent) => {
  7773. this.offsetY = event.offsetY - this.dragRefOffset;
  7774. this.neighborItem = -1;
  7775. let indexA = this.songList.indexOf(item);
  7776. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  7777. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  7778. let value: number = 0;
  7779. if (this.offsetY < 0) {
  7780. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  7781. this.neighborItem = indexA - 1;
  7782. this.neighborScale = 1 - value / 20;
  7783. } else if (this.offsetY > 0) {
  7784. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  7785. this.neighborItem = indexA + 1;
  7786. this.neighborScale = 1 - value / 20;
  7787. }
  7788. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  7789. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  7790. this.offsetY -= this.ITEM_INTV;
  7791. this.dragRefOffset += this.ITEM_INTV;
  7792. this.itemMoveSon(indexA, indexA + 1);
  7793. });
  7794. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  7795. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  7796. this.offsetY += this.ITEM_INTV;
  7797. this.dragRefOffset -= this.ITEM_INTV;
  7798. this.itemMoveSon(indexA, indexA - 1);
  7799. });
  7800. }
  7801. })
  7802. .onActionEnd((event: GestureEvent) => {
  7803. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  7804. this.dragItem = -1
  7805. this.neighborItem = -1
  7806. })
  7807. animateTo({
  7808. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  7809. }, () => {
  7810. this.scaleItem = -1
  7811. })
  7812. })
  7813. )
  7814. .onCancel(() => {
  7815. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  7816. this.dragItem = -1
  7817. this.neighborItem = -1
  7818. })
  7819. animateTo({
  7820. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  7821. }, () => {
  7822. this.scaleItem = -1
  7823. })
  7824. })
  7825. ) //拖动List关键代码结束
  7826. .onClick(() => {
  7827. this.doPlay(item, index, true)
  7828. })
  7829. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  7830. }
  7831. .width('100%')
  7832. .height('100%')
  7833. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  7834. // .animation({ duration: 500, curve: Curve.Ease }))
  7835. .cachedCount(10)
  7836. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  7837. .gesture(PinchGesture({ fingers: 2 })
  7838. .onActionEnd((event: GestureEvent) => {
  7839. this.setSonListTwoFingers()
  7840. })
  7841. .onActionUpdate(e => {
  7842. this.scaleValue = this.pinchValue * e.scale
  7843. })
  7844. .onActionStart(e => {
  7845. }))
  7846. .padding({
  7847. bottom: 0
  7848. })
  7849. }
  7850. setSonListTwoFingers() {
  7851. this.pinchValue = this.scaleValue;
  7852. Logger.info('this.pinchValue = ' + this.pinchValue);
  7853. if (this.pinchValue >= 1) {
  7854. this.sonTwoFingerType++
  7855. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  7856. if (this.sonTwoFingerType > 3) {
  7857. this.sonTwoFingerType = 1
  7858. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  7859. }
  7860. } else {
  7861. this.sonTwoFingerType--
  7862. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  7863. if (this.sonTwoFingerType < 1) {
  7864. this.sonTwoFingerType = 1
  7865. }
  7866. }
  7867. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  7868. this.pinchValue = 1;
  7869. this.scaleValue = 1;
  7870. }
  7871. @State sonTwoFingerType:number = 3
  7872. @Builder
  7873. private MusicItemSon(item: VideoItem, index?: number) {
  7874. Button({ type: ButtonType.Normal, stateEffect: true }) {
  7875. Row() {
  7876. Stack() {
  7877. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  7878. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  7879. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  7880. .alt($r('app.media.music_red'))
  7881. .fillColor(this.themeColor)
  7882. .borderRadius('100%')
  7883. .clip(true)
  7884. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  7885. .draggable(false)// 禁止长按手势拖动
  7886. .autoResize(true) // 重采样,可减少内存占用
  7887. .margin({ left: 20 })
  7888. }
  7889. .width('15%')
  7890. Column() {
  7891. Column() {
  7892. Text(this.isShowFileName?item.fileName :item.name)
  7893. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  7894. .fontColor(this.curIndex === index ? this.themeColor :
  7895. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  7896. .maxLines(1)
  7897. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  7898. Row() {
  7899. Column(){
  7900. Text(item.md5Str?.includes('Lossless')?
  7901. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  7902. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  7903. .padding({ top: 3,right:6,left:6,bottom:3 })
  7904. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  7905. $r('app.color.text_color'))
  7906. .fontWeight(500)
  7907. .borderRadius(12)
  7908. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  7909. .backgroundColor('#FFC107')
  7910. }
  7911. .padding({ top: 8 })
  7912. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  7913. item.artist + ' ' + item?.duration)
  7914. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  7915. .padding({ top: 8 })
  7916. .maxLines(1)
  7917. .fontColor(this.curIndex === index ? this.themeColor :
  7918. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  7919. .margin({ left: this.sonTwoFingerType == 3 ? 5 : 3 })
  7920. Blank()
  7921. Text(item.size)
  7922. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  7923. .padding({ top: 8 })
  7924. .maxLines(1)
  7925. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  7926. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  7927. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  7928. .margin({ left: 10 })
  7929. }
  7930. }
  7931. .height('100%')
  7932. .width('100%')
  7933. .justifyContent(FlexAlign.Center)
  7934. .alignItems(HorizontalAlign.Start)
  7935. }
  7936. .height('100%')
  7937. .width('65%')
  7938. Column() {
  7939. ImageAnimator()
  7940. .images(this.imagesF)// 动画数组
  7941. .duration(1000)// 持续
  7942. .state(this.animationState)// 动画状态
  7943. .fillMode(FillMode.Forwards)
  7944. .width(18)
  7945. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  7946. Visibility.None)
  7947. .height(18)
  7948. .iterations(-1) // 播放次数
  7949. }
  7950. .width('20%')
  7951. }
  7952. }
  7953. .backgroundColor(Color.Transparent)
  7954. .width('100%')
  7955. .reuseId('son_item')
  7956. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  7957. .shadow(this.scaleItem === index ? {
  7958. radius: 70,
  7959. color: '#15000000',
  7960. offsetX: 0,
  7961. offsetY: 0
  7962. } :
  7963. {
  7964. radius: 0,
  7965. color: '#15000000',
  7966. offsetX: 0,
  7967. offsetY: 0
  7968. })
  7969. .animation({ curve: Curve.Sharp, duration: 300 })
  7970. }
  7971. @Builder
  7972. MusicPlayBuilder() {
  7973. Column() {
  7974. this.IjkMusicPlayerView()
  7975. }
  7976. .transition(TransitionEffect.asymmetric(
  7977. TransitionEffect.opacity(1),
  7978. TransitionEffect.OPACITY
  7979. ))
  7980. .visualEffect(deviceInfo.sdkApiVersion>=20&&this.bgController?
  7981. new hdsEffect.HdsEffectBuilder()
  7982. .shaderEffect({
  7983. effectType: hdsEffect.EffectType.UV_BACKGROUND_FLOW_LIGHT,
  7984. animation: {
  7985. duration: 10000,
  7986. iterations: -1,
  7987. autoPlay: true,
  7988. onFinish: ()=> {
  7989. console.info('Succeeded in finishing');
  7990. }
  7991. },
  7992. controller: this.bgController,
  7993. })
  7994. .buildEffect():null)
  7995. .height('100%')
  7996. .width('100%')
  7997. .onDisAppear(() => {
  7998. this.translateY = 0;
  7999. })
  8000. .translate({ y: this.translateY })
  8001. .gesture(
  8002. PanGesture(this.panOption)
  8003. .onActionUpdate((event?: GestureEvent) => {
  8004. if (event) {
  8005. // 只允许向下滑动,向上滑动时限制为0
  8006. this.translateY = Math.max(0, event.offsetY);
  8007. this.getUIContext().animateTo({
  8008. duration: 500,
  8009. curve: Curve.Sharp
  8010. }, () => {
  8011. this.scaleValueImage = Math.min(1, Math.max(0.3, 1 - event.offsetY / 260));
  8012. console.info('onecold scaleValueImage:', this.scaleValueImage)
  8013. this.scaleValueText =Math.min(1, Math.max(0.6, 1 - event.offsetY / 300));
  8014. })
  8015. }
  8016. })
  8017. .onActionEnd((event?: GestureEvent) => {
  8018. // 使用更低的阈值和滑动速度判断
  8019. const minDistance = 300; // 最小滑动距离 100vp
  8020. const minVelocity = 500; // 最小滑动速度
  8021. // 获取滑动速度(如果可用)
  8022. const velocity = event?.velocityY || 0;
  8023. // 判断是否应该关闭:距离足够 或者 速度足够快
  8024. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  8025. if (shouldClose) {
  8026. // 添加关闭动画
  8027. this.getUIContext().animateTo({
  8028. duration: 600,
  8029. curve: Curve.Friction
  8030. }, () => {
  8031. this.isShowPlay = false;
  8032. this.scaleValueImage = 1
  8033. this.scaleValueText = 1
  8034. this.translateY = 0;
  8035. })
  8036. } else {
  8037. // 回弹动画
  8038. this.getUIContext().animateTo({
  8039. duration: 600,
  8040. curve: Curve.Friction
  8041. }, () => {
  8042. this.scaleValueImage = 1
  8043. this.scaleValueText = 1
  8044. this.translateY = 0;
  8045. })
  8046. }
  8047. })
  8048. )
  8049. }
  8050. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  8051. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  8052. HeightBreakpoint.HEIGHT_LG;
  8053. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  8054. @State topBarHeight: number = 50
  8055. @State barOpacity: number = 1
  8056. @State barBottomOpacity: number = 1
  8057. private hideDone: boolean = false;
  8058. @State currentYOffset: number = 0;
  8059. @State bottomBarHeight: number = 68;
  8060. private isHiding: boolean = false;
  8061. //是否是Pura X外屏,或者小屏幕
  8062. isPuraWP() {
  8063. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  8064. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  8065. }
  8066. //是否是Pura X外屏,或者小屏幕,手机横屏
  8067. /**
  8068. * 是否是Pura X外屏,或者小屏幕,手机横屏
  8069. * @returns
  8070. */
  8071. isCoverOpacity() {
  8072. if (this.isPuraWP()) {
  8073. return true
  8074. }
  8075. if (this.isPhoneLan()) {
  8076. return true
  8077. }
  8078. if (deviceInfo.marketName.includes('Pura X')
  8079. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  8080. return true
  8081. }
  8082. return false
  8083. }
  8084. //是不是手机横屏
  8085. isPhoneLan() {
  8086. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  8087. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  8088. LogUtil.info('hicar isPhoneLan width= ' + this.windowWidth);
  8089. LogUtil.info('hicar isPhoneLan height= ' + this.windowHeight);
  8090. LogUtil.info(`twocold hicarWindow size: ${this.windowWidth}x${this.windowHeight}, this.isHiCarStatus: ${this.isHiCarStatus}`);
  8091. LogUtil.info(`twocold hicar Window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall: ${this.isHiCarSmall()}`);
  8092. if (this.isHiCarKuanBianPing()) {
  8093. return true
  8094. }
  8095. if (this.isHiCar()) {
  8096. return false
  8097. }
  8098. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8099. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  8100. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  8101. return true
  8102. }
  8103. return false
  8104. }
  8105. //是不是1920x720的hicar的屏幕分辨率
  8106. isHiCarKuanBianPing(){
  8107. if(!this.isHiCar()){
  8108. return false
  8109. }
  8110. const hiCarAspectRatios: HiCarAspectRatio[] = [
  8111. { ratio: 1920 / 720, name: "1920x720" },
  8112. ];
  8113. const currentRatio: number = this.windowWidth / this.windowHeight;
  8114. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  8115. LogUtil.info('twocold isHiCarKuanBianPing currentRatio = ' + currentRatio)
  8116. for (const hiCarRatio of hiCarAspectRatios) {
  8117. LogUtil.info('twocold isHiCarKuanBianPing hiCarRatio= ' + hiCarRatio.ratio)
  8118. LogUtil.info('twocold isHiCarKuanBianPing Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  8119. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  8120. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  8121. //宽扁平的尺寸设置列表展示
  8122. this.twoFingerType ==3
  8123. this.isGridMusic = false
  8124. return true;
  8125. }
  8126. }
  8127. return false;
  8128. }
  8129. //是不是hicar的屏幕分辨率
  8130. isHiCarSmall() {
  8131. if(!this.isHiCar()){
  8132. return false
  8133. }
  8134. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  8135. {
  8136. this.columns = 6
  8137. return false
  8138. }
  8139. const hiCarAspectRatios: HiCarAspectRatio[] = [
  8140. { ratio: 800 / 480, name: "800x480" },
  8141. { ratio: 1280 / 720, name: "1280x720" },
  8142. { ratio: 1920 / 1080, name: "1920x1080" },
  8143. ];
  8144. const currentRatio: number = this.windowWidth / this.windowHeight;
  8145. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  8146. LogUtil.info('twocold isHiCarSmall currentRatio = ' + currentRatio)
  8147. for (const hiCarRatio of hiCarAspectRatios) {
  8148. LogUtil.info('twocold isHiCarSmall hiCarRatio= ' + hiCarRatio.ratio)
  8149. LogUtil.info('twocold isHiCarSmall Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  8150. LogUtil.info('twocold isHiCarSmall isHiCarStatus= ' + this.isHiCarStatus);
  8151. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  8152. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  8153. //宽扁平的尺寸设置列表展示
  8154. return true;
  8155. }
  8156. }
  8157. return false;
  8158. }
  8159. isHiCar() {
  8160. return this.isHiCarStatus&&this.curDisplayIsHiCar;
  8161. }
  8162. //是不是正常的手机竖屏
  8163. isPhonePortrait() {
  8164. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  8165. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  8166. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  8167. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8168. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  8169. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  8170. return true
  8171. }
  8172. return false
  8173. }
  8174. @State showSpeedDialog: boolean = false
  8175. @State longPressSpeed: number = 3 //长按默认倍数
  8176. @Builder
  8177. SpeedDialog() {
  8178. Stack() {
  8179. Column() {
  8180. Text('已切换至' + this.longPressSpeed + '倍速播放')
  8181. .fontColor(Color.White)
  8182. .visibility(Visibility.Hidden)
  8183. }
  8184. .backgroundColor(Color.Black)
  8185. .borderRadius(20)
  8186. .padding({
  8187. top: 10,
  8188. right: 20,
  8189. left: 15,
  8190. bottom: 20
  8191. })
  8192. .opacity(0.6)
  8193. Text('已切换至' + this.longPressSpeed + '倍速播放')
  8194. .fontColor(Color.White)
  8195. }
  8196. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  8197. .zIndex(5)
  8198. .margin({ top: 80 })
  8199. }
  8200. @Builder
  8201. IjkMusicPlayerView() {
  8202. Stack() {
  8203. if(canIUse("SystemCapability.UIDesign.HDSComponent.Core")
  8204. &&deviceInfo.sdkApiVersion>=20&&this.sceneBgController){
  8205. HdsVisualComponent()
  8206. .scene(HdsSceneType.DUAL_EDGE_FLOW_LIGHT_WITH_BACKGROUND_MASK, this.sceneBgController, () => {
  8207. console.info('Succeeded in finishing');
  8208. })
  8209. .width('100%')
  8210. .height('100%')
  8211. .visibility(this.isShowBgLiuGUANG?Visibility.Visible:Visibility.None)
  8212. }
  8213. Column() {
  8214. Column() {
  8215. //播放标题
  8216. Column() {
  8217. this.PlayTitle()
  8218. }
  8219. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  8220. .width('100%')
  8221. .margin({ top: 0 })
  8222. .height(PlayConstants.HEIGHT)
  8223. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  8224. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  8225. if (this.showSpeedDialog) {
  8226. this.SpeedDialog()
  8227. }
  8228. Stack() {
  8229. //手势拖动快进
  8230. Column()
  8231. .width(CommonConstants.FULL_PERCENT)
  8232. .height('100%')
  8233. .gesture(
  8234. GestureGroup(GestureMode.Parallel,
  8235. // 长按屏幕倍数播放
  8236. LongPressGesture({ repeat: true })
  8237. .onAction(() => {
  8238. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8239. this.showSpeedDialog = true;
  8240. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  8241. }
  8242. })
  8243. .onActionEnd(() => {
  8244. this.showSpeedDialog = false;
  8245. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  8246. }),
  8247. //双击屏幕暂停或者播放
  8248. TapGesture({ count: 2 })
  8249. .onAction((event: GestureEvent) => {
  8250. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8251. ToastUtil.showToast('已暂停')
  8252. }
  8253. console.info('onecold playOrPause 6693')
  8254. this.playOrPause()
  8255. })
  8256. )
  8257. )
  8258. }
  8259. .height('65%')
  8260. Swiper() {
  8261. this.CoverInfo()
  8262. this.PlayerLyrics()
  8263. }
  8264. .onChange((index: number) => {
  8265. this.currentSwiperIndex = index
  8266. })
  8267. .indicator(false)
  8268. .displayCount(new BreakpointType({
  8269. sm: 1,
  8270. md: 2,
  8271. lg: 2,
  8272. xl: 2,
  8273. xxl: 2
  8274. }).getValue(this.currentBreakpoint))
  8275. .clip(false)
  8276. .loop(false)
  8277. .autoPlay(false)
  8278. // .interval(8000)
  8279. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  8280. .height('100%')
  8281. .hitTestBehavior(HitTestMode.Transparent)
  8282. Image($r('app.media.icon_replay'))
  8283. .objectFit(ImageFit.Auto)
  8284. .width('120px')
  8285. .height('120px')
  8286. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  8287. .border({ width: 0 })
  8288. .visibility(Visibility.None)
  8289. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  8290. .onClick(() => {
  8291. console.info('onecold startPlayOrResumePlay 6744')
  8292. this.startPlayOrResumePlay();
  8293. })
  8294. }
  8295. .width(CommonConstants.FULL_PERCENT)
  8296. .height(CommonConstants.FULL_PERCENT)
  8297. .justifyContent(FlexAlign.End)
  8298. }
  8299. .justifyContent(FlexAlign.End)
  8300. .margin({ bottom: 8 })
  8301. }
  8302. .backgroundImage(!this.isMusicBGCover||StrUtil.isEmpty(this.cover)?null: this.cover)
  8303. .backgroundImageSize(this.isPuraWP()||!this.isMusicBGCover ? { width: '100%' } : { height: '150%', width: '100%' })
  8304. .animation({
  8305. duration: 666,
  8306. curve: 'ease-in-out' // 可选动画曲线
  8307. })
  8308. .backgroundBlurStyle((this.isPuraWP() && this.currentSwiperIndex === 0) ||!this.isMusicBGCover
  8309. ? BlurStyle.NONE :
  8310. BlurStyle.BACKGROUND_ULTRA_THICK)
  8311. .hitTestBehavior(HitTestMode.Transparent)
  8312. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  8313. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  8314. .onClick(() => {
  8315. if(this.isHiCar())
  8316. return
  8317. if(this.is_auto_hide_progress){
  8318. this.is_auto_hide_progress = false
  8319. }
  8320. this.startAutoHide()
  8321. })
  8322. }
  8323. @State progressValue: number = 0;
  8324. @State currentTime: string = "00:00";
  8325. @State totalTime: string = "00:00";
  8326. @State loadingVisible: Visibility = Visibility.None;
  8327. @State replayVisible: Visibility = Visibility.None;
  8328. @State slideEnable: boolean = false;
  8329. @State aspRatio: number = 0.5;
  8330. @State mContext: object | undefined = undefined;
  8331. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  8332. @State mFirst: boolean = true;
  8333. @State mDestroyPage: boolean = false;
  8334. @State playSpeed: number = 1;
  8335. @State oldSeconds: number = 0;
  8336. @State isSeekTo: boolean = false;
  8337. @State isCurrentTime: boolean = false;
  8338. @State videoWidth: string = '100%';
  8339. @State videoHeight: string = '100%';
  8340. @State initAspectRatio: number = 1;
  8341. @State videoAspectRatio: number = this.initAspectRatio;
  8342. @State videoUrl: string = '';
  8343. private last: number = 0;
  8344. @State videoParentAspectRatio: number = this.initAspectRatio;
  8345. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  8346. @State CONTROL_PlayStatus: number = PlayStatus.INIT;
  8347. @State PROGRESS_MAX_VALUE: number = 100;
  8348. @State updateProgressTimer: number = 0;
  8349. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  8350. @State name: string = '';
  8351. // @State loop: boolean = false;
  8352. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  8353. @State multiple: string = '1.0X';
  8354. xcomponentController: XComponentController = new XComponentController()
  8355. private panOptionBright: PanGestureOptions =
  8356. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  8357. private panOptionVolume: PanGestureOptions =
  8358. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  8359. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  8360. //手势的音量控制和亮度控制
  8361. private positionX: number = PlayConstants.POSITION_X;
  8362. private positionY: number = PlayConstants.POSITION_Y;
  8363. private windowClass: window.Window = globalThis.windowClass
  8364. @State volume: number = 0.5;
  8365. @State volumeSmall: boolean = false
  8366. @State autoParseMusicName: boolean = true
  8367. @State isShowFileName: boolean = false
  8368. @State isLongNameRoLL: boolean = true//长歌名滚动
  8369. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  8370. @State bright: number = PlayConstants.BRIGHT;
  8371. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  8372. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  8373. @State screenWidth: number = 0
  8374. @State screenHeight: number = 0
  8375. @State statusBarHeight: number = 0
  8376. @State isYesFull: boolean = false
  8377. private seekValue: number = 0
  8378. @State isVideoLock: boolean = false; // Whether the video playback is locked
  8379. eventHub = getContext().eventHub;
  8380. //投播组件
  8381. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  8382. private castController: avSession.AVCastController | undefined = undefined;
  8383. @State isCastPlaying: boolean = false;
  8384. @State currentTime2: number = 0;
  8385. @State currentStringTime: string = '00:00';
  8386. @State duration: number = 0;
  8387. @State isReady: boolean = false;
  8388. @State durationTime: number = 0;
  8389. @State durationStringTime: string = '00:00';
  8390. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  8391. // @State isPlaying: boolean = false;
  8392. private castSeek: boolean = false;
  8393. private castItem: avSession.AVQueueItem | undefined = undefined;
  8394. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  8395. @State rotateAngle2: number = -9
  8396. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  8397. @State cover: string | undefined = '';
  8398. @State artist: string | undefined = ''
  8399. // 1.初始化controller
  8400. private lyricController: LyricController = new LyricController()
  8401. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  8402. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  8403. private parser = new LyricParser()
  8404. @State randomColor: string = 'rgb(0,0,0)'
  8405. @State randomShakenX: number = 0
  8406. @State randomShakenY: number = 0
  8407. @State lyricTextSize: number = 24
  8408. @State lyricContent: string = ''
  8409. @State isDebug: boolean = false
  8410. @State isHightLightCenter: boolean = true
  8411. /**
  8412. * 初始化歌词加载与展示逻辑
  8413. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  8414. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  8415. * @param isApi2 是否使用API2获取歌词(可选)
  8416. *
  8417. * 主要流程:
  8418. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  8419. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  8420. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  8421. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  8422. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  8423. * 6. 解析失败或读取失败时,清空歌词显示。
  8424. *
  8425. * 注意事项:
  8426. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  8427. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  8428. * - 歌词内容解析后通过lyricController驱动UI渲染。
  8429. */
  8430. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  8431. if (StrUtil.isEmpty(lyricPath)) {
  8432. return
  8433. }
  8434. this.initPipLyricSetting()
  8435. this.lyricControllerSingle
  8436. .setTextSize(15)
  8437. .setCacheSize(4)
  8438. .setTextColor("#FFFFFF")
  8439. .setHighlightColor("#FFFFFF")
  8440. .setHighlightScale(1.2)
  8441. .setEmptyHint("")
  8442. .setAlignMode('center')
  8443. .setAnimationDuration(500)
  8444. .setSingleLine(true)
  8445. this.lyricContent = ''
  8446. this.lyricController
  8447. .setTextSize(this.currentLyricSize)
  8448. .setCacheSize(4)
  8449. .setTextColor("#DDDDDD")
  8450. .setHighlightColor("#FFFFFF")
  8451. .setEmptyHint("")
  8452. .setAnimationDuration(1000)
  8453. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  8454. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  8455. this.setBlurDegree(this.blurDegree, false)
  8456. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  8457. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  8458. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  8459. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  8460. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  8461. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  8462. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  8463. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  8464. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  8465. this.lyricController.setTextWeight(this.lyricTextWeight)
  8466. this.showSingleLyric = false
  8467. this.timeOffset = 0
  8468. this.lyricController.setLyric(null)
  8469. this.lyricControllerSingle.setLyric(null)
  8470. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  8471. console.log("onecold lyricPath =" + lyricPath)
  8472. let neiqianLrc = ''
  8473. let lyContent = this.currentSong?.lyricContent
  8474. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  8475. neiqianLrc = lyContent
  8476. }
  8477. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast&&!isLocal&&!isLocal) {
  8478. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  8479. //赋值给this.lyricContent,播控中心才可以显示歌词
  8480. this.lyricContent = neiqianLrc
  8481. // 将文件内容按行分割成字符串数组
  8482. let lines = neiqianLrc.split('\n').map(line => line.trim());
  8483. // 3.解析歌词
  8484. let lyric = this.parser.parse(lines);
  8485. // 4.设置歌词
  8486. this.lyricController.setLyric(lyric);
  8487. this.lyricControllerXF.setLyric(lyric)
  8488. this.lyricControllerSingle.setLyric(lyric)
  8489. return
  8490. }
  8491. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  8492. && !Utility.isVideoByExtension(this.videoUrl))) {
  8493. if (this.currentSong !== undefined) {
  8494. // ToastUtil.showShort('正在为你搜索在线歌词!')
  8495. //判断是不是赞助会员,是会员的话才开启歌词功能
  8496. // if (!this.isDebug) {
  8497. // if (!Utility.isNoble()) {
  8498. // LogUtil.debug("onecold 不是赞助会员")
  8499. // return
  8500. // }
  8501. // if(!Utility.isPassInstallTime(33)){
  8502. // LogUtil.debug("onecold not pass time")
  8503. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  8504. // return
  8505. // }
  8506. // }
  8507. let artist = this.currentSong?.artist
  8508. if (artist === undefined) {
  8509. artist = ''
  8510. }
  8511. if (isApi2 === undefined) {
  8512. isApi2 = false
  8513. }
  8514. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  8515. // LogUtil.debug("onecold res =" + res)
  8516. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  8517. if (StrUtil.isNotEmpty(res)) {
  8518. this.lyricContent = res
  8519. let lines = res.split('\n').map(line => line.trim());
  8520. // 3.解析歌词
  8521. let lyric = this.parser.parse(lines);
  8522. // 4.设置歌词
  8523. this.lyricController.setLyric(lyric);
  8524. this.lyricControllerXF.setLyric(lyric)
  8525. this.lyricControllerSingle.setLyric(lyric)
  8526. this.showSingleLyric = true
  8527. // 4.保存歌词文件lyric到本地
  8528. //2025年8月28日歌词不再加密下载
  8529. this.saveDataToFile(res, lyricPath, false)
  8530. } else {
  8531. this.lyricController.setLyric(null)
  8532. this.lyricControllerXF.setLyric(null)
  8533. this.lyricControllerSingle.setLyric(null)
  8534. if (isOnLineAndToast) {
  8535. ToastUtil.showShort('未获取到歌词!')
  8536. }
  8537. }
  8538. } else {
  8539. this.lyricController.setLyric(null)
  8540. this.lyricControllerXF.setLyric(null)
  8541. this.lyricControllerSingle.setLyric(null)
  8542. if (isOnLineAndToast) {
  8543. ToastUtil.showShort('未获取到歌词!')
  8544. }
  8545. }
  8546. })
  8547. } else {
  8548. this.lyricController.setLyric(null)
  8549. this.lyricControllerXF.setLyric(null)
  8550. this.lyricControllerSingle.setLyric(null)
  8551. if (isOnLineAndToast) {
  8552. ToastUtil.showShort('未获取到歌词!')
  8553. }
  8554. }
  8555. return
  8556. }
  8557. try {
  8558. let isJiaMi = false;
  8559. let realLyricPath = lyricPath
  8560. if (FileUtil.accessSync(jiaMilyricPath)) {
  8561. isJiaMi = true
  8562. realLyricPath = jiaMilyricPath
  8563. console.info("onecold 找到加密本地歌词 ");
  8564. } else {
  8565. isJiaMi = false
  8566. realLyricPath = lyricPath
  8567. console.info("onecold 找到本地歌词 ");
  8568. }
  8569. // 3.读取文件内容并指定编码为 UTF-8
  8570. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  8571. const stat = await fileIo.stat(file.fd);
  8572. const arrayBuffer = new ArrayBuffer(stat.size);
  8573. fs.read(file.fd, arrayBuffer)
  8574. .then((readLen: number) => {
  8575. console.info("read file data succeed");
  8576. // let buf = buffer.from(arrayBuffer, 0, readLen);
  8577. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  8578. // 检查 buf 是否为空
  8579. if (buf.length === 0) {
  8580. throw new Error("Buffer is empty after reading the file");
  8581. }
  8582. try {
  8583. // 检测文件编码
  8584. // let detectedEncoding = chardet.detect(buf);
  8585. // console.info("onecoldT Detected encoding: " + detectedEncoding);
  8586. let detectedEncoding = this.detect(arrayBuffer)
  8587. console.info("onecoldT Detected encoding: " + detectedEncoding);
  8588. // 使用检测到的编码解码,解决中文乱码问题
  8589. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  8590. console.info("onecoldT Detected textDecoder: " + textDecoder);
  8591. let fileContent = textDecoder.decode(buf);
  8592. console.info(`onecoldT The content of file1: ${fileContent}`);
  8593. //解密
  8594. if (isJiaMi) {
  8595. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  8596. }
  8597. console.info(`onecold The content of file2: ${fileContent}`);
  8598. this.lyricContent = fileContent
  8599. if(isLocal){//编辑标签选择本地歌词需要赋值给this.lyricConStr
  8600. this.lyricConStr = fileContent
  8601. }
  8602. // 将文件内容按行分割成字符串数组
  8603. let lines = fileContent.split('\n').map(line => line.trim());
  8604. console.info(`onecold The content of file: ${fileContent}`);
  8605. // 3.解析歌词
  8606. let lyric = this.parser.parse(lines);
  8607. // 4.设置歌词
  8608. this.lyricController.setLyric(lyric);
  8609. this.lyricControllerXF.setLyric(lyric)
  8610. this.lyricControllerSingle.setLyric(lyric)
  8611. this.showSingleLyric = true
  8612. console.info(`The content of file: ${fileContent}`);
  8613. } catch (chardetError) {
  8614. console.error("chardet.detect failed with error: " + chardetError.message);
  8615. this.lyricController.setLyric(null);
  8616. this.lyricControllerXF.setLyric(null)
  8617. this.lyricControllerSingle.setLyric(null)
  8618. }
  8619. })
  8620. .catch((err: BusinessError) => {
  8621. this.lyricController.setLyric(null)
  8622. this.lyricControllerXF.setLyric(null)
  8623. this.lyricControllerSingle.setLyric(null)
  8624. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  8625. })
  8626. .catch((err: Error) => {
  8627. this.lyricController.setLyric(null)
  8628. this.lyricControllerXF.setLyric(null)
  8629. this.lyricControllerSingle.setLyric(null)
  8630. console.error("read file 2 data failed with error message: " + err.message);
  8631. })
  8632. .finally(() => {
  8633. fs.closeSync(file);
  8634. });
  8635. } catch (error) {
  8636. this.lyricController.setLyric(null)
  8637. this.lyricControllerSingle.setLyric(null)
  8638. this.lyricControllerXF.setLyric(null)
  8639. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  8640. }
  8641. }
  8642. detect(data: ArrayBuffer): string {
  8643. //创建检测对象
  8644. let detector: UniversalDetector = new UniversalDetector();
  8645. // 传入检测数据并实时判断编码格式
  8646. detector.handleData(data, 0, data.byteLength);
  8647. // 标记检测数据 读取结束
  8648. detector.dataEnd();
  8649. // 获取检测结果
  8650. let detected: string = detector.getDetectedCharset();
  8651. // 释放资源
  8652. detector.reset();
  8653. return detected;
  8654. }
  8655. //初始化悬浮歌词的自定义设置
  8656. initPipLyricSetting() {
  8657. this.lyricControllerXF
  8658. .setTextSize(this.currentLyricSize)
  8659. .setCacheSize(4)
  8660. .setTextColor("#DDDDDD")
  8661. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  8662. .setEmptyHint("")
  8663. .setAnimationDuration(1000)
  8664. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  8665. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  8666. this.setBlurDegree(this.blurDegreePip, true)
  8667. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  8668. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  8669. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  8670. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  8671. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  8672. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  8673. this.lyricControllerXF.setHightLightCenter(true)
  8674. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  8675. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  8676. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  8677. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  8678. if (this.pipBgIndex === 0) {
  8679. if (this.cover) {
  8680. this.pipBg = this.cover
  8681. } else {
  8682. this.pipBg = this.imageColor
  8683. }
  8684. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  8685. }
  8686. }
  8687. //根据item返回歌词内容
  8688. async getLyricContent(item: VideoItem): Promise<string> {
  8689. let neiqianLrc = ''
  8690. let lyContent = item?.lyricContent
  8691. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  8692. neiqianLrc = lyContent
  8693. return neiqianLrc
  8694. }
  8695. try {
  8696. //取数据库里面的歌词lyContent
  8697. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  8698. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  8699. console.log("onecold Lyrics:", lyricContent);
  8700. neiqianLrc = lyricContent
  8701. return neiqianLrc
  8702. }
  8703. } catch (error) {
  8704. console.error("Error fetching lyrics:", error);
  8705. }
  8706. try {
  8707. let filePath = item.filePath;
  8708. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  8709. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  8710. let isJiaMi = false;
  8711. let realLyricPath = lyricPath;
  8712. if (FileUtil.accessSync(jiaMilyricPath)) {
  8713. isJiaMi = true;
  8714. realLyricPath = jiaMilyricPath;
  8715. console.info("onecold 找到加密本地歌词");
  8716. } else {
  8717. console.info("onecold 找到本地歌词");
  8718. }
  8719. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  8720. const stat = await fileIo.stat(file.fd);
  8721. const arrayBuffer = new ArrayBuffer(stat.size);
  8722. const readLen = await fs.read(file.fd, arrayBuffer);
  8723. console.info("read file data succeed");
  8724. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  8725. if (buf.length === 0) {
  8726. throw new Error("Buffer is empty after reading the file");
  8727. }
  8728. // let detectedEncoding = chardet.detect(buf);
  8729. let detectedEncoding = this.detect(arrayBuffer)
  8730. console.info("Detected encoding: " + detectedEncoding);
  8731. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  8732. let fileContent = textDecoder.decode(buf);
  8733. console.info(`onecold The content of file1: ${fileContent}`);
  8734. if (isJiaMi) {
  8735. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  8736. }
  8737. console.info(`onecold The content of file2: ${fileContent}`);
  8738. fs.closeSync(file);
  8739. return fileContent;
  8740. } catch (error) {
  8741. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  8742. return '';
  8743. }
  8744. }
  8745. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  8746. if (StrUtil.isEmpty(filePath)) {
  8747. return
  8748. }
  8749. try {
  8750. //将content进行加密
  8751. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  8752. let lyricContent = ''
  8753. if (isJiaMi) {
  8754. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  8755. } else {
  8756. lyricContent = content
  8757. }
  8758. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  8759. // 清空文件内容
  8760. await fileIo.truncate(file.fd, 0);
  8761. await fileIo.write(file.fd, lyricContent);
  8762. await fileIo.close(file);
  8763. console.log('onecold lyric file Data saved successfully.');
  8764. } catch (error) {
  8765. console.error('onecold lyric file Failed to save data:', error);
  8766. }
  8767. }
  8768. // 定义开始旋转的方法
  8769. // 定时器用于一百毫秒执行一次旋转角度
  8770. @State timer: number = 0
  8771. @State rotateAngle: number = 0
  8772. //封面旋转动画
  8773. animationRoFun() {
  8774. if (this.isPlaying && !this.isCoverRectangle) {
  8775. this.timer = setInterval(() => {
  8776. this.rotateAngle += 1
  8777. }, 100)
  8778. this.startRotation()
  8779. } else {
  8780. clearInterval(this.timer)
  8781. this.stopRotation()
  8782. }
  8783. }
  8784. // 定义开始旋转的方法
  8785. startRotation() {
  8786. if (this.isPlaying) {
  8787. animateTo({
  8788. duration: 777,
  8789. iterations: 1,
  8790. curve: Curve.Linear
  8791. }, () => {
  8792. this.rotateAngle2 = -9
  8793. })
  8794. }
  8795. }
  8796. // 回调,暂停和播放按钮回调,下一首和上一首
  8797. playChange() {
  8798. // if(this.isCoverRectangle){
  8799. // return
  8800. // }
  8801. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8802. this.setIsPlaying(true)
  8803. this.animationState = AnimationStatus.Running
  8804. } else {
  8805. this.setIsPlaying(false)
  8806. this.animationState = AnimationStatus.Paused
  8807. }
  8808. AppStorage.setOrCreate('animationState', this.animationState);
  8809. }
  8810. // 定义停止旋转的方法
  8811. stopRotation() {
  8812. if (this.isCoverRectangle) {
  8813. this.rotateAngle = 0
  8814. } else {
  8815. //唱针以左上角为点选择逆时针40度
  8816. animateTo({
  8817. duration: 1000,
  8818. curve: Curve.Linear,
  8819. iterations: 1,
  8820. }, () => {
  8821. this.rotateAngle2 = -45;
  8822. });
  8823. }
  8824. }
  8825. @Builder
  8826. private LyricsTopItem() {
  8827. Row() {
  8828. Stack() {
  8829. Image(this.cover)
  8830. .height(58)
  8831. .width(58)
  8832. .alt($r('app.media.alt'))
  8833. .borderRadius(8)
  8834. .clickEffect({ level: ClickEffectLevel.HEAVY })
  8835. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  8836. .shadow({
  8837. radius: 22,
  8838. type: ShadowType.BLUR,
  8839. color: 'on_primary'
  8840. })
  8841. }
  8842. .width('18%')
  8843. Column() {
  8844. Column() {
  8845. Text(this.name)
  8846. .fontSize(16)
  8847. .maxLines(1)
  8848. .fontWeight(FontWeight.Bolder)
  8849. .fontColor(this.currentLyricColor)
  8850. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  8851. Row() {
  8852. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  8853. .fontSize(13)
  8854. .fontWeight(FontWeight.Bold)
  8855. .padding({ top: 8 })
  8856. .fontColor(this.currentLyricColor)
  8857. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  8858. Blank()
  8859. }
  8860. }
  8861. .height('100%')
  8862. .width('100%')
  8863. .justifyContent(FlexAlign.Center)
  8864. .alignItems(HorizontalAlign.Start)
  8865. }
  8866. .height('100%')
  8867. .width('65%')
  8868. Column() {
  8869. Image($r('app.media.lyric'))
  8870. .width(28)
  8871. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8872. .margin({ right: 30 })
  8873. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8874. .onClick(() => {
  8875. this.isLyricSetting = !this.isLyricSetting;
  8876. })
  8877. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  8878. height: '95%',
  8879. dragBar: true,
  8880. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8881. showClose: true,
  8882. blurStyle: BlurStyle.Thin,
  8883. backgroundColor: Color.Transparent,
  8884. // title: { title: $r('app.string.lyric_setting') }
  8885. })
  8886. }
  8887. .width('18%')
  8888. }
  8889. .width('82%')
  8890. .height(58)
  8891. .justifyContent(FlexAlign.SpaceBetween)
  8892. }
  8893. //歌词显示
  8894. @Builder
  8895. PlayerLyrics() {
  8896. Column() {
  8897. Column() {
  8898. this.LyricsTopItem()
  8899. }
  8900. .height(this.isPuraWP() ? 15 : 58)
  8901. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  8902. Visibility.None : Visibility.Visible)
  8903. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  8904. .width("100%")
  8905. Column() {
  8906. LyricView2({
  8907. controller: this.lyricController,
  8908. enableSeek: true,
  8909. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  8910. seekLineColor: "#80ffffff", // 滑动定位线颜色
  8911. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  8912. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  8913. if (!this.isPlaying) {
  8914. console.info('onecold startPlayOrResumePlay 7527')
  8915. this.startPlayOrResumePlay()
  8916. }
  8917. else {
  8918. this.isSeekTo = true;
  8919. this.mDestroyPage = false;
  8920. this.showLoadIng();
  8921. this.seekTo(position + "");
  8922. this.isSeekTo = false;
  8923. }
  8924. return true
  8925. }
  8926. })
  8927. .width("100%")
  8928. .layoutWeight(1)
  8929. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  8930. if (this.isPhoneLan()) {
  8931. Column() {
  8932. this.playProgressView()
  8933. // this.playCenterView()
  8934. }
  8935. .margin({ bottom: 30, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  8936. }
  8937. }
  8938. .position({
  8939. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  8940. (this.isPuraWP() ? 58 : 99)
  8941. })
  8942. .justifyContent(FlexAlign.Center)
  8943. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  8944. }
  8945. }
  8946. @Builder
  8947. SingleLyricView() {
  8948. Column() {
  8949. Column() {
  8950. LyricView2({
  8951. controller: this.lyricControllerSingle,
  8952. enableSeek: false,
  8953. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  8954. seekLineColor: "#80ffffff", // 滑动定位线颜色
  8955. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  8956. })
  8957. }
  8958. .height(66)
  8959. .margin({ bottom: 20 })
  8960. }
  8961. }
  8962. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  8963. @Builder
  8964. BottomControl() {
  8965. Column() {
  8966. this.TopPlayProgressView()
  8967. //播放 暂停,下一首,上一首
  8968. this.playCenterView()
  8969. //播放进度条
  8970. this.BottomView()
  8971. }
  8972. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  8973. }
  8974. //播放控制上一首 下一首 暂停和播放
  8975. @Builder
  8976. playCenterView(){
  8977. Row() {
  8978. Button({type:ButtonType.Circle,stateEffect:true}){
  8979. //更多功能
  8980. Image($r('app.media.menu'))
  8981. .width(24)
  8982. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8983. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  8984. height: '99%',
  8985. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  8986. dragBar: true,
  8987. showClose: true,
  8988. blurStyle: BlurStyle.Thin,
  8989. backgroundColor: Color.Transparent,
  8990. })
  8991. }
  8992. .height(45)
  8993. .width(45)
  8994. .margin({ left: 5 })
  8995. .backgroundColor(Color.Transparent)
  8996. .onClick(() => {
  8997. this.isShowMoreView = !this.isShowMoreView;
  8998. })
  8999. Button({type:ButtonType.Circle,stateEffect:true}){
  9000. Image($r('app.media.ic_previous'))
  9001. .width(33)
  9002. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9003. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9004. }
  9005. .height(45)
  9006. .width(45)
  9007. .onClick(async () => {
  9008. await this.playPrevious()
  9009. })
  9010. .backgroundColor(Color.Transparent)
  9011. Button({type:ButtonType.Circle,stateEffect:true}){
  9012. Column() {
  9013. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  9014. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  9015. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  9016. .width(this.isPhoneLan()?45:55)
  9017. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9018. .fillColor(Color.White)
  9019. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9020. }
  9021. }
  9022. .onClick(async () => {
  9023. this.playOrPause()
  9024. })
  9025. .backgroundColor(Color.Transparent)
  9026. .layoutWeight(1)
  9027. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9028. Image($r('app.media.ic_next'))
  9029. .width(33)
  9030. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9031. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9032. }
  9033. .height(45)
  9034. .width(45)
  9035. .backgroundColor(Color.Transparent)
  9036. .onClick(async () => {
  9037. await this.playNext();
  9038. })
  9039. this.fullButton()
  9040. }
  9041. .width('95%')
  9042. .margin({ bottom:this.isCoverOpacity()?0:15 })
  9043. .justifyContent(FlexAlign.SpaceEvenly)
  9044. }
  9045. @Builder
  9046. TopPlayProgressView(){
  9047. Row() {
  9048. Column(){
  9049. Row(){
  9050. Stack(){
  9051. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  9052. .fontColor([Color.White])
  9053. .fontSize(21)
  9054. .effectStrategy(1)
  9055. Text(this.fastForwardSeconds)
  9056. .fontColor(Color.White)
  9057. .fontSize(10)
  9058. .fontWeight(FontWeight.Bold)
  9059. }
  9060. .margin({left:12,bottom:6})
  9061. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  9062. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9063. .onClick(()=>{
  9064. this.backForward()
  9065. })
  9066. Slider({
  9067. value: this.progressValue,
  9068. min: 0,
  9069. max: this.PROGRESS_MAX_VALUE,
  9070. step: 1,
  9071. style: SliderStyle.InSet
  9072. })
  9073. .height(20)
  9074. .blockColor('rgba(255,255,255,1)')
  9075. .trackColor('rgba(255,255,255,0.3)')
  9076. .selectedColor(Color.White)
  9077. .trackThickness(4)
  9078. .layoutWeight(1)
  9079. .showSteps(false)
  9080. .showTips(true)
  9081. .alignSelf(ItemAlign.Center)
  9082. .enabled(this.slideEnable)
  9083. .onChange((value: number, mode: SliderChangeMode) => {
  9084. // if (mode == 2) {
  9085. this.isSeekTo = true;
  9086. this.mDestroyPage = false;
  9087. this.showLoadIng();
  9088. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  9089. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  9090. this.seekTo(seekValue + "");
  9091. // this.setProgress()
  9092. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  9093. this.isSeekTo = false;
  9094. // }
  9095. })
  9096. Stack(){
  9097. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  9098. .fontColor([Color.White])
  9099. .fontSize(21)
  9100. .effectStrategy(1)
  9101. Text(this.fastForwardSeconds)
  9102. .fontColor(Color.White)
  9103. .fontSize(10)
  9104. .fontWeight(FontWeight.Bold)
  9105. }
  9106. .margin({right:10,bottom:6})
  9107. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  9108. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9109. .onClick(()=>{
  9110. this.fastForward()
  9111. })
  9112. }
  9113. .padding({ right: 7,left:22 })
  9114. Row(){
  9115. Text(this.currentTime)
  9116. .fontSize(10)
  9117. .fontColor(Color.White)
  9118. Blank()
  9119. .layoutWeight(1)
  9120. Text(this.totalTime)
  9121. .fontSize(10)
  9122. .fontColor(Color.White)
  9123. }
  9124. .justifyContent(FlexAlign.Start)
  9125. .padding({ right: 18,left:36 })
  9126. }
  9127. }
  9128. //x5的竖屏模式需要99%
  9129. .width(this.isLandscape?'80%':'93%')
  9130. .justifyContent(FlexAlign.Center)
  9131. .margin({bottom:3})
  9132. .animation({
  9133. duration: 666,
  9134. curve: 'ease-in-out' // 可选动画曲线
  9135. })
  9136. }
  9137. //播放进度条
  9138. @Builder
  9139. BottomView(){
  9140. Row() {
  9141. Button({type:ButtonType.Circle,stateEffect:true}){
  9142. Column() {
  9143. if (this.playType === 0) {
  9144. Image($r('app.media.loop'))
  9145. .width(27)
  9146. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9147. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9148. } else if (this.playType === 1) {
  9149. Image($r('app.media.single'))
  9150. .width(27)
  9151. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9152. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9153. } else if (this.playType === 2) {
  9154. Image($r('app.media.normal_play'))
  9155. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9156. .width(27)
  9157. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9158. } else if (this.playType === 3) {
  9159. Image($r('app.media.random'))
  9160. .width(27)
  9161. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9162. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9163. }
  9164. }
  9165. }
  9166. .layoutWeight(1)
  9167. .margin({ left: 5 })
  9168. .height(45)
  9169. .width(45)
  9170. .backgroundColor(Color.Transparent)
  9171. .onClick(async () => {
  9172. this.setLoopMode()
  9173. })
  9174. if(this.currentSong){
  9175. Button({type:ButtonType.Circle,stateEffect:true}){
  9176. Column() {
  9177. Image($r('app.media.rename2'))
  9178. .width(21)
  9179. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9180. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9181. }
  9182. }
  9183. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  9184. height: '99%',
  9185. dragBar: true,
  9186. showClose: true,
  9187. preferType: SheetType.BOTTOM,
  9188. title: { title: '编辑标签' }
  9189. })
  9190. .height(45)
  9191. .width(45)
  9192. .layoutWeight(1)
  9193. .backgroundColor(Color.Transparent)
  9194. .onClick(async () => {
  9195. this.initEditFields(this.currentSong)
  9196. this.tempLyricContent = this.lyricContent
  9197. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  9198. this.lyricConStr = this.tempLyricContent
  9199. }
  9200. this.isShowEdit = !this.isShowEdit;
  9201. })
  9202. }
  9203. Button({type:ButtonType.Circle,stateEffect:true}){
  9204. Column() {
  9205. Image($r('app.media.lyric'))
  9206. .width(26)
  9207. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9208. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9209. }
  9210. }
  9211. .height(45)
  9212. .width(45)
  9213. .layoutWeight(1)
  9214. .backgroundColor(Color.Transparent)
  9215. .onClick(async () => {
  9216. this.isLyricSetting = !this.isLyricSetting;
  9217. })
  9218. //播放列表
  9219. Button({type:ButtonType.Circle,stateEffect:true}){
  9220. Image($r('app.media.hm_playlist'))
  9221. .width(24)
  9222. .fillColor(Color.White)
  9223. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9224. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9225. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  9226. height: '95%',
  9227. dragBar: true,
  9228. showClose: true,
  9229. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9230. blurStyle: BlurStyle.Thin,
  9231. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  9232. title: {
  9233. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  9234. + `(${this.songList.length}首)`
  9235. }
  9236. })
  9237. }
  9238. .layoutWeight(1)
  9239. .height(45)
  9240. .width(45)
  9241. .backgroundColor(Color.Transparent)
  9242. .onClick(() => {
  9243. this.isShowSheetView = !this.isShowSheetView;
  9244. if(this.isPlayListBgGrass){
  9245. this.isFrontWhite = true
  9246. }else{
  9247. this.isFrontWhite = false
  9248. }
  9249. this.scrollIndex()
  9250. })
  9251. }
  9252. .width(this.isLandscape?'88%':'95%')
  9253. .justifyContent(FlexAlign.SpaceAround)
  9254. .height(30)
  9255. .animation({
  9256. duration: 666,
  9257. curve: 'ease-in-out' // 可选动画曲线
  9258. })
  9259. }
  9260. @Builder
  9261. fullButton(){
  9262. Button({type:ButtonType.Circle,stateEffect:true}){
  9263. Column() {
  9264. Image($r('app.media.full_4'))
  9265. .width(25)
  9266. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9267. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9268. }
  9269. }
  9270. .layoutWeight(1)
  9271. .backgroundColor(Color.Transparent)
  9272. .height(45)
  9273. .width(45)
  9274. .onClick(async () => {
  9275. if (this.isLandscape) {
  9276. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  9277. } else {
  9278. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  9279. }
  9280. })
  9281. }
  9282. //旧版本播放进度条
  9283. @Builder
  9284. playProgressView() {
  9285. Row() {
  9286. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9287. Column() {
  9288. if (this.playType === 0) {
  9289. Image($r('app.media.loop'))
  9290. .width($r('app.float.control_image_width'))
  9291. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9292. } else if (this.playType === 1) {
  9293. Image($r('app.media.single'))
  9294. .width($r('app.float.control_image_width'))
  9295. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9296. } else if (this.playType === 2) {
  9297. Image($r('app.media.normal_play'))
  9298. .width($r('app.float.control_image_width'))
  9299. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9300. } else if (this.playType === 3) {
  9301. Image($r('app.media.random'))
  9302. .width($r('app.float.control_image_width'))
  9303. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9304. }
  9305. }
  9306. }
  9307. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  9308. .animation({
  9309. duration: 666,
  9310. curve: 'ease-in-out' // 可选动画曲线
  9311. })
  9312. .backgroundColor(Color.Transparent)
  9313. .margin({ right: 10 })
  9314. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9315. .onClick(async () => {
  9316. this.setLoopMode()
  9317. })
  9318. Text(this.currentTime)
  9319. .fontSize($r('app.float.slider_font_size'))
  9320. .fontColor(Color.White)
  9321. .margin(3)
  9322. Slider({
  9323. value: this.progressValue,
  9324. min: 0,
  9325. max: this.PROGRESS_MAX_VALUE,
  9326. step: 1,
  9327. style: SliderStyle.OutSet
  9328. })
  9329. .width('600px')
  9330. .blockColor('rgba(255,255,255,1)')
  9331. .trackColor('rgba(255,255,255,0.3)')
  9332. .selectedColor(Color.White)
  9333. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  9334. .layoutWeight(1)
  9335. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  9336. .showSteps(false)
  9337. .showTips(true)
  9338. .enabled(this.slideEnable)
  9339. .onChange((value: number, mode: SliderChangeMode) => {
  9340. // if (mode == 2) {
  9341. this.isSeekTo = true;
  9342. this.mDestroyPage = false;
  9343. this.showLoadIng();
  9344. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  9345. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  9346. this.seekTo(seekValue + "");
  9347. // this.setProgress()
  9348. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  9349. this.isSeekTo = false;
  9350. // }
  9351. })
  9352. Text(this.totalTime)
  9353. .fontSize($r('app.float.slider_font_size'))
  9354. .fontColor(Color.White)
  9355. .margin(3)
  9356. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  9357. //播放列表
  9358. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9359. Image($r('app.media.hm_playlist'))
  9360. .width($r('app.float.control_image_width'))
  9361. .fillColor(Color.White)
  9362. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9363. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  9364. height: '95%',
  9365. dragBar: true,
  9366. showClose: true,
  9367. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9368. blurStyle: BlurStyle.Thin,
  9369. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  9370. title: {
  9371. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  9372. + `(${this.songList.length}首)`
  9373. }
  9374. })
  9375. }
  9376. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  9377. .animation({
  9378. duration: 666,
  9379. curve: 'ease-in-out' // 可选动画曲线
  9380. })
  9381. .backgroundColor(Color.Transparent)
  9382. .margin({ right: 20, left: 10 })
  9383. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9384. .onClick(() => {
  9385. this.isShowSheetView = !this.isShowSheetView;
  9386. if (this.isPlayListBgGrass) {
  9387. this.isFrontWhite = true
  9388. } else {
  9389. this.isFrontWhite = false
  9390. }
  9391. this.scrollIndex()
  9392. })
  9393. }
  9394. //x5的竖屏模式需要99%
  9395. .width(this.isPhonePortrait() ? '93.4%'
  9396. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  9397. .height(this.isPhoneLan() ? 25 : 33)
  9398. .animation({
  9399. duration: 666,
  9400. curve: 'ease-in-out' // 可选动画曲线
  9401. })
  9402. }
  9403. isBigScreen() {
  9404. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  9405. return true
  9406. }
  9407. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  9408. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  9409. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  9410. return false
  9411. } else {
  9412. return true
  9413. }
  9414. return false
  9415. }
  9416. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  9417. @State isCoverRectangle: boolean = false
  9418. @State isCoverTop: boolean = true
  9419. // 添加控制缩放的状态变量
  9420. @State scaleValueImage: number = 1
  9421. @State scaleValueText: number = 1
  9422. @Builder
  9423. CoverInfo() {
  9424. Column() {
  9425. //如果是方形,判断是不是封面在顶部,如果不是顶部,显示musicNameInfo, 如果是圆形显示musicNameInfo
  9426. if (this.isCoverRectangle) {
  9427. if (!this.isCoverTop) {
  9428. this.musicNameInfo(false)
  9429. }
  9430. } else {
  9431. this.musicNameInfo(false)
  9432. }
  9433. Stack() {
  9434. // 唱片旋转效果
  9435. Image($r('app.media.ic_music_disc'))
  9436. .width(245)
  9437. .height(245)
  9438. .margin({ right: 20, left: 20 ,top:this.isCoverRectangle||this.isLandscape?0:43})
  9439. .aspectRatio(1)
  9440. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  9441. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  9442. .borderRadius('100%')
  9443. .align(Alignment.Center)
  9444. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  9445. .rotate({
  9446. angle: this.rotateAngle,
  9447. centerX: "50%",
  9448. centerY: "50%",
  9449. })
  9450. .animation({
  9451. duration: 100,
  9452. curve: Curve.Linear
  9453. })
  9454. .shadow({
  9455. radius: 22,
  9456. type: ShadowType.BLUR,
  9457. color: 'on_primary'
  9458. })
  9459. Column() {
  9460. if (this.isCoverTop && this.isCoverRectangle) {
  9461. Image(this.cover)
  9462. .height(this.isHiCar()?(px2vp(this.windowHeight)*0.46):
  9463. this.isCoverOpacity()?(px2vp(this.windowHeight)*0.6):'auto')
  9464. .width(this.isHiCar()||this.isCoverOpacity()?'auto':this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '88%')
  9465. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  9466. .alt($r('app.media.alt'))
  9467. .margin({ right: 8, left: 8, top: 8 })
  9468. .aspectRatio(1)
  9469. .geometryTransition('cover') // 绑定标识符
  9470. .opacity(this.opacityValueImage)
  9471. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  9472. // 设置左下角为缩放中心点
  9473. centerX: '0%',
  9474. centerY: '100%' })
  9475. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  9476. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  9477. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  9478. .clip(true)
  9479. .rotate({
  9480. x: 0,
  9481. y: 0,
  9482. z: 1,
  9483. angle: this.rotateAngle
  9484. })
  9485. .shadow({
  9486. radius: 22,
  9487. type: ShadowType.BLUR,
  9488. color: 'on_primary'
  9489. })
  9490. .onClick(() => {
  9491. })
  9492. // .visualEffect(new hdsEffect.HdsEffectBuilder()
  9493. // .shaderEffect({
  9494. // effectType: hdsEffect.EffectType.DUAL_EDGE_FLOW_LIGHT,
  9495. // animation: {
  9496. // duration: 4000,
  9497. // iterations: -1,
  9498. // autoPlay: true,
  9499. // onFinish: () => {
  9500. // console.info('Succeeded in finishing');
  9501. // }
  9502. // },
  9503. // controller: this.controller,
  9504. // params: {
  9505. // firstEdgeFlowLight: {
  9506. // startPos: 0,
  9507. // endPos: 1.0,
  9508. // color: '#1AD0F1',
  9509. // },
  9510. // secondEdgeFlowLight: {
  9511. // startPos: 0.5,
  9512. // endPos: 1.5,
  9513. // color: '#FFA4E5',
  9514. // }
  9515. // }
  9516. // })
  9517. // .buildEffect())
  9518. this.musicNameInfo(false)
  9519. } else {
  9520. Image(this.cover)
  9521. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  9522. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 162))
  9523. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  9524. .alt($r('app.media.alt'))
  9525. .geometryTransition('cover') // 绑定标识符
  9526. .margin({ right: 20, left: 20,top:this.isCoverRectangle||this.isLandscape?0:43 })
  9527. .aspectRatio(1)
  9528. .opacity(this.opacityValueImage)
  9529. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  9530. // 设置左下角为缩放中心点
  9531. centerX: '0%',
  9532. centerY: '100%' })
  9533. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  9534. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  9535. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  9536. .align(Alignment.Center)//
  9537. .clip(true)
  9538. .shadow({
  9539. radius: 22,
  9540. type: ShadowType.BLUR,
  9541. color: 'on_primary'
  9542. })
  9543. .rotate({
  9544. x: 0,
  9545. y: 0,
  9546. z: 1,
  9547. angle: this.rotateAngle
  9548. })
  9549. .onClick(() => {
  9550. })
  9551. }
  9552. if (this.isPhoneLan()) {
  9553. Text(this.name)
  9554. .fontSize(18)
  9555. .fontWeight(FontWeight.Bold)
  9556. .margin({ top: 13 })
  9557. .textOverflow({ overflow: TextOverflow.Ellipsis })
  9558. .maxLines(1)
  9559. .width('99%')
  9560. .textAlign(TextAlign.Center)
  9561. .fontColor(Color.White)
  9562. }
  9563. }
  9564. // 唱针以左上角为点选择逆时针40度
  9565. Image($r('app.media.ic_music_cover_hand'))
  9566. .height(130)
  9567. .margin({ bottom: 220, top: 0 })
  9568. .align(Alignment.Top)
  9569. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  9570. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  9571. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  9572. Column({ space: 8 }) {
  9573. Text(this.name)
  9574. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  9575. .fontWeight(FontWeight.Bold)
  9576. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9577. .maxLines(1)
  9578. .width('48%')
  9579. .textAlign(TextAlign.Center)
  9580. .fontColor(Color.White)
  9581. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  9582. Text(this.artist)
  9583. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  9584. .fontColor(Color.White)
  9585. .fontWeight(FontWeight.Bold)
  9586. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  9587. }
  9588. .justifyContent(FlexAlign.Start)
  9589. .zIndex(1)
  9590. .geometryTransition('name')
  9591. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  9592. }
  9593. .margin({
  9594. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  9595. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  9596. top: this.isCoverOpacity() ? 0 : 20
  9597. })
  9598. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  9599. this.SingleLyricView()
  9600. }
  9601. if (this.isPhoneLan()) {
  9602. Column() {
  9603. this.playCenterView()
  9604. // this.playProgressView()
  9605. }
  9606. .position({ left: 28, bottom: 38 })
  9607. } else {
  9608. this.BottomControl()
  9609. }
  9610. }
  9611. .width(CommonConstants.FULL_PERCENT)
  9612. .clip(true)
  9613. }
  9614. @Builder
  9615. private musicNameInfo(isHidden: boolean) {
  9616. Row(){
  9617. Column({ space: 8 }) {
  9618. Text(this.name)
  9619. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 20)
  9620. .fontWeight(FontWeight.Bold)
  9621. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9622. .maxLines(1)
  9623. .width('99%')
  9624. .textAlign(TextAlign.Start)
  9625. .fontColor(Color.White)
  9626. Text(this.artist + ' ' + this.currentSong?.album)
  9627. .fontSize(this.isCoverOpacity() ? 12 : 15)
  9628. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9629. .fontColor(Color.White)
  9630. .textAlign(TextAlign.Start)
  9631. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  9632. .width('99%')
  9633. .maxLines(1)
  9634. }
  9635. .zIndex(1)
  9636. .geometryTransition('name') // 绑定标识符
  9637. .layoutWeight(1)
  9638. .margin({ left: 15 })
  9639. Blank()
  9640. Row(){
  9641. Button({type:ButtonType.Circle,stateEffect:true}){
  9642. //添加或取消收藏
  9643. SymbolGlyph(Utility.getIsFav(this.favList,this.currentSong)?
  9644. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'))
  9645. .fontSize(22)
  9646. .fontColor([Color.White])
  9647. .alignSelf(ItemAlign.Center)
  9648. // .width(24)
  9649. .clickEffect({level:ClickEffectLevel.MIDDLE})
  9650. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9651. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9652. .onClick(async () => {
  9653. if(this.currentSong){
  9654. this.doFav(this.currentSong)
  9655. }
  9656. })
  9657. }
  9658. .margin({ left: 15,right:3 })
  9659. .backgroundColor(Color.Transparent)
  9660. .width(45)
  9661. .height(45)
  9662. }
  9663. }
  9664. .width('90%')
  9665. .scale({ x: this.scaleValueText, y: this.scaleValueText }) // 添加缩放效果
  9666. .margin({ top: this.isCoverOpacity() ? 10 : isHidden ? 20 : 10 })
  9667. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  9668. }
  9669. @Builder
  9670. private PlayTitle() {
  9671. Row() {
  9672. Row() {
  9673. Image($r('app.media.ic_back_down'))
  9674. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  9675. .hitTestBehavior(HitTestMode.Transparent)
  9676. Text(this.name + ' ' + this.artist)
  9677. .fontColor(Color.White)
  9678. .fontSize($r('app.float.title_font_size'))
  9679. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9680. .maxLines(1)
  9681. .visibility(Visibility.None)
  9682. .margin({ left: 2, right: 30 })
  9683. }
  9684. .layoutWeight(1)
  9685. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9686. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  9687. .onClick(() => {
  9688. this.setShowPlayFalse()
  9689. })
  9690. Column() {
  9691. AVCastPicker({
  9692. normalColor: Color.White,
  9693. onStateChange: this.onStateVastChange
  9694. })
  9695. .width(24)
  9696. .height(24)
  9697. }
  9698. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  9699. }
  9700. .width(PlayConstants.ROW_WIDTH)
  9701. }
  9702. @Builder
  9703. lyricSettingSheet(isPip: boolean) {
  9704. Scroll() {
  9705. this.lyricSetting(isPip)
  9706. }
  9707. .width('100%')
  9708. .height('100%')
  9709. }
  9710. @Builder
  9711. lyricSetting(isPip: boolean) {
  9712. Column() {
  9713. // 时间调节模块
  9714. if (!isPip) {
  9715. this.BuildTimeControls()
  9716. }
  9717. // 字号控制模块
  9718. this.BuildFontControls(isPip)
  9719. }
  9720. }
  9721. // 歌词时间偏移状态
  9722. @State timeOffset: number = 0.0
  9723. @State currentLyricColor: string = '#FFFFFF'
  9724. @State currentLyricColorPip: string = '#FFFFFF'
  9725. @State currentHighLightLyricColor: string = '#FF4081'
  9726. @State currentHighLightLyricColorPip: string = '#FF4081'
  9727. // 歌词字号状态
  9728. @State currentLyricSize: number = 20
  9729. @State currentLyricSizePip: number = 20
  9730. // 高亮歌词放大倍数
  9731. @State currentHightLyricSize: number = 1.2
  9732. @State currentHightLyricSizePip: number = 1.2
  9733. @State currentLyricLineSpace: number = 10
  9734. @State currentLyricLineSpacePip: number = 10
  9735. @State currentLyricAlignMode: number = 1
  9736. @State currentLyricAlignModePip: number = 1
  9737. @State blurDegree: number = 2
  9738. @State blurDegreePip: number = 2
  9739. @State isShowSelectColor: boolean = false
  9740. @State isShowHLSelectColor: boolean = false
  9741. @State isShowPipBgSelectColor: boolean = false
  9742. @State pipLyWidth: number = 330
  9743. @State pipLyHeight: number = 120
  9744. // 构建颜色选择器
  9745. @Builder
  9746. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  9747. Row({ space: 10 }) {
  9748. HSBColorPicker({
  9749. color: '#FFFFFF',
  9750. radius: 8,
  9751. layout: HSBColorPickerLayout.COLUMN,
  9752. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  9753. '#fa7105'],
  9754. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  9755. this.changeLyricColor(value, isPip, isBGPip)
  9756. })
  9757. .height(250)
  9758. .layoutWeight(1)
  9759. .padding(25)
  9760. }
  9761. .width('66%')
  9762. }
  9763. @State isOpenPip: boolean = false
  9764. @State pipBgIndex: number = 0
  9765. // 构建字号控制器
  9766. @Builder
  9767. BuildFontControls(isPip: boolean) {
  9768. Column() {
  9769. if (isPip) {
  9770. Column() {
  9771. Row() {
  9772. Text('悬浮歌词')
  9773. .margin({ left: 18 })
  9774. .fontSize(15)
  9775. .fontColor(Color.White)
  9776. .fontWeight(480)
  9777. .layoutWeight(1)
  9778. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  9779. .selectedColor(this.themeColor)
  9780. .switchPointColor(Color.White)
  9781. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9782. .margin({ right: 18 })
  9783. .onChange((checked: boolean) => {
  9784. this.isOpenPip = checked;
  9785. if (this.isOpenPip) {
  9786. this.startPip()
  9787. } else {
  9788. this.stopPip()
  9789. }
  9790. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  9791. })
  9792. .width(50)
  9793. .height(30);
  9794. }
  9795. .height(55)
  9796. }
  9797. .backgroundColor(Color.Transparent)
  9798. .borderRadius(15)
  9799. .margin({
  9800. left: 30,
  9801. right: 30,
  9802. top: 0,
  9803. bottom: 20
  9804. })
  9805. .padding(0)
  9806. .border({
  9807. color: Color.White,
  9808. width: 1.8
  9809. })
  9810. }else{
  9811. Column() {
  9812. Row() {
  9813. Text('单行歌词')
  9814. .margin({ left: 18 })
  9815. .fontSize(15)
  9816. .fontColor(Color.White)
  9817. .fontWeight(480)
  9818. .layoutWeight(1)
  9819. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  9820. .selectedColor(this.themeColor)
  9821. .switchPointColor(Color.White)
  9822. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9823. .margin({ right: 18 })
  9824. .onChange((checked: boolean) => {
  9825. this.isShowSingleLineLyric = checked;
  9826. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  9827. })
  9828. .width(50)
  9829. .height(30);
  9830. }
  9831. .height(55)
  9832. }
  9833. .backgroundColor(Color.Transparent)
  9834. .borderRadius(15)
  9835. .margin({
  9836. left: 30,
  9837. right: 30,
  9838. top: 10,
  9839. bottom: 10
  9840. })
  9841. .padding(0)
  9842. .border({
  9843. color: Color.White,
  9844. width: 1.8
  9845. })
  9846. }
  9847. Row() {
  9848. Text(`歌词居中:`)
  9849. .fontSize(14)
  9850. .fontColor(Color.White)
  9851. .margin({ left: 2 })
  9852. Row() {
  9853. ForEach(['居中', '居左'], (size: string, index: number) => {
  9854. Button(size)
  9855. .width(60)
  9856. .height(28)
  9857. .fontSize(12)
  9858. .fontColor('#FFFFFF')
  9859. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  9860. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  9861. .border({
  9862. color: (!isPip && this.currentLyricAlignMode === index) ||
  9863. (isPip && this.currentLyricAlignModePip === index) ?
  9864. '#007DFF' : '#DDDDDD',
  9865. width: 1.8
  9866. })
  9867. .onClick(() => {
  9868. this.setLyricAlignMode(index, isPip)
  9869. })
  9870. .margin({ left: 10, right: 8 })
  9871. })
  9872. }
  9873. .width('76%')
  9874. Blank()
  9875. }
  9876. .margin({
  9877. top: 10,
  9878. bottom: 10,
  9879. right: 20,
  9880. left: 20
  9881. })
  9882. if (isPip) {
  9883. Row() {
  9884. Text(`悬浮背景:`)
  9885. .fontSize(14)
  9886. .fontColor(Color.White)
  9887. Select([
  9888. { value: CommonConstants.PIP_LYRIC_BG[0] },
  9889. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  9890. .font({ size: 13, weight: FontWeight.Medium })
  9891. .fontColor(Color.White)
  9892. .margin({ left: 10 })
  9893. .selected(this.pipBgIndex)
  9894. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  9895. .onSelect(async (_index: number, text?: string | undefined) => {
  9896. this.pipBgIndex = _index
  9897. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  9898. if (this.pipBgIndex === 0) {
  9899. if (this.cover) {
  9900. this.pipBg = this.cover
  9901. } else {
  9902. this.pipBg = this.imageColor
  9903. }
  9904. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  9905. } else {
  9906. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  9907. }
  9908. })
  9909. Column() {
  9910. }
  9911. .backgroundColor(this.pipBg)
  9912. .margin({ left: 10, right: 10 })
  9913. .borderRadius(20)
  9914. .height(28)
  9915. .width(28)
  9916. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9917. Row() {
  9918. SymbolGlyph($r('sys.symbol.paintbrush'))
  9919. .fontColor([Color.White])
  9920. .effectStrategy(1)
  9921. Text(`选择颜色`)
  9922. .fontSize(13)
  9923. .margin({ left: 10 })
  9924. .fontColor(Color.White)
  9925. }
  9926. }
  9927. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  9928. .backgroundColor(Color.Transparent)
  9929. .border({
  9930. color: '#FFFFFF',
  9931. radius: 20,
  9932. width: 1.8
  9933. })
  9934. .height(36)
  9935. .width(110)
  9936. .onClick(() => {
  9937. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  9938. })
  9939. .bindPopup(this.isShowPipBgSelectColor, {
  9940. builder: this.SelectColor(false, isPip, true),
  9941. placement: Placement.Top,
  9942. mask: { color: '#33000000' },
  9943. enableArrow: false, //是否显示箭头
  9944. showInSubWindow: false,
  9945. onStateChange: (e) => {
  9946. if (!e.isVisible) {
  9947. this.isShowPipBgSelectColor = false
  9948. }
  9949. }
  9950. })
  9951. }
  9952. .width('76%')
  9953. .margin({ bottom: 5, right: 45, left: 20 })
  9954. }
  9955. if (!isPip) {
  9956. Row() {
  9957. Text(`高亮居中:`)
  9958. .fontSize(14)
  9959. .fontColor(Color.White)
  9960. Column() {
  9961. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  9962. .selectedColor(this.themeColor)
  9963. .switchPointColor(Color.White)
  9964. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9965. .onChange((checked: boolean) => {
  9966. this.isHightLightCenter = checked;
  9967. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  9968. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  9969. })
  9970. .width(50)
  9971. .height(30)
  9972. .alignSelf(ItemAlign.Start)
  9973. .margin({ left: 12 })
  9974. Blank()
  9975. }
  9976. .width('76%')
  9977. }
  9978. .margin({
  9979. left: 20,
  9980. right: 15,
  9981. top: 10,
  9982. bottom: 10
  9983. })
  9984. }
  9985. Row() {
  9986. Text(`歌词颜色:`)
  9987. .fontSize(14)
  9988. .fontColor(Color.White)
  9989. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  9990. .fontSize(15)
  9991. .fontColor(Color.White)
  9992. .margin({ left: 12, right: 12 })
  9993. Column() {
  9994. }
  9995. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  9996. .margin({ right: 12 })
  9997. .borderRadius(20)
  9998. .height(28)
  9999. .width(28)
  10000. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10001. Row() {
  10002. SymbolGlyph($r('sys.symbol.paintbrush'))
  10003. .fontColor([Color.White])
  10004. .effectStrategy(1)
  10005. Text(`选择颜色`)
  10006. .fontSize(13)
  10007. .margin({ left: 10 })
  10008. .fontColor(Color.White)
  10009. }
  10010. }
  10011. .backgroundColor(Color.Transparent)
  10012. .border({
  10013. color: '#FFFFFF',
  10014. radius: 20,
  10015. width: 1.8
  10016. })
  10017. .height(36)
  10018. .width(110)
  10019. .onClick(() => {
  10020. this.isShowSelectColor = !this.isShowSelectColor
  10021. })
  10022. .bindPopup(this.isShowSelectColor, {
  10023. builder: this.SelectColor(false, isPip),
  10024. placement: Placement.Top,
  10025. mask: { color: '#33000000' },
  10026. enableArrow: false, //是否显示箭头
  10027. showInSubWindow: false,
  10028. onStateChange: (e) => {
  10029. if (!e.isVisible) {
  10030. this.isShowSelectColor = false
  10031. }
  10032. }
  10033. })
  10034. }
  10035. .width('76%')
  10036. .margin({
  10037. top: 10,
  10038. bottom: 10,
  10039. right: 45,
  10040. left: 20
  10041. })
  10042. Row() {
  10043. Text(`高亮颜色:`)
  10044. .fontSize(14)
  10045. .fontColor(Color.White)
  10046. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  10047. .fontSize(15)
  10048. .fontColor(Color.White)
  10049. .margin({ left: 12, right: 12 })
  10050. Column() {
  10051. }
  10052. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  10053. .margin({ right: 12 })
  10054. .borderRadius(20)
  10055. .height(28)
  10056. .width(28)
  10057. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10058. Row() {
  10059. SymbolGlyph($r('sys.symbol.paintbrush'))
  10060. .fontColor([Color.White])
  10061. .effectStrategy(1)
  10062. Text(`选择颜色`)
  10063. .fontSize(13)
  10064. .margin({ left: 10 })
  10065. .fontColor(Color.White)
  10066. }
  10067. }
  10068. .backgroundColor(Color.Transparent)
  10069. .border({
  10070. color: '#FFFFFF',
  10071. radius: 20,
  10072. width: 1.8
  10073. })
  10074. .height(36)
  10075. .width(110)
  10076. .onClick(() => {
  10077. this.isShowHLSelectColor = !this.isShowHLSelectColor
  10078. })
  10079. .bindPopup(this.isShowHLSelectColor, {
  10080. builder: this.SelectColor(true, isPip),
  10081. placement: Placement.Top,
  10082. mask: { color: '#33000000' },
  10083. enableArrow: false, //是否显示箭头
  10084. showInSubWindow: false,
  10085. onStateChange: (e) => {
  10086. if (!e.isVisible) {
  10087. this.isShowHLSelectColor = false
  10088. }
  10089. }
  10090. })
  10091. }
  10092. .width('76%')
  10093. .margin({
  10094. top: 10,
  10095. bottom: 10,
  10096. right: 45,
  10097. left: 20
  10098. })
  10099. if (isPip) {
  10100. Row() {
  10101. Text(`显示宽度:`)
  10102. .fontSize(14)
  10103. .fontColor(Color.White)
  10104. Slider({
  10105. value: this.pipLyWidth,
  10106. min: 10,
  10107. max: 800,
  10108. step: 1,
  10109. style: SliderStyle.OutSet
  10110. })
  10111. .blockColor(this.themeColor)
  10112. .trackColor($r('app.color.speed_text_color'))
  10113. .selectedColor(Color.White)
  10114. .trackThickness(6)
  10115. .onChange((value: number) => {
  10116. this.pipLyWidth = value
  10117. if (this.pipController) {
  10118. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10119. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  10120. }
  10121. })
  10122. .width('76%')
  10123. }
  10124. .margin({
  10125. left: 20,
  10126. right: 15,
  10127. top: 5,
  10128. bottom: 5
  10129. })
  10130. Row() {
  10131. Text(`显示高度:`)
  10132. .fontSize(14)
  10133. .fontColor(Color.White)
  10134. Slider({
  10135. value: this.pipLyHeight,
  10136. min: 10,
  10137. max: 1000,
  10138. step: 1,
  10139. style: SliderStyle.OutSet
  10140. })
  10141. .blockColor(this.themeColor)
  10142. .trackColor($r('app.color.speed_text_color'))
  10143. .selectedColor(Color.White)
  10144. .trackThickness(6)
  10145. .onChange((value: number) => {
  10146. this.pipLyHeight = value
  10147. if (this.pipController) {
  10148. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10149. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  10150. }
  10151. })
  10152. .width('76%')
  10153. }
  10154. .margin({
  10155. left: 20,
  10156. right: 15,
  10157. top: 5,
  10158. bottom: 5
  10159. })
  10160. }
  10161. Row() {
  10162. Text(`歌词字号:`)
  10163. .fontSize(14)
  10164. .fontColor(Color.White)
  10165. Slider({
  10166. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  10167. min: 12,
  10168. max: 30,
  10169. step: 0.1,
  10170. style: SliderStyle.OutSet
  10171. })
  10172. .blockColor(this.themeColor)
  10173. .trackColor($r('app.color.speed_text_color'))
  10174. .selectedColor(Color.White)
  10175. .trackThickness(6)
  10176. .onChange((value: number) => {
  10177. this.setLyricTextSize(value, isPip)
  10178. })
  10179. .width('76%')
  10180. }
  10181. .margin({
  10182. left: 20,
  10183. right: 15,
  10184. top: 5,
  10185. bottom: 5
  10186. })
  10187. Row() {
  10188. Text(`高亮倍数:`)
  10189. .fontSize(14)
  10190. .fontColor(Color.White)
  10191. Slider({
  10192. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  10193. min: 1,
  10194. max: 2,
  10195. step: 0.1,
  10196. style: SliderStyle.OutSet
  10197. })
  10198. .blockColor(this.themeColor)
  10199. .trackColor($r('app.color.speed_text_color'))
  10200. .selectedColor(Color.White)
  10201. .trackThickness(6)
  10202. .onChange((value: number) => {
  10203. this.setHighLyricTextSize(value, isPip)
  10204. })
  10205. .width('76%')
  10206. }
  10207. .margin({
  10208. left: 20,
  10209. right: 15,
  10210. top: 5,
  10211. bottom: 5
  10212. })
  10213. Row() {
  10214. Text(`歌词间隙:`)
  10215. .fontSize(14)
  10216. .fontColor(Color.White)
  10217. Slider({
  10218. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  10219. min: 0,
  10220. max: 100,
  10221. step: 1,
  10222. style: SliderStyle.OutSet
  10223. })
  10224. .blockColor(this.themeColor)
  10225. .trackColor($r('app.color.speed_text_color'))
  10226. .selectedColor(Color.White)
  10227. .trackThickness(6)
  10228. .onChange((value: number) => {
  10229. this.setLyricLineSpace(value, isPip)
  10230. })
  10231. .width('76%')
  10232. }
  10233. .margin({
  10234. left: 20,
  10235. right: 15,
  10236. top: 5,
  10237. bottom: 5
  10238. })
  10239. //取值间隔为100,默认为400,取值越大,字体越粗
  10240. Row() {
  10241. Text(`歌词字重:`)
  10242. .fontSize(14)
  10243. .fontColor(Color.White)
  10244. Slider({
  10245. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  10246. min: 100,
  10247. max: 900,
  10248. step: 100,
  10249. style: SliderStyle.OutSet
  10250. })
  10251. .blockColor(this.themeColor)
  10252. .trackColor($r('app.color.speed_text_color'))
  10253. .selectedColor(Color.White)
  10254. .trackThickness(6)
  10255. .onChange((value: number) => {
  10256. if (isPip) {
  10257. this.lyricTextWeightPip = value
  10258. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  10259. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  10260. } else {
  10261. this.lyricTextWeight = value
  10262. this.lyricController.setTextWeight(this.lyricTextWeight)
  10263. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  10264. }
  10265. })
  10266. .width('76%')
  10267. }
  10268. .margin({
  10269. left: 20,
  10270. right: 15,
  10271. top: 5,
  10272. bottom: 5
  10273. })
  10274. if (!isPip) {
  10275. Row() {
  10276. Text(`歌词模糊:`)
  10277. .fontSize(14)
  10278. .fontColor(Color.White)
  10279. Slider({
  10280. value: isPip ? this.blurDegreePip : this.blurDegree,
  10281. min: 0,
  10282. max: 5,
  10283. step: 0.1,
  10284. style: SliderStyle.OutSet
  10285. })
  10286. .blockColor(this.themeColor)
  10287. .trackColor($r('app.color.speed_text_color'))
  10288. .selectedColor(Color.White)
  10289. .trackThickness(6)
  10290. .onChange((value: number) => {
  10291. this.setBlurDegree(value, isPip)
  10292. })
  10293. .width('76%')
  10294. }
  10295. .margin({
  10296. left: 20,
  10297. right: 15,
  10298. top: 5,
  10299. bottom: 15
  10300. })
  10301. }
  10302. Row() {
  10303. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  10304. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  10305. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  10306. }
  10307. .justifyContent(FlexAlign.Center)
  10308. .margin({ top: 3, bottom: 10 })
  10309. }
  10310. }
  10311. private setBlurDegree(index: number, isPip: boolean) {
  10312. if (isPip) {
  10313. this.blurDegreePip = index
  10314. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  10315. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  10316. } else {
  10317. this.blurDegree = index
  10318. this.lyricController.setBlurDegree(this.blurDegree)
  10319. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  10320. }
  10321. }
  10322. private setLyricAlignMode(index: number, isPip: boolean) {
  10323. if (isPip) {
  10324. this.currentLyricAlignModePip = index
  10325. if (this.currentLyricAlignModePip === 1) {
  10326. this.lyricControllerXF.setAlignMode("left")
  10327. } else {
  10328. this.lyricControllerXF.setAlignMode("center")
  10329. }
  10330. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  10331. } else {
  10332. this.currentLyricAlignMode = index
  10333. if (this.currentLyricAlignMode === 1) {
  10334. this.lyricController.setAlignMode("left")
  10335. } else {
  10336. this.lyricController.setAlignMode("center")
  10337. }
  10338. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  10339. }
  10340. }
  10341. private setLyricTextSize(index: number, isPip: boolean) {
  10342. if (isPip) {
  10343. this.currentLyricSizePip = index
  10344. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  10345. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  10346. } else {
  10347. this.currentLyricSize = index
  10348. this.lyricController.setTextSize(this.currentLyricSize)
  10349. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  10350. }
  10351. }
  10352. private setHighLyricTextSize(scale: number, isPip: boolean) {
  10353. if (isPip) {
  10354. this.currentHightLyricSizePip = scale
  10355. this.lyricControllerXF
  10356. .setHighlightScale(this.currentHightLyricSizePip)
  10357. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  10358. } else {
  10359. this.currentHightLyricSize = scale
  10360. this.lyricController
  10361. .setHighlightScale(this.currentHightLyricSize)
  10362. PreferencesUtil.putSync('HighLyricTextSize', scale)
  10363. }
  10364. }
  10365. private setLyricLineSpace(index: number, isPip: boolean) {
  10366. if (isPip) {
  10367. this.currentLyricLineSpacePip = index
  10368. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  10369. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  10370. } else {
  10371. this.currentLyricLineSpace = index
  10372. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  10373. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  10374. }
  10375. }
  10376. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  10377. LogUtil.info('onecold isBG = ' + isBG)
  10378. if (isBG) { //如果是设置悬浮背景
  10379. this.pipBg = color
  10380. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  10381. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  10382. return
  10383. }
  10384. if (isPip) {
  10385. this.currentLyricColorPip = color
  10386. this.lyricControllerXF
  10387. .setTextColor(this.currentLyricColorPip)
  10388. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  10389. } else {
  10390. this.currentLyricColor = color
  10391. this.lyricController
  10392. .setTextColor(this.currentLyricColor)
  10393. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  10394. }
  10395. }
  10396. private changeLyricHightLightColor(color: string, isPip: boolean) {
  10397. if (isPip) {
  10398. this.currentHighLightLyricColorPip = color
  10399. this.lyricControllerXF
  10400. .setHighlightColor(this.currentHighLightLyricColorPip)
  10401. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  10402. } else {
  10403. this.currentHighLightLyricColor = color
  10404. this.lyricController
  10405. .setHighlightColor(this.currentHighLightLyricColor)
  10406. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  10407. }
  10408. }
  10409. // 构建时间控制器
  10410. @Builder
  10411. BuildTimeControls() {
  10412. Column() {
  10413. // 时间显示
  10414. Text(this.getTimeText())
  10415. .fontSize(18)
  10416. .fontColor(Color.White)
  10417. .margin({ bottom: 10 })
  10418. Row() {
  10419. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  10420. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  10421. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  10422. }
  10423. .justifyContent(FlexAlign.Center)
  10424. }
  10425. .margin({ top: 12, bottom: 8 })
  10426. }
  10427. // 精度按钮组件
  10428. @Builder
  10429. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  10430. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10431. Column() {
  10432. Image(icon)
  10433. .width(28)
  10434. .margin({ bottom: 5 })
  10435. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  10436. Text(label)
  10437. .fontSize(12)
  10438. .fontColor('#FFFFFF')
  10439. }
  10440. }
  10441. .backgroundColor(Color.Transparent)
  10442. .enabled(!this.isButtonDisabled(step))
  10443. .onClick(() => this.handlePrecisionAdjust(step))
  10444. .padding(5)
  10445. .width(66)
  10446. .height(66)
  10447. .margin({ left: 18, right: 18 })
  10448. .border({
  10449. color: '#FFFFFF',
  10450. width: 1.8
  10451. })
  10452. }
  10453. private handlePrecisionAdjust(step: number) {
  10454. if (step === 0) {
  10455. this.timeOffset = 0
  10456. return
  10457. }
  10458. // 精度处理:保留1位小数
  10459. const newOffset = Number((this.timeOffset + step).toFixed(5))
  10460. // 边界保护(±15.0秒)
  10461. if (newOffset < -30.0 || newOffset > 30.0) {
  10462. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  10463. return
  10464. }
  10465. // 状态更新
  10466. this.timeOffset = newOffset
  10467. }
  10468. // 按钮禁用逻辑
  10469. private isButtonDisabled(step: number): boolean {
  10470. const futureOffset = this.timeOffset + step
  10471. return (futureOffset < -30.0) || (futureOffset > 30.0)
  10472. }
  10473. // 时间显示文本升级
  10474. private getTimeText(): string {
  10475. const absValue = Math.abs(this.timeOffset)
  10476. return this.timeOffset === 0
  10477. ? '歌词时间已重置'
  10478. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  10479. }
  10480. // 导入 本地歌词 搜索歌词
  10481. @Builder
  10482. pushLyricButton(icon: Resource, step: number, label: string) {
  10483. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10484. Row() {
  10485. Image(icon)
  10486. .width(14)
  10487. .margin({ left: 13 })
  10488. Text(label)
  10489. .fontSize(12)
  10490. .margin({ left: 6 })
  10491. .fontColor('#FFFFFF')
  10492. }
  10493. }
  10494. .onClick(() => {
  10495. switch (step) {
  10496. case 0:
  10497. this.callFilePickerSelectFileForLyric()
  10498. break;
  10499. case 1:
  10500. //判断有没有设置api
  10501. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  10502. this.isLyricSetting = false
  10503. this.showTipsDialog()
  10504. return
  10505. }
  10506. if (StrUtil.isNotEmpty(this.videoUrl)) {
  10507. ToastUtil.showToast('正在获取')
  10508. this.isLyricSetting = false
  10509. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  10510. this.initLyric(lyricPath, true);
  10511. }
  10512. break;
  10513. }
  10514. })
  10515. .padding(5)
  10516. .width(110)
  10517. .backgroundColor(Color.Transparent)
  10518. .height(40)
  10519. .margin({ left: 6, right: 6 })
  10520. .border({
  10521. color: '#FFFFFF',
  10522. radius: 20,
  10523. width: 1.8
  10524. })
  10525. }
  10526. showVipDialog() {
  10527. DialogHelper.showCustomContentDialog({
  10528. dialogId: 'vip',
  10529. title: "友情提示",
  10530. autoCancel: false, //点击遮障层时,不关闭弹窗
  10531. backCancel: true, //点击返回键,不关闭弹窗
  10532. contentBuilder: () => {
  10533. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  10534. },
  10535. buttons: [],
  10536. })
  10537. }
  10538. //去赞助的自定义内容
  10539. @Builder
  10540. customVipBuilder(content: string) {
  10541. Column() {
  10542. Text(content)
  10543. .fontColor(Color.Gray)
  10544. .fontSize(16)
  10545. .alignSelf(ItemAlign.Start)
  10546. .margin({ bottom: 15 })
  10547. .fontSize(16)
  10548. Row() {
  10549. Button('取消')
  10550. .fontColor(Color.White)
  10551. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  10552. .height(50)
  10553. .layoutWeight(1)
  10554. .stateEffect(true)
  10555. .margin({ right: 6 })
  10556. .onClick(() => {
  10557. DialogHelper.closeDialog('vip'); //关闭弹框
  10558. })
  10559. Button('开通')
  10560. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  10561. .layoutWeight(1)
  10562. .height(50)
  10563. .backgroundColor(this.themeColor)
  10564. .stateEffect(true)
  10565. .margin({ left: 6 })
  10566. .onClick(() => {
  10567. DialogHelper.closeDialog('vip'); //关闭弹框
  10568. this.isShowPlay = false
  10569. this.mType = 1 //跳转到用户中心
  10570. // router.pushUrl({
  10571. // url: 'pages/VipPage'
  10572. // }, router.RouterMode.Single);
  10573. })
  10574. }
  10575. }
  10576. .width("100%")
  10577. .padding(10)
  10578. }
  10579. showTipsDialog() {
  10580. DialogHelper.showCustomContentDialog({
  10581. dialogId: 'tips',
  10582. title: "友情提示",
  10583. autoCancel: false, //点击遮障层时,不关闭弹窗
  10584. backCancel: true, //点击返回键,不关闭弹窗
  10585. contentBuilder: () => {
  10586. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  10587. },
  10588. buttons: [],
  10589. })
  10590. }
  10591. @Builder
  10592. customTipsBuilder(content: string) {
  10593. Column() {
  10594. Text(content)
  10595. .fontColor(Color.Gray)
  10596. .fontSize(16)
  10597. .alignSelf(ItemAlign.Start)
  10598. .margin({ bottom: 15 })
  10599. .fontSize(16)
  10600. Row() {
  10601. Button('取消')
  10602. .fontColor(Color.White)
  10603. .backgroundColor(this.themeColor)
  10604. .height(50)
  10605. .layoutWeight(1)
  10606. .stateEffect(true)
  10607. .margin({ right: 6 })
  10608. .onClick(() => {
  10609. DialogHelper.closeDialog('tips'); //关闭弹框
  10610. })
  10611. Button('跳转')
  10612. .fontColor(Color.White)//
  10613. .layoutWeight(1)
  10614. .height(50)
  10615. .backgroundColor(this.themeColor)
  10616. .stateEffect(true)
  10617. .margin({ left: 6 })
  10618. .onClick(() => {
  10619. DialogHelper.closeDialog('tips'); //关闭弹框
  10620. this.isShowEdit = false
  10621. this.longItemFilePath = ''
  10622. // if(this.isGridMusic&&!this.isShowPlay){
  10623. // this.longItemFilePath== ''
  10624. // }else{
  10625. // this.isShowEdit = false
  10626. // }
  10627. this.isShowMoreView = false;
  10628. this.isShowPlay = false
  10629. this.mType = 4
  10630. // router.pushUrl({
  10631. // url: 'pages/SettingPage'
  10632. // }, router.RouterMode.Single);
  10633. })
  10634. }
  10635. }
  10636. .width("100%")
  10637. .padding(10)
  10638. }
  10639. @Builder
  10640. PlayMoreSheet() {
  10641. Column() {
  10642. this.MoreList()
  10643. }
  10644. .width('100%')
  10645. .height('100%')
  10646. }
  10647. @Builder
  10648. MoreList() {
  10649. Scroll() {
  10650. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  10651. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  10652. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10653. Row() {
  10654. if (more.id === 3&&this.currentSong) {
  10655. Image(more.image)
  10656. .width(24)
  10657. .height(24)
  10658. .margin({ left: 10, right: 10 })
  10659. Text(more.title)
  10660. .fontSize(16)
  10661. .fontColor(Color.White)
  10662. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  10663. height: this.isCoverOpacity() ? '95%' : '95%',
  10664. dragBar: true,
  10665. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  10666. showClose: true,
  10667. blurStyle: BlurStyle.Thin,
  10668. backgroundColor: Color.Transparent,
  10669. title: { title: '歌曲信息' }
  10670. })
  10671. } else if (more.id === 15 && this.currentSong) { //编辑标签
  10672. Image(more.image)
  10673. .width(24)
  10674. .height(24)
  10675. .margin({ left: 10, right: 10 })
  10676. Text(more.title)
  10677. .fontSize(16)
  10678. .fontColor(Color.White)
  10679. } else if (more.id === 5) { //定时关闭
  10680. Image(more.image)
  10681. .width(24)
  10682. .height(24)
  10683. .margin({ left: 10, right: 10 })
  10684. Text(more.title)
  10685. .fontSize(16)
  10686. .fontColor(Color.White)
  10687. .onClick(() => {
  10688. this.doMore(more.id)
  10689. })
  10690. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  10691. height: this.isCoverOpacity() ? '95%' : '95%',
  10692. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  10693. dragBar: true,
  10694. showClose: true,
  10695. title: { title: $r('app.string.time_close') }
  10696. })
  10697. } else if (more.id === 2) { //歌词设置
  10698. Image(more.image)
  10699. .width(24)
  10700. .height(24)
  10701. .margin({ left: 10, right: 10 })
  10702. Text(more.title)
  10703. .fontSize(16)
  10704. .fontColor(Color.White)
  10705. } else if (more.id === 16) { //悬浮歌词设置
  10706. Image(more.image)
  10707. .width(24)
  10708. .height(24)
  10709. .margin({ left: 10, right: 10 })
  10710. Text(more.title)
  10711. .fontSize(16)
  10712. .fontColor(Color.White)
  10713. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  10714. height: this.isCoverOpacity() ? '95%' : '95%',
  10715. dragBar: true,
  10716. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  10717. showClose: true,
  10718. blurStyle: BlurStyle.Thin,
  10719. backgroundColor: Color.Transparent,
  10720. title: { title: '悬浮歌词' }
  10721. })
  10722. } else if (more.id === 11) {
  10723. Image(more.image)
  10724. .width(24)
  10725. .height(24)
  10726. .margin({ left: 10, right: 10 })
  10727. Text(more.title)
  10728. .fontSize(16)
  10729. .fontColor(Color.White)
  10730. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  10731. height: this.isCoverOpacity() ? '95%' : '60%',
  10732. dragBar: true,
  10733. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  10734. showClose: true,
  10735. blurStyle: BlurStyle.Thin,
  10736. backgroundColor: Color.Transparent,
  10737. title: { title: '跳过头尾' }
  10738. })
  10739. } else if (more.id === 12) { //投播
  10740. AVCastPicker({
  10741. customPicker: (): void => this.TPImageBuilder(more),
  10742. onStateChange: (state) => {
  10743. if (state == AVCastPickerState.STATE_APPEARING) {
  10744. console.log(' The picker starts showing.');
  10745. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  10746. console.log(' The picker finishes presenting.');
  10747. }
  10748. },
  10749. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  10750. sessionType: 'video'
  10751. })
  10752. .id('AVCastPicker')
  10753. } else {
  10754. Image(more.image)
  10755. .width(24)
  10756. .height(24)
  10757. .fillColor(Color.White)
  10758. .margin({ left: 10, right: 10 })
  10759. .onClick(() => {
  10760. this.doMore(more.id)
  10761. })
  10762. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  10763. .fontSize(16)
  10764. .fontColor(Color.White)
  10765. .onClick(() => {
  10766. this.doMore(more.id)
  10767. })
  10768. Select([//倍速
  10769. { value: '0.25x' },
  10770. { value: '0.5x' },
  10771. { value: '0.75x' },
  10772. { value: '1x' },
  10773. { value: '1.25x' },
  10774. { value: '1.5x' },
  10775. { value: '1.75x' },
  10776. { value: '2x' },
  10777. { value: '3x' }])
  10778. .font({ size: 16, weight: FontWeight.Medium })
  10779. .fontColor($r('sys.color.white'))
  10780. .margin({ left: 25 })
  10781. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  10782. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  10783. .value(Utility.optimizedFormat(this.playSpeed))
  10784. .onSelect(async (_index: number, text?: string | undefined) => {
  10785. let speed = parseFloat(text?.replace('x', '') || '1');
  10786. if (!CommonConstants.video_speed_list.includes(speed)) {
  10787. speed = 1;
  10788. }
  10789. this.playSpeed = speed
  10790. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  10791. })
  10792. Slider({
  10793. value: this.volume,
  10794. min: 0,
  10795. max: 1,
  10796. step: 0.1,
  10797. style: SliderStyle.OutSet
  10798. })
  10799. .margin({ left: 18, right: 8 })
  10800. .blockColor(this.themeColor)
  10801. .trackColor($r('app.color.speed_text_color'))
  10802. .selectedColor(Color.White)
  10803. .trackThickness(9)
  10804. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  10805. .onChange((value: number) => {
  10806. this.volume = value;
  10807. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  10808. PreferencesUtil.putSync('DefalutVolume',this.volume)
  10809. })
  10810. .layoutWeight(1)
  10811. Blank()
  10812. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  10813. .selectedColor(this.themeColor)
  10814. .switchPointColor(Color.White)
  10815. .margin({ right: 15 })
  10816. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10817. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  10818. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  10819. if (more.id == 6) {
  10820. this.isMusicMemoryPlay = checked;
  10821. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  10822. if (this.isMusicMemoryPlay) {
  10823. ToastUtil.showToast('记忆播放已开启')
  10824. } else {
  10825. ToastUtil.showToast('记忆播放已关闭')
  10826. }
  10827. }
  10828. })
  10829. .width(48)
  10830. .height(24);
  10831. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  10832. .selectedColor(this.themeColor)
  10833. .switchPointColor(Color.White)
  10834. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10835. .margin({ right: 15 })
  10836. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  10837. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  10838. if (more.id == 7) {
  10839. this.isMusicBGCover = checked;
  10840. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  10841. if (this.isMusicBGCover) {
  10842. ToastUtil.showToast('播放背景随音乐封面已开启')
  10843. } else {
  10844. ToastUtil.showToast('播放背景随音乐封面已关闭')
  10845. }
  10846. }
  10847. })
  10848. .width(48)
  10849. .height(24);
  10850. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  10851. .selectedColor(this.themeColor)
  10852. .switchPointColor(Color.White)
  10853. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10854. .margin({ right: 15 })
  10855. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  10856. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  10857. if (more.id == 8) {
  10858. this.isSavePlayMode = checked;
  10859. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  10860. if (this.isSavePlayMode) {
  10861. ToastUtil.showToast('保存播放模式已开启')
  10862. } else {
  10863. ToastUtil.showToast('保存播放模式已关闭')
  10864. }
  10865. }
  10866. })
  10867. .width(48)
  10868. .height(24);
  10869. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  10870. .selectedColor(this.themeColor)
  10871. .switchPointColor(Color.White)
  10872. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10873. .margin({ right: 15 })
  10874. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  10875. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  10876. if (more.id == 13) {
  10877. this.isCoverRectangle = checked;
  10878. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  10879. if (this.isCoverRectangle) {
  10880. ToastUtil.showToast('封面方形已开启')
  10881. this.animationRoFun()
  10882. } else {
  10883. ToastUtil.showToast('封面圆形已开启')
  10884. this.animationRoFun()
  10885. }
  10886. }
  10887. })
  10888. .width(48)
  10889. .height(24);
  10890. Toggle({ type: ToggleType.Switch, isOn: this.isShowBgLiuGUANG })
  10891. .selectedColor(this.themeColor)
  10892. .switchPointColor(Color.White)
  10893. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10894. .margin({ right: 15 })
  10895. .visibility(more.id == 21 ? Visibility.Visible : Visibility.None)
  10896. .onChange((checked: boolean) => { // 是否开启背景流光效果
  10897. if (more.id == 21) {
  10898. this.isShowBgLiuGUANG = checked;
  10899. PreferencesUtil.putSync('isShowBgLiuGUANG',this.isShowBgLiuGUANG)
  10900. }
  10901. })
  10902. .width(48)
  10903. .height(24);
  10904. }
  10905. }
  10906. .width('100%')
  10907. .height(45)
  10908. .padding(15)
  10909. .backgroundColor(Color.Transparent)
  10910. .borderRadius(12)
  10911. .margin({ bottom: 6 })
  10912. }
  10913. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  10914. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  10915. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  10916. .backgroundColor(Color.Transparent)
  10917. .onClick(() => {
  10918. this.doMore(more.id)
  10919. })
  10920. });
  10921. }
  10922. .width('100%')
  10923. .padding(16)
  10924. }.margin({ bottom: 18 })
  10925. }
  10926. @Builder
  10927. TPImageBuilder(more: MoreItem): void {
  10928. Row() {
  10929. Image($r('app.media.tuoping'))
  10930. .width(22)
  10931. .height(22)
  10932. .margin({ left: 10, right: 10 })
  10933. Text(more.title)
  10934. .fontSize(16)
  10935. .fontColor(Color.White)
  10936. }
  10937. .width('100%')
  10938. .layoutWeight(1)
  10939. .alignItems(VerticalAlign.Center)
  10940. .justifyContent(FlexAlign.Start)
  10941. }
  10942. private moreItems: MoreItem[] = [
  10943. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  10944. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  10945. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  10946. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  10947. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  10948. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  10949. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  10950. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  10951. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  10952. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  10953. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  10954. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  10955. { id: 4, image: $r('app.media.share2'), title: '分享' },
  10956. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  10957. // { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  10958. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  10959. { id : 21, image: $r('app.media.music_red'), title: '开启背景流光' },
  10960. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  10961. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  10962. ];
  10963. @State isShowBgLiuGUANG: boolean = true;
  10964. @State isShowMoreView: boolean = false;
  10965. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  10966. @State isShowTimeCloseMore: boolean = false
  10967. @State isShowDetailMore: boolean = false
  10968. @State isMusicBGCover: boolean = true
  10969. @State isSavePlayMode: boolean = true
  10970. @State isLyricSetting: boolean = false
  10971. @State isJumpSetting: boolean = false
  10972. @State isShowEdit: boolean = false
  10973. @State showPipLyric: boolean = false
  10974. async setRingTone() {
  10975. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  10976. return
  10977. }
  10978. // 确定后的逻辑
  10979. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  10980. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  10981. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  10982. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  10983. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  10984. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  10985. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  10986. , this.videoUrl, this.name).then(res => {
  10987. LogUtil.info('onecold setFlag :' + res);
  10988. });
  10989. }
  10990. doMore(moreId: number) {
  10991. switch (moreId) {
  10992. case 2: //歌词
  10993. this.isLyricSetting = !this.isLyricSetting;
  10994. this.isShowMoreView = false
  10995. break;
  10996. case 3: //详情
  10997. this.isShowDetailMore = !this.isShowDetailMore;
  10998. break;
  10999. case 4: //分享
  11000. if (this.currentSong !== undefined) {
  11001. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  11002. }
  11003. this.isShowMoreView = false
  11004. break;
  11005. case 5: //定时关闭
  11006. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  11007. break;
  11008. case 10: //设为铃声
  11009. this.setRingTone()
  11010. this.isShowMoreView = false
  11011. break;
  11012. case 11: //跳过头尾
  11013. this.isJumpSetting = !this.isJumpSetting;
  11014. break;
  11015. case 13: //倍速
  11016. break;
  11017. case 14: //搜索封面
  11018. if (this.currentSong !== undefined) {
  11019. this.doSearchCover(this.currentSong)
  11020. }
  11021. this.isShowMoreView = false
  11022. break;
  11023. case 15: //编辑标签
  11024. this.initEditFields(this.currentSong)
  11025. this.tempLyricContent = this.lyricContent
  11026. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  11027. this.lyricConStr = this.tempLyricContent
  11028. }
  11029. this.isShowEdit = !this.isShowEdit;
  11030. break;
  11031. case 16: //悬浮歌词
  11032. this.showPipLyric = !this.showPipLyric;
  11033. break;
  11034. case 17: //横屏模式
  11035. if (this.isLandscape) {
  11036. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  11037. } else {
  11038. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  11039. }
  11040. this.isShowMoreView = false
  11041. break;
  11042. case 20://AB循环
  11043. this.isABSheet = !this.isABSheet
  11044. break;
  11045. }
  11046. }
  11047. //AB循环
  11048. @State isOpenAB:boolean = false
  11049. @State jumpATime:number = 0
  11050. @State jumpBTime:number = 0
  11051. @State isABSheet:boolean = false
  11052. @Builder
  11053. ABLoopSheet() {
  11054. ABLoopComptent({
  11055. jumpATime:this.jumpATime,
  11056. jumpBTime:this.jumpBTime,
  11057. onClickAItem: async ()=>{
  11058. if(this.mIjkMediaPlayer){
  11059. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  11060. }
  11061. },
  11062. onClickBItem: async ()=>{
  11063. if(this.mIjkMediaPlayer){
  11064. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  11065. if(this.jumpBTime<=this.jumpATime){
  11066. ToastUtil.showToast('设置B点时间不能小于A点时间')
  11067. this.jumpBTime = 0
  11068. }
  11069. }
  11070. },
  11071. onCancleButtonClick: async ()=>{
  11072. this.isOpenAB = false
  11073. this.isABSheet = false
  11074. },
  11075. onStartButtonClick: async ()=>{
  11076. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  11077. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  11078. return
  11079. }
  11080. this.isABSheet = false
  11081. this.startABLoop()
  11082. },
  11083. })
  11084. }
  11085. //开始AB循环
  11086. startABLoop(){
  11087. if(this.mIjkMediaPlayer){
  11088. this.seekTo(this.jumpATime+'')
  11089. this.isOpenAB = true
  11090. }
  11091. }
  11092. /**
  11093. * 切换横竖屏
  11094. *
  11095. */
  11096. setOrientation(orientation: number) {
  11097. this.windowClass.setPreferredOrientation(orientation).then(() => {
  11098. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  11099. }).catch((err: BusinessError) => {
  11100. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  11101. });
  11102. }
  11103. /**
  11104. * 画中画功能(悬浮歌词功能)
  11105. *
  11106. */
  11107. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  11108. pipController?: PiPWindow.PiPController;
  11109. navigationId: string = '';
  11110. @State curState: string = '';
  11111. @State curError: ResourceStr = '';
  11112. @State pipBg: string = '#E8E8E8'
  11113. @State buttonAction: string = '';
  11114. //开启画中画功能
  11115. async startPip() {
  11116. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  11117. if (!this.pipController) {
  11118. await this.createPipController();
  11119. }
  11120. if (!this.pipController) {
  11121. Logger.info(`[${TAG}] pipController create error`);
  11122. return;
  11123. }
  11124. await this.pipController.startPiP();
  11125. }
  11126. async stopPip() {
  11127. if (!this.pipController) {
  11128. Logger.info(`[${TAG}] pipController is not exist`);
  11129. return;
  11130. }
  11131. this.isOpenPip = false
  11132. await this.pipController.stopPiP();
  11133. }
  11134. async createPipController() {
  11135. this.pipController = await PiPWindow.create({
  11136. context: getContext(this),
  11137. componentController: this.xcomponentController,
  11138. navigationId: this.navigationId,
  11139. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  11140. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  11141. customUIController: this.nodeController,
  11142. });
  11143. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  11144. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  11145. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  11146. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  11147. this.onStateChange(state, reason);
  11148. });
  11149. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  11150. this.onActionEvent(event, status);
  11151. });
  11152. }
  11153. destroyPipController() {
  11154. if (!this.pipController) {
  11155. return;
  11156. }
  11157. this.pipController.off('stateChange');
  11158. this.pipController.off('controlPanelActionEvent');
  11159. this.pipController = undefined;
  11160. }
  11161. onStateChange(state: PiPWindow.PiPState, reason: string) {
  11162. switch (state) {
  11163. case PiPWindow.PiPState.ABOUT_TO_START:
  11164. this.curState = 'ABOUT_TO_START';
  11165. this.curError = $r('app.string.current_error_hint');
  11166. break;
  11167. case PiPWindow.PiPState.STARTED:
  11168. this.curState = 'STARTED';
  11169. this.curError = $r('app.string.current_error_hint');
  11170. break;
  11171. case PiPWindow.PiPState.ABOUT_TO_STOP:
  11172. this.curState = 'ABOUT_TO_STOP';
  11173. this.curError = $r('app.string.current_error_hint');
  11174. break;
  11175. case PiPWindow.PiPState.STOPPED:
  11176. this.curState = 'STOPPED';
  11177. this.curError = $r('app.string.current_error_hint');
  11178. this.stopPip()
  11179. this.destroyPipController()
  11180. break;
  11181. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  11182. this.curState = 'ABOUT_TO_RESTORE';
  11183. this.curError = $r('app.string.current_error_hint');
  11184. break;
  11185. case PiPWindow.PiPState.ERROR:
  11186. this.curState = 'ERROR';
  11187. this.curError = reason;
  11188. break;
  11189. default:
  11190. break;
  11191. }
  11192. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  11193. }
  11194. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  11195. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  11196. switch (event) {
  11197. case 'playbackStateChanged':
  11198. if (status === 0) {
  11199. this.pause();
  11200. } else {
  11201. console.info('onecold startPlayOrResumePlay 9869')
  11202. this.startPlayOrResumePlay();
  11203. }
  11204. break;
  11205. case 'nextVideo':
  11206. // 切换到下一个视频
  11207. this.playNext().catch(() => {
  11208. Logger.error('heanup onActionEvent playNext', `播放下一首失败`);
  11209. });
  11210. break;
  11211. case 'previousVideo':
  11212. // 切换到上一个视频
  11213. this.playPrevious().catch(() => {
  11214. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败`);
  11215. });
  11216. break;
  11217. case 'previousVideo':
  11218. // 切换到上一个视频
  11219. this.playPrevious().catch(() => {
  11220. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败:`);
  11221. });
  11222. break;
  11223. default:
  11224. }
  11225. this.buttonAction = event + `-status:${status}`;
  11226. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  11227. }
  11228. /**
  11229. * 画中画功能(悬浮歌词功能)结束
  11230. *
  11231. */
  11232. async doSearchCover(item: VideoItem): Promise<string> {
  11233. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  11234. this.isShowMoreView = false;
  11235. this.showTipsDialog();
  11236. return ''; // Return empty string when no API is configured
  11237. }
  11238. if (!item) {
  11239. return ''; // Return empty string if item is undefined
  11240. }
  11241. const artist = item?.artist || ''; // Use empty string if artist is missing
  11242. return this.searchCover(item, item.name, artist); // Await is not needed here as we return the promise directly
  11243. }
  11244. /**
  11245. *api搜索封面
  11246. *item,根据title和artist
  11247. */
  11248. searchCover(item: VideoItem, title: string, artist: string): Promise<string> {
  11249. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  11250. LogUtil.debug("onecold res =" + res);
  11251. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  11252. if (item.filePath == this.currentSong?.filePath) {
  11253. this.cover = res;
  11254. if (this.currentSong) {
  11255. this.currentSong.pixelMapPath = res;
  11256. }
  11257. }
  11258. // Update pixel map path but always return res regardless of success
  11259. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  11260. if (success) {
  11261. this.doUpdateData();
  11262. console.log("onecold 更新音乐封面成功,数据库已同步");
  11263. } else {
  11264. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  11265. }
  11266. // Note: We don't resolve/reject here because we already returned res
  11267. });
  11268. LogUtil.debug("onecold this.cover =" + this.cover);
  11269. }
  11270. return res; // Always return res regardless of updatePixelMapPath result
  11271. });
  11272. }
  11273. @State jumpTopTime: number = 0
  11274. @State jumpEndTime: number = 0
  11275. @State isOpenJump: boolean = false
  11276. @Builder
  11277. JumpTopEndSheet() {
  11278. Scroll() {
  11279. Column() {
  11280. Column() {
  11281. Text('仅对本播放列表有效')
  11282. .fontSize(16)
  11283. .fontColor($r('app.color.text_color'))
  11284. // 跳过头尾
  11285. Column() {
  11286. Row() {
  11287. Text('跳过片头:')
  11288. .fontSize(16)
  11289. .fontColor($r('app.color.text_color'))
  11290. Text(this.jumpTopTime + 's')
  11291. .fontSize(16)
  11292. .fontColor($r('app.color.text_color'))
  11293. }
  11294. .margin({ bottom: 5 })
  11295. Row() {
  11296. Slider({
  11297. value: this.jumpTopTime,
  11298. min: 0,
  11299. max: 120,
  11300. step: 1,
  11301. style: SliderStyle.OutSet
  11302. })
  11303. .blockColor(this.themeColor)
  11304. .trackColor($r('app.color.speed_text_color'))
  11305. .selectedColor(Color.White)
  11306. .trackThickness(8)
  11307. .onChange((value: number) => {
  11308. this.jumpTopTime = value;
  11309. })
  11310. .width('85%')
  11311. }
  11312. .alignItems(VerticalAlign.Top)
  11313. }
  11314. .margin({ top: 10, bottom: 10 })
  11315. // 跳过头尾
  11316. Column() {
  11317. Row() {
  11318. Text('跳过片尾:')
  11319. .fontSize(16)
  11320. .fontColor($r('app.color.text_color'))
  11321. Text(this.jumpEndTime + 's')
  11322. .fontSize(16)
  11323. .fontColor($r('app.color.text_color'))
  11324. }
  11325. .margin({ bottom: 5 })
  11326. Row() {
  11327. Slider({
  11328. value: this.jumpEndTime,
  11329. min: 0,
  11330. max: 120,
  11331. step: 1,
  11332. style: SliderStyle.OutSet
  11333. })
  11334. .blockColor(this.themeColor)
  11335. .trackColor($r('app.color.speed_text_color'))
  11336. .selectedColor(Color.White)
  11337. .trackThickness(8)
  11338. .onChange((value: number) => {
  11339. this.jumpEndTime = value;
  11340. })
  11341. .width('85%')
  11342. }
  11343. .alignItems(VerticalAlign.Top)
  11344. }
  11345. .margin({ top: 10, bottom: 10 })
  11346. Row() {
  11347. Button('保存设置')
  11348. .fontColor(Color.White)
  11349. .layoutWeight(1)
  11350. .height(40)
  11351. .width(80)
  11352. .backgroundColor(this.themeColor)
  11353. .stateEffect(true)
  11354. .margin({ left: 0, bottom: 20 })
  11355. .onClick(async () => {
  11356. if (!Utility.isNoble()) {
  11357. this.isJumpSetting = false
  11358. this.isShowMoreView = false
  11359. this.showVipDialog()
  11360. return
  11361. }
  11362. if (this.currentSong === undefined) {
  11363. return
  11364. }
  11365. if (this.modeType === 0) {
  11366. let parentPath = FileUtil.getParentPath(this.videoUrl)
  11367. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  11368. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  11369. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  11370. } else if (this.modeType === 1) { //媒体库
  11371. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  11372. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  11373. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  11374. } else if (this.modeType === 2) { //艺术家
  11375. if (this.currentSong?.artist) {
  11376. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  11377. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  11378. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  11379. }
  11380. } else if (this.modeType === 3) { //专辑
  11381. if (this.currentSong?.album) {
  11382. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  11383. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  11384. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  11385. }
  11386. }
  11387. ToastUtil.showShort("保存成功")
  11388. this.isJumpSetting = false
  11389. })
  11390. }
  11391. .margin({
  11392. left: 38,
  11393. right: 38,
  11394. top: 10,
  11395. bottom: 10
  11396. })
  11397. .width(120)
  11398. .height(50)
  11399. }
  11400. }
  11401. }
  11402. .width('100%')
  11403. .height('100%')
  11404. }
  11405. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  11406. private onStateVastChange(state: AVCastPickerState) {
  11407. if (state == AVCastPickerState.STATE_APPEARING) {
  11408. console.log('The picker starts showing.');
  11409. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  11410. console.log('The picker finishes presenting.');
  11411. }
  11412. }
  11413. private showSelectLyric() {
  11414. DialogHelper.showActionSheetDialog({
  11415. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  11416. // sheets: ["本地歌词", "搜索歌词"],
  11417. sheets: [
  11418. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  11419. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  11420. ],
  11421. maskColor: Color.Transparent,
  11422. backgroundColor: $r('app.color.bg_card'),
  11423. transition: AnimationHelper.transitionInDown(666),
  11424. onAction: (index) => {
  11425. switch (index) {
  11426. case 0:
  11427. this.callFilePickerSelectFileForLyric()
  11428. break;
  11429. case 1:
  11430. if (StrUtil.isNotEmpty(this.videoUrl)) {
  11431. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  11432. this.initLyric(lyricPath);
  11433. }
  11434. break;
  11435. }
  11436. }
  11437. })
  11438. }
  11439. // 拉起picker选择文件管理器
  11440. async callFilePickerSelectFileForLyric(): Promise<void> {
  11441. try {
  11442. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  11443. DocumentSelectOptions.maxSelectNumber = 1
  11444. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  11445. let documentPicker = new picker.DocumentViewPicker();
  11446. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  11447. Logger.info(TAG,
  11448. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  11449. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  11450. this.saveVideoDatasLyric(DocumentSelectResult)
  11451. }
  11452. }).catch((err: BusinessError) => {
  11453. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  11454. });
  11455. } catch (err) {
  11456. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  11457. }
  11458. }
  11459. async saveVideoDatasLyric(uris: string[]) {
  11460. if (ArrayUtil.isEmpty(uris)) {
  11461. return
  11462. }
  11463. let newUris: string[] = [];
  11464. for (let i = 0; i < uris.length; i++) {
  11465. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  11466. Logger.info(TAG, 'filePath uri: ' + filePath);
  11467. newUris.push(filePath)
  11468. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  11469. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  11470. fileIo.copyFileSync(file.fd, file2.fd)
  11471. fileIo.closeSync(file);
  11472. fileIo.closeSync(file2);
  11473. this.initLyric(filePath,false,false,true)
  11474. }
  11475. }
  11476. private initDelayPlay(context: object) {
  11477. this.mContext = context;
  11478. }
  11479. startPipLyric() {
  11480. if (this.pipController) {
  11481. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  11482. PiPWindow.PiPControlStatus.PLAY);
  11483. }
  11484. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  11485. if (this.isOpenPip) {
  11486. this.startPip()
  11487. } else {
  11488. this.stopPip()
  11489. }
  11490. }
  11491. //startOffset 从cue分轨时间开始播
  11492. private startPlayOrResumePlay(startOffset?:number) {
  11493. //针对dsf文件高采样率,统一转wav播放
  11494. const sampleRate = this.currentSong?.sampleRate||0
  11495. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  11496. console.info('onecold 采样率 ='+sampleRate)
  11497. let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  11498. console.info('onecold newDsfPath ='+newDsfPath)
  11499. if(!FileUtil.accessSync(newDsfPath)){
  11500. const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  11501. taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  11502. this.videoUrl = newDsfPath
  11503. this.startPlay(startOffset)
  11504. }).catch((e:object)=>{
  11505. console.info("task1 catch e: " + e);
  11506. })
  11507. }else{
  11508. this.videoUrl = newDsfPath
  11509. this.startPlay(startOffset)
  11510. }
  11511. }else{
  11512. this.startPlay(startOffset)
  11513. }
  11514. }
  11515. startPlay(startOffset?:number) {
  11516. this.startPipLyric()
  11517. this.mDestroyPage = false;
  11518. this.animationState = AnimationStatus.Running
  11519. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  11520. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  11521. this.stopProgressTask();
  11522. this.startProgressTask();
  11523. this.play(this.videoUrl.toString(),startOffset);
  11524. }
  11525. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  11526. this.mIjkMediaPlayer.start();
  11527. this.setProgress()
  11528. this.CONTROL_PlayStatus = PlayStatus.PLAY
  11529. }
  11530. this.setIsPlaying(true)
  11531. this.updateSessionPlayState(true)
  11532. this.watchStatus();
  11533. this.updateLastPlayTimeStr(this.videoUrl)
  11534. }
  11535. updateLastPlayTimeStr(filePath: string) {
  11536. // 检查是否为网络音频(WebDAV),如果是则不更新本地数据库
  11537. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  11538. Logger.info(`heanup 检测到网络音频播放,跳过数据库更新: ${filePath}`)
  11539. return;
  11540. }
  11541. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  11542. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  11543. if (success) {
  11544. this.getHistoryList(false)
  11545. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  11546. } else {
  11547. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  11548. }
  11549. });
  11550. }
  11551. private completionNum(num: number): string | number {
  11552. if (num < 10) {
  11553. return '0' + num;
  11554. } else {
  11555. return num;
  11556. }
  11557. }
  11558. private stringForTime(timeMs: number): string {
  11559. let totalSeconds: number | string = (timeMs / 1000);
  11560. let newSeconds: number | string = totalSeconds % 60;
  11561. let minutes: number | string = (totalSeconds / 60) % 60;
  11562. let hours: number | string = totalSeconds / 3600;
  11563. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  11564. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  11565. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  11566. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  11567. if (this.isCurrentTime) {
  11568. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  11569. this.oldSeconds = newSeconds
  11570. } else {
  11571. newSeconds = this.oldSeconds
  11572. }
  11573. }
  11574. newSeconds = this.completionNum(newSeconds);
  11575. if (hours > 0) {
  11576. return hours + ":" + minutes + ":" + newSeconds;
  11577. } else {
  11578. return minutes + ":" + newSeconds;
  11579. }
  11580. }
  11581. private setProgress() {
  11582. let position = this.mIjkMediaPlayer.getCurrentPosition();
  11583. let duration = this.mIjkMediaPlayer.getDuration();
  11584. let pos = 0;
  11585. if (duration > 0) {
  11586. this.slideEnable = true;
  11587. let curPercent = position / duration;
  11588. pos = curPercent * 100;
  11589. if (pos > this.PROGRESS_MAX_VALUE) {
  11590. this.progressValue = this.PROGRESS_MAX_VALUE
  11591. } else {
  11592. this.progressValue = pos;
  11593. }
  11594. }
  11595. // LogUtils.getInstance()
  11596. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  11597. this.totalTime = this.stringForTime(duration);
  11598. if (position > duration) {
  11599. position = duration;
  11600. }
  11601. this.isCurrentTime = true;
  11602. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  11603. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  11604. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  11605. this.currentTime = this.stringForTime(position);
  11606. this.isCurrentTime = false
  11607. if (this.mIjkMediaPlayer.isPlaying()) {
  11608. this.randomColor =
  11609. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  11610. //如果是开启AB循环
  11611. if(this.isOpenAB){
  11612. if(position >=this.jumpBTime){
  11613. this.seekTo(this.jumpATime+'')
  11614. return
  11615. }
  11616. }
  11617. // 判断是否播放到结束时间
  11618. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  11619. if (position >= duration - this.jumpEndTime * 1000) {
  11620. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  11621. this.CONTROL_PlayStatus = PlayStatus.INIT
  11622. this.startPlayOrResumePlay();
  11623. }else if (this.playType == 2) { //2:正常播放,单曲播完
  11624. this.showRePlay();
  11625. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  11626. this.progressValue = this.PROGRESS_MAX_VALUE;
  11627. this.slideEnable = false;
  11628. this.stop();
  11629. // ToastUtil.showToast('开始重新播放')
  11630. }else{
  11631. this.playNext().catch(() => {
  11632. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  11633. });
  11634. }
  11635. }
  11636. }
  11637. } else {
  11638. this.randomColor = 'rbg(0,0,0)'
  11639. }
  11640. }
  11641. private startProgressTask() {
  11642. let that = this;
  11643. this.updateProgressTimer = setInterval(() => {
  11644. //LogUtils.getInstance().LOGI("startProgressTask");
  11645. if (!that.mDestroyPage) {
  11646. that.setProgress();
  11647. }
  11648. }, 300);
  11649. }
  11650. private stopProgressTask() {
  11651. LogUtils.getInstance().LOGI("stopProgressTask");
  11652. clearInterval(this.updateProgressTimer);
  11653. }
  11654. private showLoadIng() {
  11655. this.loadingVisible = Visibility.Visible;
  11656. this.replayVisible = Visibility.None;
  11657. }
  11658. private hideLoadIng() {
  11659. this.loadingVisible = Visibility.None;
  11660. this.replayVisible = Visibility.None;
  11661. }
  11662. private showRePlay() {
  11663. this.loadingVisible = Visibility.None;
  11664. this.replayVisible = Visibility.Visible;
  11665. }
  11666. private async play(url: string,startOffset?:number) {
  11667. this.isShowBgLiuGUANG = PreferencesUtil.getBooleanSync('isShowBgLiuGUANG', true)
  11668. console.info('onecold this.url 1= '+url)
  11669. if(!url.toLowerCase().startsWith('http')){
  11670. let hasPermission = await PermissionUtil.activatePermission(url)
  11671. console.info('onecold this.hasPermission 1= '+hasPermission)
  11672. if(!url.includes(this.packName)){
  11673. const file = fs.openSync(url)
  11674. this.videoUrl = file.path
  11675. url= this.videoUrl
  11676. }
  11677. console.info('onecold this.hasPermission 1= '+hasPermission)
  11678. console.info('onecold this.videoUrl 1= '+this.videoUrl)
  11679. }
  11680. let that = this;
  11681. that.showLoadIng();
  11682. this.isOpenAB = false
  11683. //设置XComponent回调的context
  11684. if (!!this.mContext) {
  11685. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  11686. }
  11687. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  11688. this.mIjkMediaPlayer.reset();
  11689. }
  11690. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  11691. //设置debug模式
  11692. this.mIjkMediaPlayer.setDebug(false);
  11693. //初始化配置
  11694. this.mIjkMediaPlayer.native_setup();
  11695. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  11696. if(this.volumeSmall){
  11697. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  11698. this.mIjkMediaPlayer.setVolume('1', '1');
  11699. }else{
  11700. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  11701. }
  11702. }else{
  11703. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  11704. }
  11705. //设置视频源
  11706. this.mIjkMediaPlayer.setDataSource(url);
  11707. // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
  11708. const headers = new Map<string, string>();
  11709. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  11710. headers.set("Accept", "*/*");
  11711. if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
  11712. &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
  11713. //如果封面为空,则搜索封面
  11714. this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
  11715. }
  11716. // 如果是WebDAV网络音频,使用webdav_account_id获取认证信息(等待完成后再设置一次性头部)
  11717. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  11718. Logger.info(`heanup WebDAV歌曲认证 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
  11719. if (this.currentSong.webdav_account_id) {
  11720. try {
  11721. const webdavManager = RemoteDriveManager.getInstance();
  11722. const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  11723. if (webDavHeaders && webDavHeaders.size > 0) {
  11724. webDavHeaders.forEach((value, key) => headers.set(key, value));
  11725. Logger.info(`heanup 成功通过webdav_account_id获取并合并WebDAV认证头`);
  11726. } else {
  11727. Logger.warn(`heanup 通过webdav_account_id获取认证头失败,播放可能无法继续`);
  11728. }
  11729. } catch (error) {
  11730. const err = error as Error;
  11731. Logger.error(`heanup 获取WebDAV认证头时出错: ${err.message}`);
  11732. }
  11733. } else {
  11734. Logger.error(`heanup WebDAV歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法进行认证`);
  11735. }
  11736. }
  11737. // 统一设置带认证的请求头
  11738. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  11739. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  11740. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  11741. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  11742. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  11743. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  11744. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  11745. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  11746. // 缓冲和播放优化设置
  11747. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  11748. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  11749. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1"); // 预加载启动
  11750. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  11751. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  11752. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  11753. // 网络相关设置
  11754. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  11755. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  11756. // 重连设置
  11757. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  11758. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  11759. }
  11760. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  11761. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  11762. // }
  11763. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  11764. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  11765. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  11766. const fileSize = await this.getFileSize(this.videoUrl);
  11767. let bufferSize = 1 * 1024 ; // 默认缓冲区大小为1MB
  11768. if (fileSize > 3 * 1024 * 1024 * 1024) { // 文件大于3GB
  11769. bufferSize = 25 * 1024 * 1024; // 设置缓冲区大小为25MB
  11770. }
  11771. // 使用软件解码(通常比硬件解码更节省内存)
  11772. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", '0');
  11773. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", '0');
  11774. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", '1024');
  11775. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzeduration", '500000');
  11776. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  11777. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  11778. //停止预读的最小帧数
  11779. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  11780. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  11781. // 设置其他缓冲相关选项
  11782. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  11783. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  11784. //启动预加载
  11785. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  11786. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  11787. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  11788. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  11789. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  11790. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  11791. // 因此需要播放器丢包,才不会累积延时
  11792. // 这个和第三个参数packet-buffering无关。
  11793. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  11794. // 无限制收流
  11795. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  11796. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  11797. // 屏幕常亮
  11798. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  11799. // 设置超时
  11800. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  11801. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  11802. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  11803. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  11804. // 变速播放
  11805. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  11806. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  11807. let Speed = this.mIjkMediaPlayer.getSpeed()
  11808. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  11809. //是否开启循环播放
  11810. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  11811. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  11812. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  11813. if (height === 0) {
  11814. return;
  11815. }
  11816. const va = width / height;
  11817. const vpa = that.videoParentAspectRatio;
  11818. if (vpa > va) {
  11819. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  11820. } else {
  11821. that.videoWidth = '100%';
  11822. }
  11823. if (width && height) {
  11824. that.videoAspectRatio = width / height;
  11825. }
  11826. LogUtils.getInstance()
  11827. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  11828. that.hideLoadIng();
  11829. }
  11830. }
  11831. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  11832. let mOnPreparedListener: OnPreparedListener = {
  11833. onPrepared: async () => {
  11834. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  11835. try {
  11836. //保存碰一碰分享的当前的歌曲
  11837. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  11838. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  11839. await this.initLyric(lyricPath);
  11840. setTimeout(() => {
  11841. this.avSessionController.initAvSession(false);
  11842. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  11843. this.setAvSessionListener();
  11844. this.updateSessionPlayState(true)
  11845. this.setCurrentPlayMode()
  11846. }, 500)
  11847. if(startOffset&&startOffset>0){//cue分轨播放
  11848. this.seekTo(startOffset + "");
  11849. this.saveLastPlayList()
  11850. return
  11851. }
  11852. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  11853. let timeoutPlay = 0
  11854. if (StrUtil.isNotEmpty(this.videoUrl) &&
  11855. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  11856. timeoutPlay = 1000
  11857. }
  11858. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  11859. if (this.modeType === 0) { //文件夹
  11860. let parentPath = FileUtil.getParentPath(this.videoUrl)
  11861. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  11862. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  11863. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  11864. } else if (this.modeType === 1) { //媒体库
  11865. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  11866. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  11867. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  11868. } else if (this.modeType === 2) { //艺术家
  11869. if (this.currentSong?.artist) {
  11870. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  11871. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  11872. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  11873. }
  11874. } else if (this.modeType === 3) { //专辑
  11875. if (this.currentSong?.album) {
  11876. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  11877. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  11878. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  11879. }
  11880. }
  11881. this.duration = this.mIjkMediaPlayer.getDuration()
  11882. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  11883. if (this.mIjkMediaPlayer != null) {
  11884. let jumpTopTimeMs = this.jumpTopTime*1000;
  11885. if (jumpTopTimeMs <= this.duration) {
  11886. // 调用 seekTo 方法,跳到指定时间
  11887. if(PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY,true)){
  11888. console.log('onecold jumpTopTime = '+jumpTopTimeMs);
  11889. const position:number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  11890. console.log('onecold position = '+position);
  11891. if (position > jumpTopTimeMs) {
  11892. jumpTopTimeMs = position
  11893. }
  11894. }
  11895. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  11896. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  11897. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  11898. }
  11899. }, timeoutPlay)
  11900. } else {
  11901. // 提示用户无法跳过
  11902. ToastUtil.showToast('跳过时间超过视频时长');
  11903. }
  11904. }
  11905. } else {
  11906. this.jumpTopTime = 0
  11907. this.jumpEndTime = 0
  11908. console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  11909. console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  11910. console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  11911. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  11912. //记忆播放(每一首都会记忆播放)
  11913. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  11914. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  11915. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  11916. this.restorePlaybackPosition() //读取播放记忆功能
  11917. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  11918. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  11919. this.restorePlaybackPosition() //读取播放记忆功能
  11920. }
  11921. this.isFirstStartPlay = false
  11922. }, timeoutPlay)
  11923. } else {
  11924. this.isFirstStartPlay = false
  11925. }
  11926. }
  11927. this.saveLastPlayList()
  11928. } catch (error) {
  11929. let err: BusinessError = error as BusinessError;
  11930. console.error('onecold failed with err: ' + JSON.stringify(err));
  11931. }
  11932. }
  11933. }
  11934. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  11935. let mOnTimedTextListener: OnTimedTextListener = {
  11936. onTimedText: () => {
  11937. }
  11938. }
  11939. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  11940. let mOnCompletionListener: OnCompletionListener = {
  11941. onCompletion: () => {
  11942. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  11943. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  11944. // 异步调用playNext
  11945. this.playNext().catch(() => {
  11946. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  11947. });
  11948. } else if (this.playType == 1) { //1:单片重复播放
  11949. this.CONTROL_PlayStatus = PlayStatus.INIT
  11950. that.startPlayOrResumePlay();
  11951. } else if (this.playType == 2) { //2:正常播放,单曲播完
  11952. that.showRePlay();
  11953. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  11954. that.progressValue = this.PROGRESS_MAX_VALUE;
  11955. that.slideEnable = false;
  11956. that.stop();
  11957. // ToastUtil.showToast('开始重新播放')
  11958. } else if (this.playType == 3) { //3:随机播放
  11959. // 异步调用randomPlay
  11960. this.randomPlay().catch(() => {
  11961. Logger.error('heanup OnCompletionListener randomPlay', `随机播放失败`);
  11962. });
  11963. }
  11964. }
  11965. }
  11966. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  11967. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  11968. onBufferingUpdate: (percent: number) => {
  11969. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  11970. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  11971. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  11972. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  11973. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  11974. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  11975. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  11976. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  11977. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  11978. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  11979. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  11980. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  11981. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  11982. let Looping = this.mIjkMediaPlayer.isLooping()
  11983. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  11984. }
  11985. }
  11986. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  11987. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  11988. onSeekComplete: () => {
  11989. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  11990. console.info('onecold startPlayOrResumePlay 10643')
  11991. that.startPlayOrResumePlay();
  11992. }
  11993. }
  11994. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  11995. let mOnInfoListener: OnInfoListener = {
  11996. onInfo: (what: number, extra: number) => {
  11997. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  11998. that.hideLoadIng();
  11999. }
  12000. }
  12001. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  12002. let mOnErrorListener: OnErrorListener = {
  12003. onError: (what: number, extra: number) => {
  12004. this.stopProgressTask();
  12005. LogUtils.getInstance().LOGI("heanup OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  12006. LogUtils.getInstance().LOGI('heanup 播放错误,歌曲详情:' + JSON.stringify(this.currentSong))
  12007. // 检查是否为WebDAV播放错误
  12008. let isWebDavError = false;
  12009. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.currentSong.filePath) {
  12010. try {
  12011. const globalContext = GlobalContext.getContext();
  12012. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  12013. if (webDavAuthInfo) {
  12014. isWebDavError = true;
  12015. }
  12016. } catch (error) {
  12017. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  12018. }
  12019. }
  12020. if (isWebDavError) {
  12021. Logger.error(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  12022. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  12023. // this.currentWebDavAuthInfo = null;
  12024. Logger.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  12025. // 根据错误代码提供更具体的错误信息
  12026. let errorMessage = "WebDAV播放失败";
  12027. if (what === -1) { // 网络错误
  12028. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  12029. } else if (what === -1004) { // HTTP 404
  12030. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  12031. } else if (what === -1001) { // 超时
  12032. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  12033. } else if (what === -1003) { // 无法解析主机
  12034. errorMessage = "无法连接到WebDAV服务器";
  12035. }
  12036. ToastUtil.showToast(errorMessage);
  12037. } else {
  12038. if (StrUtil.isNotEmpty(this.videoUrl) &&
  12039. !this.videoUrl.startsWith('http://') &&
  12040. !this.videoUrl.startsWith('https://') &&
  12041. !FileUtil.accessSync(this.videoUrl)) {
  12042. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  12043. } else {
  12044. ToastUtil.showToast(getContext()
  12045. .resourceManager
  12046. .getStringByNameSync("Honey_the_video_is_playing_errant_The_system_is_wandering"))
  12047. }
  12048. }
  12049. that.hideLoadIng();
  12050. }
  12051. }
  12052. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  12053. this.mIjkMediaPlayer.setMessageListener();
  12054. this.mIjkMediaPlayer.prepareAsync();
  12055. this.mIjkMediaPlayer.start();
  12056. }
  12057. //保存最后播放的那首歌和已经对应的播放列表
  12058. saveLastPlayList() {
  12059. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  12060. PreferencesUtil.putSync('LastMusicList', this.songList)
  12061. }
  12062. // 清空播放记录
  12063. clearVideoHistory() {
  12064. this.table.clearPlayHistory((success: boolean, error?: string) => {
  12065. if (success) {
  12066. this.historyList = [];
  12067. this.updateListData(this.historyList)
  12068. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  12069. ToastUtil.showToast('清空播放记录成功')
  12070. } else {
  12071. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  12072. }
  12073. });
  12074. }
  12075. public async setAvSessionListener() {
  12076. if (!this.avSessionController) {
  12077. return;
  12078. }
  12079. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  12080. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  12081. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  12082. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  12083. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  12084. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  12085. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  12086. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  12087. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  12088. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  12089. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  12090. }
  12091. setLoopMode() {
  12092. let itype = this.playType + 1
  12093. if (itype >= 4) {
  12094. this.playType = 0
  12095. ToastUtil.showToast('连续播放')
  12096. } else if (itype === 1) {
  12097. this.playType = 1
  12098. ToastUtil.showToast('单曲循环')
  12099. } else if (itype === 2) {
  12100. this.playType = 2
  12101. ToastUtil.showToast('单曲播完')
  12102. } else if (itype === 3) {
  12103. this.playType = 3
  12104. ToastUtil.showToast('随机播放')
  12105. } else if (itype === 0) {
  12106. this.playType = 0
  12107. ToastUtil.showToast('连续播放')
  12108. }
  12109. PreferencesUtil.putSync('musicPlayType', this.playType)
  12110. this.setCurrentPlayMode()
  12111. }
  12112. private sessionSetLoopModeCallback = (mode: number) => {
  12113. if (this.mIjkMediaPlayer != null) {
  12114. ToastUtil.showToast('当前播放模式:' + mode)
  12115. Logger.info('onecold 当前播放模式= ' + mode)
  12116. let hmPlayMode = mode + 1
  12117. if (hmPlayMode >= 4) {
  12118. hmPlayMode = 0
  12119. }
  12120. if (hmPlayMode === 1) {
  12121. this.playType = 1
  12122. ToastUtil.showToast('单曲循环')
  12123. } else if (hmPlayMode === 0) {
  12124. this.playType = 2
  12125. ToastUtil.showToast('单曲播完')
  12126. } else if (hmPlayMode === 3) {
  12127. this.playType = 3
  12128. ToastUtil.showToast('随机播放')
  12129. } else if (hmPlayMode === 2) {
  12130. this.playType = 0
  12131. ToastUtil.showToast('连续播放')
  12132. }
  12133. PreferencesUtil.putSync('musicPlayType', this.playType)
  12134. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  12135. let playBackState: avSession.AVPlaybackState = {
  12136. loopMode: hmPlayMode,
  12137. };
  12138. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  12139. console.info(`set setLoopMode AVPlaybackState successfully`);
  12140. }).catch((err: BusinessError) => {
  12141. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  12142. });
  12143. }
  12144. }
  12145. setCurrentPlayMode() {
  12146. if (!this.avSessionController) {
  12147. return;
  12148. }
  12149. let mLoopMode = 0
  12150. switch (this.playType) {
  12151. case 0:
  12152. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  12153. break;
  12154. case 1:
  12155. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  12156. break;
  12157. case 2:
  12158. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  12159. break;
  12160. case 3:
  12161. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  12162. break;
  12163. }
  12164. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  12165. let playBState: avSession.AVPlaybackState = {
  12166. loopMode: mLoopMode,
  12167. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  12168. };
  12169. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  12170. console.info(`set setLoopMode AVPlaybackState successfully`);
  12171. }).catch((err: BusinessError) => {
  12172. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  12173. });
  12174. }
  12175. private sessionToggleFavoriteCallback = (assetId: string) => {
  12176. if (this.mIjkMediaPlayer != null && this.currentSong) {
  12177. console.info(`on toggleFavorite `);
  12178. // 应用收到收藏命令,进行收藏处理。
  12179. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  12180. this.doFav(this.currentSong)
  12181. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  12182. let playbackState: avSession.AVPlaybackState = {
  12183. isFavorite: !this.isFac,
  12184. };
  12185. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  12186. console.info(`SetAVPlaybackState successfully`);
  12187. }).catch((err: BusinessError) => {
  12188. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  12189. });
  12190. }
  12191. }
  12192. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  12193. device: avSession.OutputDeviceInfo) => {
  12194. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  12195. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  12196. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  12197. await this.startCasting();
  12198. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  12199. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  12200. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  12201. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  12202. if (device) {
  12203. this.endCasting();
  12204. }
  12205. }
  12206. };
  12207. private async startCasting() {
  12208. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  12209. this.setPlaybackStateChangeListener();
  12210. this.pause();
  12211. this.initQueueItem();
  12212. this.prepare();
  12213. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  12214. refToIsCasting?.set(true);
  12215. this.castSeek = true;
  12216. this.isCastPlaying = true;
  12217. }
  12218. async changeCasting() {
  12219. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  12220. this.initQueueItem();
  12221. this.prepare();
  12222. this.setPlaybackStateChangeListener();
  12223. this.isCastPlaying = true;
  12224. this.castSeek = true;
  12225. }
  12226. public endCasting() {
  12227. this.avSessionController.getAvSession()?.stopCasting();
  12228. this.stopCast();
  12229. this.isCastPlaying = false;
  12230. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  12231. refToIsCasting?.set(false);
  12232. this.pause();
  12233. this.setIsPlaying(false);
  12234. // if (this.curIndex === this.curSource.index) {
  12235. // this.play
  12236. // this.seek(this.currentTime * 1000);
  12237. // this.setIsPlaying(true);
  12238. // } else {
  12239. // this.pauseVideo();
  12240. // this.setIsPlaying(false);
  12241. // }
  12242. }
  12243. public setIsPlaying(isPlayer: boolean) {
  12244. this.isPlaying = isPlayer;
  12245. // 发送播放状态变化事件给歌单详情页面
  12246. try {
  12247. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  12248. const currentFilePath = this.currentSong?.filePath || ''
  12249. const eventData: emitter.EventData = {
  12250. data: {
  12251. isPlaying: this.isPlaying,
  12252. curIndex: this.curIndex,
  12253. currentFilePath: currentFilePath
  12254. }
  12255. };
  12256. emitter.emit(eventPlaybackStatus, eventData)
  12257. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  12258. } catch (error) {
  12259. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  12260. }
  12261. }
  12262. private setPlaybackStateChangeListener(): void {
  12263. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  12264. this.castController?.on('endOfStream', this.reloadCasting);
  12265. this.castController?.on('playNext', this.playNextCallback);
  12266. this.castController?.on('playPrevious', this.playPreviousCallback);
  12267. }
  12268. private updateSessionPlayState(isPlay: boolean): void {
  12269. // if(!this.isBgPlayOpen)
  12270. // return
  12271. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  12272. this.setAVSessionPlayState({
  12273. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  12274. position: {
  12275. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  12276. updateTime: new Date().getTime()
  12277. }
  12278. });
  12279. }
  12280. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  12281. this.avSessionController.setAvSessionPlayState(playbackState)
  12282. }
  12283. private positionChange(position: number) {
  12284. this.currentTime2 = position / 1000;
  12285. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  12286. }
  12287. private playDurationChange(duration: number) {
  12288. this.duration = duration;
  12289. this.durationTime = Math.floor(this.duration / 1000);
  12290. this.durationStringTime = secondToTime((this.durationTime));
  12291. }
  12292. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  12293. const duration = playbackState?.extras?.duration;
  12294. if (typeof duration === 'number') {
  12295. this.playDurationChange(duration as number);
  12296. }
  12297. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  12298. this.positionChange(playbackState?.position?.elapsedTime);
  12299. }
  12300. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  12301. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  12302. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  12303. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  12304. this.isCastPlaying = false;
  12305. }
  12306. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  12307. this.isCastPlaying = true;
  12308. }
  12309. };
  12310. private reloadCasting = async () => {
  12311. let item = this.songList[this.curIndex];
  12312. let uri = fileUri.getUriFromPath(item.filePath);
  12313. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  12314. // description.startPosition = 0;
  12315. this.castItem = {
  12316. itemId: this.curIndex,
  12317. description: {
  12318. assetId: item.filePath,
  12319. title: item.name,
  12320. artist: '',
  12321. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  12322. // mediaUri: item.filePath,
  12323. fdSrc: {
  12324. fd: file.fd
  12325. },
  12326. // 该字段大写,音频'AUDIO',视频'VIDEO'
  12327. mediaType: 'VIDEO',
  12328. mediaSize: item.videoSize,
  12329. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  12330. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  12331. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  12332. duration: this.duration,
  12333. // albumCoverUri: 'https://www.example.jpeg',
  12334. // albumTitle: '《ExampleAlbum》',
  12335. appName: this.appName,
  12336. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  12337. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  12338. }
  12339. };
  12340. this.prepare();
  12341. this.isCastPlaying = true;
  12342. };
  12343. public playNextCallback = (): void => {
  12344. this.playNext().catch(() => {
  12345. Logger.error('heanup playNextCallback', `播放下一首失败`);
  12346. });
  12347. };
  12348. public playPreviousCallback = (): void => {
  12349. this.playPrevious().catch(() => {
  12350. Logger.error('heanup playNextCallback', `播放上一首失败`);
  12351. });
  12352. };
  12353. async prepare() {
  12354. await this.castController?.prepare(this.castItem);
  12355. await this.castController?.start(this.castItem);
  12356. }
  12357. public initQueueItem() {
  12358. let item = this.songList[this.curIndex];
  12359. let time = this.currentTime;
  12360. let uri = fileUri.getUriFromPath(item.filePath);
  12361. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  12362. this.castItem = {
  12363. itemId: this.curIndex,
  12364. description: {
  12365. assetId: item.filePath,
  12366. title: item.name,
  12367. artist: '',
  12368. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  12369. fdSrc: {
  12370. fd: file.fd
  12371. },
  12372. // 该字段大写,音频'AUDIO',视频'VIDEO'
  12373. mediaType: 'AUDIO',
  12374. mediaSize: item.videoSize,
  12375. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  12376. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  12377. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  12378. duration: this.duration,
  12379. // albumCoverUri: 'https://www.example.jpeg',
  12380. // albumTitle: '《ExampleAlbum》',
  12381. appName: this.appName,
  12382. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  12383. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  12384. }
  12385. };
  12386. }
  12387. async stopCast() {
  12388. try {
  12389. this.castController?.off('playbackStateChange');
  12390. this.castController?.off('endOfStream');
  12391. this.castController?.off('playNext');
  12392. this.castController?.off('playPrevious');
  12393. this.castController?.off('error');
  12394. } catch (error) {
  12395. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  12396. }
  12397. }
  12398. private sessionPlayCallback = (): void => {
  12399. this.playOrPause()
  12400. };
  12401. private sessionPauseCallback = (): void => {
  12402. this.pause()
  12403. };
  12404. private playOrPause() {
  12405. if (!this.debounce()) {
  12406. return;
  12407. }
  12408. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  12409. this.pause();
  12410. } else {
  12411. console.info('onecold startPlayOrResumePlay 11064')
  12412. this.startPlayOrResumePlay();
  12413. this.playChange()
  12414. }
  12415. }
  12416. private sessionPlayNextCallback = (): void => {
  12417. this.playNext().catch(() => {
  12418. Logger.error('heanup sessionPlayPreviousCallback', `播放下 一首失败`);
  12419. });
  12420. };
  12421. private sessionPlayPreviousCallback = (): void => {
  12422. this.playPrevious().catch(() => {
  12423. Logger.error('heanup sessionPlayPreviousCallback', `播放上一首失败`);
  12424. });
  12425. };
  12426. private sessionStopCallback = (): void => {
  12427. this.stop()
  12428. };
  12429. private sessionFastForwardCallback = (time?: number) => {
  12430. if (!time) {
  12431. return;
  12432. }
  12433. if (this.mIjkMediaPlayer != null) {
  12434. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12435. let seeTime = curPosition + time * 1000;
  12436. // 限制 seekValue 在合法范围内
  12437. if (seeTime < 0) {
  12438. seeTime = 0;
  12439. } else if (seeTime > this.duration) {
  12440. seeTime = this.duration;
  12441. }
  12442. Logger.info('onecold seeTime= ' + seeTime)
  12443. this.setSeekToActionProgress(seeTime)
  12444. this.seekTo(seeTime + "")
  12445. }
  12446. };
  12447. /**
  12448. * Gesture method onActionUpdate.
  12449. *
  12450. * @param event Gesture event.手势拖动设置快进和后退
  12451. */
  12452. private setSeekToActionProgress(position: number) {
  12453. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  12454. let duration = this.mIjkMediaPlayer.getDuration();
  12455. let pos = 0;
  12456. if (duration > 0) {
  12457. this.slideEnable = true;
  12458. let curPercent = position / duration;
  12459. pos = curPercent * 100;
  12460. if (pos > this.PROGRESS_MAX_VALUE) {
  12461. this.progressValue = this.PROGRESS_MAX_VALUE
  12462. } else {
  12463. this.progressValue = pos;
  12464. }
  12465. }
  12466. // LogUtils.getInstance()
  12467. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  12468. this.totalTime = this.stringForTime(duration);
  12469. if (position > duration) {
  12470. position = duration;
  12471. }
  12472. this.isCurrentTime = true;
  12473. this.currentTime = this.stringForTime(position);
  12474. this.isCurrentTime = false
  12475. }
  12476. private sessionRewindCallback = (time?: number) => {
  12477. if (!time) {
  12478. return;
  12479. }
  12480. if (this.mIjkMediaPlayer != null) {
  12481. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12482. let seeTime = curPosition - time * 1000;
  12483. // 限制 seekValue 在合法范围内
  12484. if (seeTime < 0) {
  12485. seeTime = 0;
  12486. } else if (seeTime > this.duration) {
  12487. seeTime = this.duration;
  12488. }
  12489. Logger.info('onecold seeTime= ' + seeTime)
  12490. this.setSeekToActionProgress(seeTime)
  12491. this.seekTo(seeTime + "")
  12492. }
  12493. };
  12494. private sessionSeekCallback = (seekTime: number) => {
  12495. if (this.mIjkMediaPlayer != null) {
  12496. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12497. this.seekTo(seekTime + "")
  12498. }
  12499. };
  12500. private async getFileSize(filePath: string): Promise<number> {
  12501. try {
  12502. const stat = await fs.stat(filePath);
  12503. return stat.size;
  12504. } catch (err) {
  12505. console.error('Failed to get file size: ' + err.message);
  12506. return 0;
  12507. }
  12508. }
  12509. private pause() {
  12510. if (this.mIjkMediaPlayer.isPlaying()) {
  12511. this.savePlaybackPosition();
  12512. this.mIjkMediaPlayer.pause();
  12513. this.setProgress();
  12514. this.mDestroyPage = true;
  12515. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  12516. this.updateSessionPlayState(false)
  12517. this.playChange()
  12518. if (this.pipController) {
  12519. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  12520. PiPWindow.PiPControlStatus.PAUSE);
  12521. }
  12522. }
  12523. }
  12524. private stop() {
  12525. this.savePlaybackPosition();
  12526. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12527. this.mIjkMediaPlayer.stop();
  12528. this.mIjkMediaPlayer.release();
  12529. this.stopProgressTask();
  12530. this.updateSessionPlayState(false)
  12531. this.playChange()
  12532. this.watchStatus();
  12533. }
  12534. //保持记忆播放功能
  12535. private savePlaybackPosition() {
  12536. if (this.mIjkMediaPlayer != null) {
  12537. const position = this.mIjkMediaPlayer.getCurrentPosition();
  12538. // ToastUtil.showToast('保存记忆播放 = ' + position)
  12539. const duration = this.mIjkMediaPlayer.getDuration();
  12540. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  12541. // 如果播放位置接近视频末尾,则保存 position 为 0
  12542. const playbackPosition = (duration - position < threshold) ? 0 : position;
  12543. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  12544. }
  12545. }
  12546. //获取记忆播放功能
  12547. private restorePlaybackPosition() {
  12548. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  12549. // ToastUtil.showToast('position = ' + position)
  12550. if (this.mIjkMediaPlayer != null && position > 0) {
  12551. // ToastUtil.showToast('seekTo = ' + position)
  12552. this.seekTo(position + "");
  12553. }
  12554. }
  12555. private seekTo(value: string) {
  12556. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  12557. ToastUtil.showToast('wma格式不支持拖动快进。')
  12558. return
  12559. }
  12560. this.isSeekTo = true
  12561. this.mIjkMediaPlayer.seekTo(value);
  12562. console.info('onecold startPlayOrResumePlay 11227')
  12563. // this.startPlayOrResumePlay()
  12564. // 在这里恢复计时器状态
  12565. this.setProgress()
  12566. this.isSeekTo = false
  12567. }
  12568. // 添加到下一首播放
  12569. private addToNextPlay(song: VideoItem) {
  12570. if (!this.debounce()) {
  12571. return;
  12572. }
  12573. if (this.currentSong) {
  12574. if (this.currentSong === song) {
  12575. ToastUtil.showToast('当前已经在播放这首歌了!')
  12576. return
  12577. }
  12578. }
  12579. // 如果未开始播放或队列为空
  12580. if (this.curIndex === -1 || this.songList.length === 0) {
  12581. this.songList = [song];
  12582. this.curIndex = 0;
  12583. this.doPlay(song)
  12584. return;
  12585. }
  12586. // 插入到当前索引+1的位置
  12587. const insertPos = this.curIndex + 1;
  12588. this.songList.splice(insertPos, 0, song);
  12589. this.songList = [...this.songList]; // 触发状态更新
  12590. this.sonDataSource.pushArrayData(this.songList)
  12591. ToastUtil.showToast('已添加至下一首播放')
  12592. }
  12593. //后退10s,可再设置设置默认几秒
  12594. backForward() {
  12595. if(this.mIjkMediaPlayer){
  12596. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  12597. let value = pos - Number(this.fastForwardSeconds) * 1000;
  12598. this.seekTo(value+"");
  12599. }
  12600. }
  12601. //快进10s,可再设置设置默认几秒
  12602. fastForward() {
  12603. if(this.mIjkMediaPlayer){
  12604. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  12605. let value = pos + Number(this.fastForwardSeconds) * 1000;
  12606. this.seekTo(value+"");
  12607. }
  12608. }
  12609. //下一个
  12610. private async playNext() {
  12611. if (!this.debounce()) {
  12612. return;
  12613. }
  12614. if (this.playType == 3) { //3:随机播放
  12615. await this.randomPlay()
  12616. return;
  12617. }
  12618. if (ArrayUtil.isNotEmpty(this.songList)) {
  12619. if (this.curIndex == this.songList.length - 1) {
  12620. this.curIndex = 0;
  12621. } else {
  12622. this.curIndex++;
  12623. }
  12624. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12625. this.stop();
  12626. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  12627. this.currentSong = this.songList[this.curIndex];
  12628. Logger.info('heanup playNext', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  12629. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12630. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  12631. context: this.context,
  12632. autoParseMusicName: this.autoParseMusicName
  12633. });
  12634. this.artist = this.songList[this.curIndex].artist
  12635. this.name = this.songList[this.curIndex].name
  12636. //this.cover = this.songList[this.curIndex].pixelMapPath
  12637. this.changeImageAnimation()
  12638. }
  12639. }
  12640. changeImageAnimation() {
  12641. if(this.openSkipSongAnimate){
  12642. // 第一步:淡出动画
  12643. this.getUIContext()?.animateTo({
  12644. duration: 500,
  12645. curve: Curve.EaseOut,
  12646. }, () => {
  12647. this.opacityValueImage = 0.1;
  12648. if(this.isCoverRectangle){
  12649. this.scaleValueImage = 0.88
  12650. }
  12651. });
  12652. // 第二步:切换图片后淡入
  12653. setTimeout(() => {
  12654. this.cover = this.songList[this.curIndex].pixelMapPath
  12655. this.getUIContext()?.animateTo({
  12656. duration: 500,
  12657. curve: Curve.EaseIn,
  12658. }, () => {
  12659. this.opacityValueImage = 1;
  12660. this.scaleValueImage = 1 // 图标恢复到原始大小
  12661. this.startPlayOrResumePlay()
  12662. });
  12663. }, 500);
  12664. }else{
  12665. this.cover = this.songList[this.curIndex].pixelMapPath
  12666. this.startPlayOrResumePlay()
  12667. }
  12668. }
  12669. // 存储已播放的歌曲索引
  12670. private playedIndices: Set<number> = new Set();
  12671. //随机播放
  12672. private async randomPlay() {
  12673. // if (!this.debounce()) {
  12674. // return;
  12675. // }
  12676. if (ArrayUtil.isNotEmpty(this.songList)) {
  12677. if (this.songList.length > 3) {
  12678. // 如果所有歌曲都播放过一次,清空已播放索引集合
  12679. if (this.playedIndices.size === this.songList.length) {
  12680. this.playedIndices.clear();
  12681. }
  12682. // 随机选择一个未播放的歌曲索引
  12683. let newIndex: number;
  12684. // 添加超时机制防止无限循环
  12685. let attempt = 0;
  12686. const maxAttempts = 100; // 根据需求调整
  12687. do {
  12688. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  12689. attempt++;
  12690. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  12691. if (attempt >= maxAttempts) {
  12692. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  12693. newIndex = Math.floor(Math.random() * this.songList.length);
  12694. }
  12695. this.curIndex = newIndex;
  12696. this.playedIndices.add(newIndex);
  12697. } else {
  12698. // 当歌曲数量小于或等于3时,直接播放下一首
  12699. if (this.curIndex == this.songList.length - 1) {
  12700. this.curIndex = 0;
  12701. } else {
  12702. this.curIndex++;
  12703. }
  12704. }
  12705. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12706. this.stop();
  12707. this.currentSong = this.songList[this.curIndex];
  12708. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12709. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  12710. context: this.context,
  12711. autoParseMusicName: this.autoParseMusicName
  12712. });
  12713. this.name = this.songList[this.curIndex].name;
  12714. this.artist = this.songList[this.curIndex].artist
  12715. // this.cover = this.songList[this.curIndex].pixelMapPath
  12716. this.changeImageAnimation()
  12717. }
  12718. }
  12719. private async playIndex(index: number) {
  12720. if (!this.debounce()) {
  12721. return;
  12722. }
  12723. if (ArrayUtil.isNotEmpty(this.songList)) {
  12724. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12725. this.stop();
  12726. this.curIndex = index;
  12727. this.currentSong = this.songList[index];
  12728. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12729. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  12730. context: this.context,
  12731. autoParseMusicName: this.autoParseMusicName
  12732. });
  12733. this.name = this.currentSong.name
  12734. this.artist = this.currentSong.artist
  12735. this.changeImageAnimation()
  12736. }
  12737. }
  12738. //上一个
  12739. private async playPrevious() {
  12740. if (!this.debounce()) {
  12741. return;
  12742. }
  12743. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  12744. this.randomModePlayFromHistory()
  12745. return;
  12746. }
  12747. if (this.curIndex == 0) {
  12748. this.curIndex = this.songList.length - 1;
  12749. } else {
  12750. this.curIndex--;
  12751. }
  12752. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12753. this.stop();
  12754. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  12755. this.currentSong = this.songList[this.curIndex];
  12756. Logger.info('heanup playPrevious', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  12757. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12758. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  12759. context: this.context,
  12760. autoParseMusicName: this.autoParseMusicName
  12761. });
  12762. this.name = this.songList[this.curIndex].name
  12763. this.artist = this.songList[this.curIndex].artist
  12764. this.changeImageAnimation()
  12765. }
  12766. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  12767. private async randomModePlayFromHistory() {
  12768. if (this.historyList.length >= 2) {
  12769. // 播放历史记录的第二首
  12770. const prevSong = this.historyList[1];
  12771. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  12772. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12773. this.stop();
  12774. // 直接使用历史记录中的歌曲信息,历史记录中的数据应该是完整的
  12775. this.currentSong = prevSong;
  12776. Logger.info('heanup randomModePlayFromHistory', `直接使用历史歌曲信息: ${prevSong.name}, type: ${prevSong.type}`);
  12777. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12778. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  12779. context: this.context,
  12780. autoParseMusicName: this.autoParseMusicName
  12781. });
  12782. this.cover = prevSong.pixelMapPath
  12783. this.artist = prevSong.artist
  12784. this.name = prevSong.name;
  12785. console.info('onecold startPlayOrResumePlay 11434')
  12786. this.startPlayOrResumePlay();
  12787. } else {
  12788. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  12789. if (this.curIndex === 0) {
  12790. this.curIndex = this.songList.length - 1;
  12791. } else {
  12792. this.curIndex--;
  12793. }
  12794. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12795. this.stop();
  12796. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  12797. this.currentSong = this.songList[this.curIndex];
  12798. Logger.info('heanup randomModePlayFromHistory', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  12799. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12800. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  12801. context: this.context,
  12802. autoParseMusicName: this.autoParseMusicName
  12803. });
  12804. this.artist = this.songList[this.curIndex].artist
  12805. this.name = this.songList[this.curIndex].name;
  12806. this.changeImageAnimation()
  12807. }
  12808. }
  12809. debounce() {
  12810. const delay = 600;
  12811. let cur = new Date().getTime();
  12812. if (cur - this.last > delay) {
  12813. this.last = cur;
  12814. return true;
  12815. }
  12816. return false;
  12817. }
  12818. /**
  12819. * Sets whether the screen is a constant based on the playback status.
  12820. */
  12821. watchStatus() {
  12822. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  12823. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  12824. this.windowClass.setWindowKeepScreenOn(true);
  12825. } else {
  12826. this.windowClass.setWindowKeepScreenOn(false);
  12827. }
  12828. }
  12829. /**
  12830. * Volume gesture method onActionStart.
  12831. *
  12832. * @param event Gesture event.
  12833. */
  12834. private customDialogComponentIdMM: number = 0
  12835. @Builder
  12836. customDialogComponentMM() {
  12837. Column() {
  12838. Row() {
  12839. Blank()
  12840. Text('验证密码')
  12841. .fontSize(22)
  12842. .fontColor($r('app.color.pri_bg'))
  12843. .margin({ top: 18 })
  12844. Blank()
  12845. Image($r('app.media.close'))
  12846. .fillColor(Color.White)
  12847. .margin({ top: 18, right: 18 })
  12848. .width(20)
  12849. .onClick(() => {
  12850. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  12851. })
  12852. }
  12853. .width('100%') // 使Row占据整个宽度
  12854. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  12855. Verify({
  12856. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  12857. });
  12858. }.height('60%')
  12859. .backgroundColor($r('app.color.index_background'))
  12860. .justifyContent(FlexAlign.SpaceBetween)
  12861. }
  12862. private handleVerifyCompleted(isSuccess: boolean) {
  12863. if (isSuccess) {
  12864. console.log('验证成功');
  12865. // 在这里处理验证成功后的逻辑
  12866. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  12867. this.currentPath = this.lockPath
  12868. this.getSortedFiles(this.currentPath)
  12869. } else {
  12870. // console.log('验证失败');
  12871. ToastUtil.showToast('验证失败')
  12872. }
  12873. }
  12874. private showVerifyDialog() {
  12875. promptAction.openCustomDialog({
  12876. transition: TransitionEffect.asymmetric(
  12877. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  12878. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  12879. ,
  12880. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  12881. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  12882. ),
  12883. builder: () => {
  12884. this.customDialogComponentMM()
  12885. },
  12886. isModal: true,
  12887. autoCancel: true,
  12888. maskColor: Color.Transparent,
  12889. alignment: DialogAlignment.Bottom,
  12890. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  12891. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  12892. console.log("dialog onWillDismiss")
  12893. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  12894. dismissDialogAction.dismiss()
  12895. }
  12896. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  12897. dismissDialogAction.dismiss()
  12898. }
  12899. }
  12900. }).then((dialogId: number) => {
  12901. this.customDialogComponentIdMM = dialogId
  12902. })
  12903. }
  12904. //左滑操作 移动文件 重命名 删除等操作
  12905. @Builder
  12906. DeleteButton(item: VideoItem, index: number, filePath: string) {
  12907. Row() {
  12908. //加入收藏
  12909. Button() {
  12910. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  12911. .fillColor(Color.White)
  12912. .width(20)
  12913. }
  12914. .width(40)
  12915. .height(40)
  12916. .type(ButtonType.Circle)
  12917. .backgroundColor(this.themeColor)
  12918. .margin(5)
  12919. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  12920. .onClick(() => {
  12921. if (item) {
  12922. this.doFav(item)
  12923. }
  12924. })
  12925. //加入下一首播放
  12926. Button() {
  12927. Image($r('app.media.next_to_play'))
  12928. .fillColor(Color.White)
  12929. .width(20)
  12930. }
  12931. .width(40)
  12932. .height(40)
  12933. .type(ButtonType.Circle)
  12934. .backgroundColor(this.themeColor)
  12935. .margin(5)
  12936. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  12937. .onClick(() => {
  12938. this.addToNextPlay(item);
  12939. })
  12940. //复制文件
  12941. Button() {
  12942. Image($r('app.media.copy'))
  12943. .fillColor(Color.White)
  12944. .width(20)
  12945. }
  12946. .width(40)
  12947. .height(40)
  12948. .type(ButtonType.Circle)
  12949. .backgroundColor(this.themeColor)
  12950. .margin(5)
  12951. .id(filePath + 'copy')
  12952. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  12953. .onClick(() => {
  12954. this.showCopyDialog(false, item, index, filePath + 'copy');
  12955. })
  12956. //移动文件
  12957. Button() {
  12958. Image($r('app.media.cut'))
  12959. .fillColor(Color.White)
  12960. .width(20)
  12961. }
  12962. .width(40)
  12963. .height(40)
  12964. .type(ButtonType.Circle)
  12965. .backgroundColor(this.themeColor)
  12966. .margin(5)
  12967. .id(filePath)
  12968. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  12969. .onClick(() => {
  12970. this.showCutDialog(false, item, index, filePath);
  12971. })
  12972. Button() {
  12973. Image($r('app.media.cut_current'))
  12974. .fillColor(Color.White)
  12975. .width(20)
  12976. }
  12977. .width(40)
  12978. .height(40)
  12979. .type(ButtonType.Circle)
  12980. .backgroundColor(this.themeColor)
  12981. .margin(5)
  12982. .id(filePath + 'current')
  12983. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  12984. (this.isHasDir ? Visibility.Visible : Visibility.None))
  12985. .onClick(() => {
  12986. this.showCutDialog(true, item, index, filePath + 'current');
  12987. })
  12988. //重命名
  12989. Button() {
  12990. Image($r('app.media.rename2'))
  12991. .fillColor(Color.White)
  12992. .width(20)
  12993. }
  12994. .width(40)
  12995. .height(40)
  12996. .type(ButtonType.Circle)
  12997. .backgroundColor(this.themeColor)
  12998. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  12999. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  13000. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  13001. .margin(5)
  13002. .onClick(() => {
  13003. this.showReNameDialog(item, index + '', filePath)
  13004. })
  13005. Button() {
  13006. Image($r('app.media.delete2'))
  13007. .fillColor(Color.White)
  13008. .width(20)
  13009. }
  13010. .width(40)
  13011. .height(40)
  13012. .type(ButtonType.Circle)
  13013. .backgroundColor(this.themeColor)
  13014. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  13015. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  13016. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  13017. .margin(5)
  13018. .onClick(() => {
  13019. this.selectedFiles.push(item)
  13020. this.showWarnIsDelete()
  13021. // this.showWarnIsDeleteFile(item, index + '', filePath)
  13022. })
  13023. Button() {
  13024. Image($r('app.media.share2'))
  13025. .fillColor(Color.White)
  13026. .width(20)
  13027. }
  13028. .width(40)
  13029. .height(40)
  13030. .type(ButtonType.Circle)
  13031. .backgroundColor(this.themeColor)
  13032. .margin(5)
  13033. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13034. .onClick(() => {
  13035. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  13036. })
  13037. }
  13038. }
  13039. /**
  13040. * 穿山甲banner广告
  13041. */
  13042. // private declare bannerAd: CSJNativeExpressAd;
  13043. // @State private status: string = "未加载"
  13044. // @State private isShowAd: boolean = false
  13045. // private declare mAdSlot: AdSlot;
  13046. // private mBiddingAdm = '' //服务端bidding才需要设置
  13047. // private expressLoadAdListener: NativeExpressAdListener = {
  13048. // /**
  13049. // * 加载失败的回调
  13050. // *
  13051. // * @param code
  13052. // * @param message
  13053. // */
  13054. // onError: (code: number, message: string) => {
  13055. // console.error("加载广告失败,code=" + code + ",message=" + message);
  13056. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  13057. // },
  13058. //
  13059. // /**
  13060. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  13061. // *
  13062. // * @param ads 返回的广告列表
  13063. // */
  13064. //
  13065. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  13066. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  13067. // if (ads && ads.length > 0) {
  13068. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  13069. // ad.setExpressInteractionListener({
  13070. // /**
  13071. // *广告的点击回调
  13072. // * @param type 广告的交互类型
  13073. // */
  13074. // onAdClicked: (type: number) => {
  13075. // console.log("BannerExpressAdPage==onAdClicked......");
  13076. // },
  13077. //
  13078. // /**
  13079. // * 广告的展示回调 每个广告仅回调一次
  13080. // * @param type 广告的交互类型
  13081. // */
  13082. // onAdShow: (type: number) => {
  13083. // console.log("BannerExpressAdPage==onAdShow......");
  13084. // },
  13085. //
  13086. // /**
  13087. // * 模板渲染失败
  13088. // */
  13089. // onRenderFail: (code: number, msg: string) => {
  13090. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  13091. // },
  13092. //
  13093. // /**
  13094. // * 模板渲染成功
  13095. // * @param width 返回view的宽 单位 vp
  13096. // * @param height 返回view的高 单位 vp
  13097. // */
  13098. // onRenderSuccess: (width: number, height: number) => {
  13099. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  13100. // this.bannerAd = ad;
  13101. // this.status = "广告加载完成待展示";
  13102. //
  13103. // this.showBannerAd()
  13104. // }
  13105. // })
  13106. // //渲染广告
  13107. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  13108. // this.setDislikeCallback(ad); //设置dislike
  13109. // ad.render(this.getUIContext())
  13110. // this.status = "广告加载中...";
  13111. // });
  13112. // }
  13113. // }
  13114. // }
  13115. //
  13116. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  13117. // ad.setDislikeCallback({
  13118. // /**
  13119. // * dislike show
  13120. // */
  13121. // onShow: () => {
  13122. // console.log("BannerExpressAdPage==dislike......show");
  13123. // },
  13124. //
  13125. // /**
  13126. // * @param position 选择的位置
  13127. // * @param value 选择的内容
  13128. // * @param enforceRemove 是否强制关闭广告
  13129. // */
  13130. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  13131. // this.isShowAd = false;
  13132. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  13133. // ",enforce=" + enforceRemove);
  13134. // },
  13135. //
  13136. // /**
  13137. // * 点击取消
  13138. // */
  13139. // onCancel: () => {
  13140. // console.log("BannerExpressAdPage==dislike......onCancel");
  13141. // }
  13142. //
  13143. // })
  13144. // }
  13145. /**
  13146. * 加载Banner广告
  13147. */
  13148. loadBannerAd(rit: string) {
  13149. // if (Utility.isNoble()) {
  13150. // return
  13151. // }
  13152. // if (!Utility.isPassInstallTime(2)) {
  13153. // return
  13154. // }
  13155. // this.isShowAd = false;
  13156. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  13157. // this.mAdSlot = new AdSlotBuilder()
  13158. // .setCodeId(rit)
  13159. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  13160. // .setAdCount(1)
  13161. // .setBidAdm(this.mBiddingAdm)
  13162. // .build()
  13163. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  13164. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  13165. // this.status = "广告加载中..."
  13166. }
  13167. /**
  13168. * 展示Banner广告
  13169. */
  13170. // showBannerAd() {
  13171. // if (!this.bannerAd) {
  13172. // return
  13173. // }
  13174. // this.isShowAd = true
  13175. // this.status = "已展示"
  13176. // }
  13177. /**
  13178. * 穿山甲广告代码结束
  13179. */
  13180. /**
  13181. * 处理歌单播放请求
  13182. */
  13183. private async handlePlaylistPlayRequest(playlistId: string, playlistName:
  13184. string, songFilePaths: string[], startIndex: number) {
  13185. try {
  13186. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 歌曲数量: ${songFilePaths.length}, 开始索引: ${startIndex}`)
  13187. // 检查是否为WebDAV播放请求
  13188. if (playlistId === 'webdav-playlist') {
  13189. Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
  13190. // 从全局内存读取videoItems数据
  13191. const videoItems = getWebdavVideoItems();
  13192. const currentPlayIndex = getWebdavCurrentPlayIndex();
  13193. Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
  13194. if (videoItems && videoItems.length > 0) {
  13195. // 验证webdav_account_id设置情况
  13196. const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
  13197. Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
  13198. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName)
  13199. return
  13200. } else {
  13201. return
  13202. }
  13203. }
  13204. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  13205. const songMap: Map<number, VideoItem> = new Map()
  13206. let completedQueries = 0
  13207. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  13208. // 遍历所有文件路径,使用索引记录位置
  13209. for (let i = 0; i < songFilePaths.length; i++) {
  13210. const filePath = songFilePaths[i]
  13211. const index = i
  13212. // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  13213. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  13214. const queryPromise = this.table.queryVideoByFilePath(filePath)
  13215. // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  13216. queryPromise.then((videoItem) => {
  13217. completedQueries++
  13218. // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  13219. if (videoItem) {
  13220. // 使用索引作为key保存到Map中,保持原始顺序
  13221. songMap.set(index, videoItem)
  13222. // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  13223. } else {
  13224. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  13225. }
  13226. // 检查是否所有歌曲都已加载完成
  13227. if (completedQueries === songFilePaths.length) {
  13228. // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  13229. // 按照索引顺序重建歌曲数组
  13230. const songs: VideoItem[] = []
  13231. for (let j = 0; j < songFilePaths.length; j++) {
  13232. const song = songMap.get(j)
  13233. if (song) {
  13234. songs.push(song)
  13235. // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  13236. }
  13237. }
  13238. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  13239. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  13240. }
  13241. }).catch((error: Error) => {
  13242. completedQueries++
  13243. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  13244. // 即使出错也要检查是否完成所有查询
  13245. if (completedQueries === songFilePaths.length) {
  13246. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  13247. // 按照索引顺序重建歌曲数组
  13248. const songs: VideoItem[] = []
  13249. for (let j = 0; j < songFilePaths.length; j++) {
  13250. const song = songMap.get(j)
  13251. if (song) {
  13252. songs.push(song)
  13253. }
  13254. }
  13255. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  13256. }
  13257. })
  13258. }
  13259. } catch (error) {
  13260. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  13261. ToastUtil.showToast('播放失败')
  13262. }
  13263. }
  13264. /**
  13265. * 完成歌单加载并开始播放
  13266. */
  13267. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string) {
  13268. if (songs.length === 0) {
  13269. Logger.error('heanup 没有找到任何可播放的歌曲')
  13270. ToastUtil.showToast('没有找到可播放的歌曲')
  13271. return
  13272. }
  13273. this.songList = songs
  13274. this.sonDataSource.pushArrayData(songs)
  13275. this.sonDataSource.notifyDataReload()
  13276. this.curIndex = startIndex
  13277. if (songs[startIndex]) {
  13278. // 确保当前播放的歌曲也更新到存储
  13279. AppStorage.setOrCreate('currentSong', songs[startIndex])
  13280. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  13281. this.doPlay(songs[startIndex], startIndex, true)
  13282. }
  13283. PreferencesUtil.putSync('LastMusicList', this.songList)
  13284. ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  13285. }
  13286. }
  13287. //视频气泡窗口的布局
  13288. @Builder
  13289. function customPopupBuilder(dataBu: BubbleBean) {
  13290. List() {
  13291. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  13292. ListItem() {
  13293. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13294. Row() {
  13295. Column() {
  13296. Image(dataBu.imageRes[index])
  13297. .height(28)
  13298. .fillColor(dataBu.color)
  13299. .alignSelf(ItemAlign.Center)
  13300. }
  13301. .width(32)
  13302. Text(item)
  13303. .padding({
  13304. top: 10,
  13305. bottom: 10,
  13306. right: 10,
  13307. left: 10
  13308. })
  13309. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  13310. .textAlign(TextAlign.Start)
  13311. .width("100%")
  13312. }
  13313. }
  13314. .backgroundColor($r('app.color.settings_background_main'))
  13315. .margin({ top: 6, bottom: 6 })
  13316. }
  13317. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  13318. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  13319. TransitionEffect.scale({ x: 0, y: 0 })))
  13320. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  13321. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  13322. .onClick(() => {
  13323. dataBu.onItemClick?.(index)
  13324. })
  13325. })
  13326. }
  13327. .scrollBar(BarState.Off)
  13328. .width(120)
  13329. .divider({
  13330. strokeWidth: 1,
  13331. color: "#22FFFFFF"
  13332. })
  13333. }
  13334. // Function to calculate a hash for the file list
  13335. function simpleHash(fileList: string[]): string {
  13336. let hash = 0;
  13337. const str = fileList.join(',');
  13338. for (let i = 0; i < str.length; i++) {
  13339. const char = str.charCodeAt(i);
  13340. hash = (hash << 5) - hash + char;
  13341. hash |= 0; // Convert to 32bit integer
  13342. }
  13343. return hash.toString();
  13344. }
  13345. interface MoreItem {
  13346. id: number;
  13347. image: Resource;
  13348. title: string;
  13349. }
  13350. //视频气泡窗口的布局
  13351. @Builder
  13352. function cutPopupBuilder(dataBu: BubbleBean) {
  13353. Column() {
  13354. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  13355. .padding({
  13356. top: 10,
  13357. bottom: 10,
  13358. right: 10,
  13359. left: 10
  13360. })
  13361. .textAlign(TextAlign.Start)
  13362. .width(160)
  13363. .fontWeight(666)
  13364. .fontSize(16)
  13365. List() {
  13366. ForEach(dataBu.data, (item: string, index: number) => {
  13367. ListItem() {
  13368. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13369. Row() {
  13370. Column() {
  13371. Image($r('app.media.music_group'))
  13372. .height(28)
  13373. .fillColor(dataBu.color)
  13374. .alignSelf(ItemAlign.Center)
  13375. }
  13376. .width(32)
  13377. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  13378. .padding({
  13379. top: 10,
  13380. bottom: 10,
  13381. right: 10,
  13382. left: 10
  13383. })
  13384. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  13385. .fontSize(15)
  13386. }
  13387. }
  13388. .backgroundColor(Color.Transparent)
  13389. .margin({ top: 7, bottom: 7 })
  13390. }
  13391. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  13392. .animation({ duration: 500 }),
  13393. TransitionEffect.scale({ x: 0, y: 0 })))
  13394. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  13395. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  13396. .onClick(() => {
  13397. dataBu.onItemClick?.(index)
  13398. })
  13399. })
  13400. }
  13401. .scrollBar(BarState.Off)
  13402. .width(150)
  13403. .divider({
  13404. strokeWidth: 1,
  13405. color: "#22FFFFFF"
  13406. })
  13407. }
  13408. .height(300)
  13409. .padding({
  13410. bottom: 30
  13411. })
  13412. }
  13413. function getFileDirName(filePath: string,rootPath:string): string{
  13414. if(filePath===rootPath){
  13415. return '首页'
  13416. }
  13417. let result = FileUtil.getFileName(filePath)
  13418. if(StrUtil.isEmpty(result))
  13419. return ''
  13420. if(result.startsWith('.'))
  13421. result = result.replace(/\./g, '')
  13422. return result
  13423. }
  13424. //只扫描当前目录下文件(不扫描子文件夹)的方法
  13425. @Concurrent
  13426. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  13427. const table: MediaTable = new MediaTable(context);
  13428. try {
  13429. // 直接获取当前目录下的文件列表
  13430. const files = FileUtil.listFileSync(dirPath);
  13431. await Promise.all(files.map(async (file) => {
  13432. const fPath = `${dirPath}/${file}`;
  13433. // 跳过目录,只处理文件
  13434. if (FileUtil.isDirectory(fPath)) {
  13435. return;
  13436. }
  13437. // 跳过特定格式文件
  13438. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  13439. return;
  13440. }
  13441. // 检查是否为媒体文件
  13442. if (Utility.isMeidaByExtension(fPath)) {
  13443. let mType = CommonConstants.TYPE_LOCAL;
  13444. if (fPath.includes(lockPath)) {
  13445. mType = CommonConstants.TYPE_LOCK;
  13446. }
  13447. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  13448. context, fPath, mType, true
  13449. );
  13450. table.insert(mediaItem, (id: number) => {
  13451. // 插入回调函数
  13452. }, cover_api);
  13453. }
  13454. }));
  13455. } catch (error) {
  13456. console.error(' 扫描当前目录失败:', error);
  13457. }
  13458. }
  13459. //内嵌标签后更新库
  13460. @Concurrent
  13461. async function updateInfoDb(
  13462. context: Context,
  13463. filePath: string,
  13464. titleStr: string,
  13465. artistStr: string,
  13466. albumStr: string,
  13467. lyricConStr: string,
  13468. yearStr: string,
  13469. genreStr: string,
  13470. trackStr: string,
  13471. albumArtistStr: string,
  13472. composerStr: string,
  13473. lyricistStr: string,
  13474. commentStr: string,
  13475. discStr: string,
  13476. ): Promise<boolean> {
  13477. const table: MediaTable = new MediaTable(context);
  13478. await new Promise<void>((resolve, reject) => {
  13479. table.getRdbStore(context, (err:Error) => {
  13480. err ? reject(err) : resolve();
  13481. });
  13482. });
  13483. return await new Promise<boolean>((resolve) => {
  13484. table.updateMediaInfo(filePath, titleStr, artistStr, albumStr, lyricConStr,
  13485. yearStr, genreStr, trackStr, albumArtistStr, composerStr, lyricistStr, commentStr, discStr,
  13486. (success: boolean, error?: string) => {
  13487. if (success) {
  13488. console.log("onecold 编辑信息成功,数据库已同步");
  13489. } else {
  13490. console.error("onecold 编辑信息数据库失败原因: " + error);
  13491. }
  13492. resolve(success);
  13493. });
  13494. });
  13495. }