LocalMusic.ets 520 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027
  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( this.currentSong?.pixelMapPath)
  6096. .height(45)
  6097. .objectFit(ImageFit.Contain)
  6098. .alt( $r('app.media.music_red'))
  6099. .fillColor(this.themeColor)
  6100. .borderRadius(8)
  6101. .shadow({
  6102. radius: 10,
  6103. type: ShadowType.BLUR,
  6104. color: 'on_primary'
  6105. })
  6106. .geometryTransition('cover', { follow: true }) // 绑定标识符
  6107. Column() {
  6108. Text(this.currentSong?.name)
  6109. .fontSize(16)
  6110. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  6111. .maxLines(1)
  6112. .fontColor(Color.White)
  6113. .fontWeight(500);
  6114. Row() {
  6115. Text(this.currentSong?.artist)
  6116. .margin({ top: 2 })
  6117. .fontSize(13)
  6118. .textAlign(TextAlign.Start)
  6119. .maxLines(1)
  6120. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  6121. .fontColor(Color.White)
  6122. }
  6123. .visibility(this.currentSong?.artist? Visibility.Visible:Visibility.None)
  6124. }
  6125. .padding({left:8})
  6126. .geometryTransition('name', { follow: true }) // 绑定标识符
  6127. .alignItems(isLeft?HorizontalAlign.Start:HorizontalAlign.End)
  6128. .margin({ right: isLeft?22:10 })
  6129. .visibility(isLeft? Visibility.Visible:Visibility.None)
  6130. }
  6131. .padding({ right: 18 })
  6132. .layoutWeight(isLeft?1:0)
  6133. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  6134. .onClick(() => {
  6135. this.showPlayerView()
  6136. })
  6137. }
  6138. setShowPlayTrue(){
  6139. this.getUIContext()?.animateTo({
  6140. duration: 500,
  6141. curve: Curve.Friction
  6142. }, () => {
  6143. this.isShowPlay = true;
  6144. });
  6145. }
  6146. setShowPlayFalse(){
  6147. this.getUIContext()?.animateTo({
  6148. duration: 500,
  6149. curve: Curve.Friction
  6150. }, () => {
  6151. this.isShowPlay = false;
  6152. });
  6153. }
  6154. //打开播放页
  6155. showPlayerView() {
  6156. if (ArrayUtil.isNotEmpty(this.songList)) {
  6157. this.setShowPlayTrue()
  6158. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  6159. this.initLyric(lyricPath);
  6160. this.startAutoHide();
  6161. } else {
  6162. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  6163. }
  6164. }
  6165. @Builder
  6166. playConRigth() {
  6167. Row() {
  6168. SymbolGlyph($r('sys.symbol.backward_end_fill'))
  6169. .fontSize(28)
  6170. .fontColor([this.themeColor])
  6171. .alignSelf(ItemAlign.Center)
  6172. .visibility(this.isShowPrecious? Visibility.Visible:Visibility.None)
  6173. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  6174. .margin({ left: 8, right: 14 })
  6175. .displayPriority(2)
  6176. .onClick(() => {
  6177. if (ArrayUtil.isNotEmpty(this.songList)) {
  6178. this.playPrevious()
  6179. } else {
  6180. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6181. }
  6182. })
  6183. //播放进度条
  6184. Stack() {
  6185. Progress({
  6186. value: Math.floor(this.progressValue),
  6187. type: ProgressType.Ring,
  6188. })
  6189. .color(this.themeColor)// 进度条前景色为灰色
  6190. .height(38)
  6191. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6192. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ? $r('app.media.hm_pause') : $r('app.media.hm_play2'))
  6193. .height(36)
  6194. .width(36)
  6195. .displayPriority(3)
  6196. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  6197. .fillColor(this.themeColor)
  6198. .onClick(() => {
  6199. if (ArrayUtil.isNotEmpty(this.songList)) {
  6200. console.info('onecold playOrPause 4642')
  6201. this.playOrPause()
  6202. } else {
  6203. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6204. }
  6205. })
  6206. }
  6207. SymbolGlyph($r('sys.symbol.forward_end_fill'))
  6208. .fontSize(28)
  6209. .fontColor([this.themeColor])
  6210. .alignSelf(ItemAlign.Center)
  6211. .margin({
  6212. right: 14,
  6213. left: 14
  6214. })
  6215. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  6216. .displayPriority(2)
  6217. .onClick(() => {
  6218. if (ArrayUtil.isNotEmpty(this.songList)) {
  6219. this.playNext()
  6220. } else {
  6221. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6222. }
  6223. })
  6224. Image($r('app.media.hm_playlist'))
  6225. .height(26)
  6226. .width(26)
  6227. .displayPriority(1)
  6228. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  6229. .fillColor(this.themeColor)
  6230. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  6231. height: '95%',
  6232. dragBar: true,
  6233. showClose: true,
  6234. blurStyle: BlurStyle.Thin,
  6235. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6236. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  6237. title: {
  6238. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  6239. + `(${this.songList.length}首)`
  6240. }
  6241. })
  6242. .onClick(() => {
  6243. if (ArrayUtil.isNotEmpty(this.songList)) {
  6244. this.isShowSheet = !this.isShowSheet;
  6245. this.isFrontWhite = false
  6246. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  6247. this.scrollIndex()
  6248. } else {
  6249. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6250. }
  6251. })
  6252. }
  6253. }
  6254. scrollIndex(){
  6255. try {
  6256. setTimeout(() => {
  6257. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  6258. if(this.curIndex>60){
  6259. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  6260. }else{
  6261. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  6262. }
  6263. })
  6264. }, 123)
  6265. }catch (error) {
  6266. console.error(`onecold scrollIndex出错: ${error}`);
  6267. }
  6268. }
  6269. //播放列表布局
  6270. @Builder
  6271. PlayListSheet() {
  6272. Column() {
  6273. this.PlayList()
  6274. }
  6275. .width('100%')
  6276. .height('100%')
  6277. }
  6278. @State titleStr: string = ''
  6279. @State ablumStr: string = ''
  6280. @State artistStr: string = ''
  6281. @State lyricConStr: string = ''
  6282. @State currentEditItem: string = ''
  6283. @State yearStr: string = ''
  6284. @State trackStr: string = ''
  6285. @State genreStr: string = ''
  6286. @State imagePathStr: string = ''
  6287. @State albumArtistStr: string = ''
  6288. @State composerStr: string = ''
  6289. @State lyricistStr: string = ''
  6290. @State commentStr: string = ''
  6291. @State discStr: string = ''
  6292. doUpdateData() {
  6293. setTimeout(() => {
  6294. if (this.modeType === 0) {
  6295. this.deleteCache(this.currentPath)
  6296. this.getSortedFiles(this.currentPath)
  6297. }else if (this.modeType === 1){
  6298. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6299. }
  6300. }, 500)
  6301. }
  6302. doAllUpdateData() {
  6303. setTimeout(() => {
  6304. if (this.modeType === 0) {
  6305. this.deleteCache(this.currentPath)
  6306. this.getSortedFiles(this.currentPath)
  6307. }
  6308. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6309. workerInstance.postMessage({ code: 3, data: this.context });
  6310. workerInstance.postMessage({ code: 4, data: this.context });
  6311. }, 999)
  6312. }
  6313. //编辑信息
  6314. async doEdit(item: VideoItem) {
  6315. if (!item) {
  6316. return
  6317. }
  6318. if (StrUtil.isEmpty(this.titleStr)) {
  6319. ToastUtil.showToast('标题不能为空')
  6320. return
  6321. }
  6322. DialogHelper.showLoadingDialog()
  6323. await PermissionUtil.activatePermission(item.filePath)
  6324. let tempOutPath = ''
  6325. // 如果不是 packName 包下的文件,则直接路径用this.currentPath
  6326. if(!item.filePath.toLowerCase().includes(this.packName)){
  6327. tempOutPath = this.currentPath + '/' + item.fileName
  6328. }
  6329. console.info('onecold tempOutPath ='+tempOutPath)
  6330. //用户更改了封面,那就内嵌下封面
  6331. if(StrUtil.isNotEmpty(this.imagePathStr)){
  6332. const resultCover:boolean = await changeMusicCover(this.context,
  6333. item.filePath,this.imagePathStr,true,tempOutPath);
  6334. this.imagePathStr = ''
  6335. if(resultCover){
  6336. ToastUtil.showToast('内嵌封面成功')
  6337. }
  6338. }
  6339. const metadata:FFMpegTags = {
  6340. title: this.titleStr,
  6341. artist: this.artistStr,
  6342. album: this.ablumStr,
  6343. TYER:this.yearStr,
  6344. genre:this.genreStr,
  6345. track:this.trackStr,
  6346. album_artist:this.albumArtistStr,
  6347. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  6348. COMPOSER:this.composerStr,
  6349. lyricist:this.lyricistStr,
  6350. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  6351. comment:this.commentStr,
  6352. disc:this.discStr,
  6353. };
  6354. let newInput = item.filePath
  6355. //内嵌标签歌路径如果不是包含包名,输入newInput要赋值tempOutPath,然后tempOutPath为空
  6356. if(!item.filePath.toLowerCase().includes(this.packName)&&FileUtil.accessSync(tempOutPath)){
  6357. newInput = tempOutPath
  6358. tempOutPath = ''
  6359. }
  6360. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  6361. const result:boolean = await repairAudioMetadata(
  6362. newInput,
  6363. this.lyricConStr,
  6364. metadata,
  6365. true,
  6366. tempOutPath
  6367. );
  6368. if (result) {
  6369. if(!item.filePath.includes(this.packName)){
  6370. //内嵌成功的歌路径如果不是包含包名,则要入库
  6371. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newInput,
  6372. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  6373. this.table.insert(newItem, (id: number) => {
  6374. //加入数据库
  6375. if(this.modeType==0){
  6376. this.deleteCache(this.currentPath)
  6377. this.getSortedFiles(this.currentPath)
  6378. }
  6379. });
  6380. }
  6381. const task = new taskpool.Task(
  6382. updateInfoDb,
  6383. this.context,
  6384. item.filePath,
  6385. this.titleStr,
  6386. this.artistStr,
  6387. this.ablumStr,
  6388. this.lyricConStr,
  6389. this.yearStr,this.genreStr,
  6390. this.trackStr,this.albumArtistStr,
  6391. this.composerStr, this.lyricistStr,
  6392. this.commentStr,this.discStr
  6393. );
  6394. taskpool.execute(task, taskpool.Priority.HIGH).then((result) => {
  6395. if (result) {
  6396. console.log(" onecold 编辑信息成功,数据库已同步");
  6397. ToastUtil.showToast('内嵌音乐标签成功')
  6398. this.isShowMoreView = false
  6399. this.name = this.titleStr
  6400. this.syncEditedFields(item)
  6401. if (item.filePath == this.currentSong?.filePath) {
  6402. this.currentSong.name = this.titleStr
  6403. this.artist = this.artistStr
  6404. this.currentSong.artist = this.artistStr
  6405. this.currentSong.album = this.ablumStr
  6406. this.currentSong.year = this.yearStr
  6407. this.currentSong.genre = this.genreStr
  6408. this.currentSong.track = this.trackStr
  6409. this.currentSong.lyricContent = this.lyricConStr
  6410. this.initLyric(item.filePath)
  6411. this.currentSong.ALBUMARTIST = this.albumArtistStr
  6412. this.currentSong.COMPOSER = this.composerStr
  6413. this.currentSong.LYRICIST = this.lyricistStr
  6414. this.currentSong.COMMENT = this.commentStr
  6415. }
  6416. this.syncListsAfterEdit(item.filePath)
  6417. this.doUpateEditedFields(item)
  6418. //this.doUpdateData()
  6419. } else {
  6420. // ToastUtil.showToast('保存失败' + error?.toString())
  6421. console.error(" onecold 编辑信息数据库失败 ");
  6422. }
  6423. }).catch((error: Error) => {
  6424. // 关闭进度条
  6425. DialogHelper.closeLoading();
  6426. console.error('onecold Subtitle sync failed:', error);
  6427. });
  6428. console.log(' onecold 元数据标签更新成功,');
  6429. } else {
  6430. // 关闭进度条
  6431. DialogHelper.closeLoading();
  6432. ToastUtil.showToast('内嵌音乐标签失败')
  6433. console.log('onecold 内嵌音乐标签失败');
  6434. }
  6435. this.longItemFilePath = ''
  6436. this.tempLyricContent = ''
  6437. this.isShowEdit = false
  6438. }
  6439. // 内嵌标签更新当前内嵌的Item
  6440. async doUpateEditedFields(item: VideoItem) {
  6441. // 找到当前项在 videoLocalList 中的索引
  6442. const index = this.videoLocalList.findIndex(video => video.filePath === item.filePath);
  6443. if (index !== -1) {
  6444. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  6445. const updatedItem = await this.table.queryVideoByFilePath(item.filePath)
  6446. // 只有当查询结果不为 null 时才更新列表
  6447. if (updatedItem !== null) {
  6448. // 更新 videoLocalList 中的项(通过创建新数组触发响应式更新)
  6449. this.videoLocalList = [
  6450. ...this.videoLocalList.slice(0, index),
  6451. updatedItem,
  6452. ...this.videoLocalList.slice(index + 1)
  6453. ];
  6454. // 同步更新 LazyDataSource
  6455. this.dataSource.pushArrayData(this.videoLocalList)
  6456. } else {
  6457. ToastUtil.showToast('未找到更新的数据');
  6458. }
  6459. }
  6460. DialogHelper.closeLoading();
  6461. }
  6462. @Builder
  6463. editSheet(item: VideoItem) {
  6464. Scroll() {
  6465. Column() {
  6466. this.editDetail(item)
  6467. }
  6468. }
  6469. .width('100%')
  6470. .height('100%')
  6471. }
  6472. @Builder
  6473. editDetail(item: VideoItem) {
  6474. Column() {
  6475. if (item) {
  6476. Row() {
  6477. Stack() {
  6478. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  6479. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  6480. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  6481. item.pixelMapPath)
  6482. .fillColor(this.themeColor)
  6483. .height(88)
  6484. .width(88)
  6485. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  6486. .borderRadius(12)
  6487. .clip(true)
  6488. .opacity(this.opacityItem)// 绑定透明度
  6489. .margin({ left: 25 })
  6490. }
  6491. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  6492. .onClick(async () => {
  6493. const imagePath:string | undefined = await this.goSelectImage(item);
  6494. if (imagePath) {
  6495. //用户更改过图片
  6496. this.imagePathStr = imagePath
  6497. }
  6498. })
  6499. .width('28%')
  6500. Row() {
  6501. Column() {
  6502. Text(item.name)
  6503. .fontSize(17)
  6504. .maxLines(1)
  6505. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6506. .animation({
  6507. duration: 555,
  6508. curve: 'Linear',
  6509. })
  6510. .fontColor(this.themeColor)
  6511. .margin({ left: 8 })
  6512. Row() {
  6513. Text(item.artist)
  6514. .fontSize(14)
  6515. .maxLines(1)
  6516. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6517. .padding({ top: 8 })
  6518. .fontColor(this.themeColor)
  6519. .margin({ left: 8 })
  6520. }
  6521. }
  6522. .height('100%')
  6523. .width(100)
  6524. .layoutWeight(1)
  6525. .justifyContent(FlexAlign.Center)
  6526. .alignItems(HorizontalAlign.Start)
  6527. Column() {
  6528. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6529. Row(){
  6530. SymbolGlyph($r('sys.symbol.picture'))
  6531. .fontSize(18)
  6532. .fontColor([Color.White])
  6533. Text('获取封面')
  6534. .margin({ left: 4 })
  6535. .fontSize(11)
  6536. .fontColor(Color.White)
  6537. .fontWeight(480)
  6538. .textAlign(TextAlign.Center)
  6539. }
  6540. .justifyContent(FlexAlign.Center)
  6541. }
  6542. .height(38)
  6543. .width(100)
  6544. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6545. .backgroundColor(this.themeColor)
  6546. .stateEffect(true)
  6547. .margin({ right: 35 })
  6548. .onClick(async () => {
  6549. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  6550. this.showTipsDialog();
  6551. return; // Return empty string when no API is configured
  6552. }
  6553. const imagePath:string | undefined = await this.doSearchCover(item);
  6554. console.info('onecold imagePath = '+imagePath)
  6555. if (StrUtil.isNotEmpty(imagePath)) {
  6556. //用户更改过图片
  6557. this.imagePathStr = imagePath
  6558. ToastUtil.showToast('获取封面成功')
  6559. }else{
  6560. ToastUtil.showToast('获取封面失败,请重试')
  6561. }
  6562. })
  6563. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6564. Row(){
  6565. SymbolGlyph($r('sys.symbol.input_mode'))
  6566. .fontSize(18)
  6567. .fontColor([Color.White])
  6568. Text('获取歌词')
  6569. .margin({ left: 4 })
  6570. .fontSize(11)
  6571. .fontColor(Color.White)
  6572. .fontWeight(480)
  6573. .textAlign(TextAlign.Center)
  6574. }
  6575. .justifyContent(FlexAlign.Center)
  6576. }
  6577. .height(38)
  6578. .width(100)
  6579. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6580. .backgroundColor(this.themeColor)
  6581. .stateEffect(true)
  6582. .margin({ top: 9, right: 35 })
  6583. .onClick(async () => {
  6584. //判断有没有设置api
  6585. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  6586. if (StrUtil.isEmpty(apiUrl)) {
  6587. this.isLyricSetting = false
  6588. this.showTipsDialog()
  6589. return
  6590. }
  6591. let artist = item.artist
  6592. let title = item.name
  6593. if(!artist)
  6594. artist = ''
  6595. if(!title)
  6596. title = ''
  6597. let res: string | undefined = await getApiLyric(apiUrl,title, artist, false);
  6598. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  6599. this.lyricConStr = res;
  6600. ToastUtil.showToast('获取歌词成功')
  6601. }else{
  6602. ToastUtil.showToast('获取歌词失败,请重试')
  6603. }
  6604. })
  6605. }
  6606. .justifyContent(FlexAlign.Start)
  6607. }
  6608. .height('100%')
  6609. .justifyContent(FlexAlign.Start)
  6610. .layoutWeight(1)
  6611. }
  6612. .width('100%')
  6613. .height(98)
  6614. Row() {
  6615. Text('标题:')
  6616. .fontSize(14)
  6617. .fontColor($r('app.color.text_color'))
  6618. .margin({ left: 22 })
  6619. TextInput({ text: item.name })
  6620. .height(40)
  6621. .maxLines(1)
  6622. .fontSize(14)
  6623. .layoutWeight(1)
  6624. .fontColor($r('app.color.text_color'))
  6625. .margin({ right: 20, left: 10 })
  6626. .onChange((val: string) => {
  6627. this.titleStr = val
  6628. })
  6629. }
  6630. .width('100%')
  6631. .margin({ top: 10, bottom: 10 })
  6632. .justifyContent(FlexAlign.Start)
  6633. Row() {
  6634. Text('艺术家:')
  6635. .fontSize(14)
  6636. .fontColor($r('app.color.text_color'))
  6637. .margin({ left: 22 })
  6638. TextInput({ text: item.artist })
  6639. .height(40)
  6640. .maxLines(1)
  6641. .fontSize(14)
  6642. .layoutWeight(1)
  6643. .fontColor($r('app.color.text_color'))
  6644. .margin({ right: 20, left: 10 })
  6645. .onChange((val: string) => {
  6646. this.artistStr = val
  6647. })
  6648. }
  6649. .width('100%')
  6650. .margin({ top: 10, bottom: 10 })
  6651. .justifyContent(FlexAlign.Start)
  6652. Row() {
  6653. Text('专辑名:')
  6654. .fontSize(14)
  6655. .fontColor($r('app.color.text_color'))
  6656. .margin({ left: 22 })
  6657. TextInput({ text: item.album })
  6658. .height(40)
  6659. .maxLines(1)
  6660. .fontSize(14)
  6661. .layoutWeight(1)
  6662. .fontColor($r('app.color.text_color'))
  6663. .margin({ right: 20, left: 10 })
  6664. .onChange((val: string) => {
  6665. this.ablumStr = val
  6666. })
  6667. }
  6668. .width('100%')
  6669. .margin({ top: 10, bottom: 10 })
  6670. .justifyContent(FlexAlign.Start)
  6671. Row() {
  6672. Column(){
  6673. Column(){
  6674. Text('歌词:')
  6675. .fontSize(14)
  6676. .fontColor($r('app.color.text_color'))
  6677. .margin({ top:9,left: 22 })
  6678. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6679. SymbolGlyph($r('sys.symbol.trash_fill'))
  6680. .fontSize(25)
  6681. .alignSelf(ItemAlign.Center)
  6682. .margin({ left: 22,top:25})
  6683. }
  6684. .backgroundColor(Color.Transparent)
  6685. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  6686. Visibility.None:Visibility.Visible)
  6687. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6688. .onClick(()=>{
  6689. this.lyricConStr = ''
  6690. this.lyricContent = ''
  6691. this.tempLyricContent = ''
  6692. })
  6693. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6694. SymbolGlyph($r('sys.symbol.plus'))
  6695. .fontSize(25)
  6696. .alignSelf(ItemAlign.Center)
  6697. .margin({ left: 22,top:25})
  6698. }
  6699. .backgroundColor(Color.Transparent)
  6700. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6701. .onClick( ()=>{
  6702. this.callFilePickerSelectFileForLyric()
  6703. })
  6704. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6705. SymbolGlyph($r('sys.symbol.traditional_square'))
  6706. .fontSize(25)
  6707. .alignSelf(ItemAlign.Center)
  6708. .margin({ left: 22,top:25})
  6709. }
  6710. .backgroundColor(Color.Transparent)
  6711. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  6712. Visibility.None:Visibility.Visible)
  6713. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6714. .onClick( ()=>{
  6715. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  6716. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  6717. })
  6718. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6719. Image($r('app.media.jianti'))
  6720. .height(25)
  6721. .fillColor($r('app.color.text_color'))
  6722. .alignSelf(ItemAlign.Center)
  6723. .margin({ left: 22,top:25})
  6724. }
  6725. .backgroundColor(Color.Transparent)
  6726. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  6727. Visibility.None:Visibility.Visible)
  6728. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6729. .onClick( ()=>{
  6730. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  6731. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  6732. })
  6733. }
  6734. .layoutWeight(1)
  6735. }
  6736. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  6737. this.tempLyricContent })
  6738. .type(TextAreaType.NORMAL)
  6739. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  6740. .fontSize(14)
  6741. .layoutWeight(1)
  6742. .fontColor($r('app.color.text_color'))
  6743. .margin({ right: 20, left: 10 })
  6744. .onChange((val: string) => {
  6745. this.lyricConStr = val
  6746. })
  6747. }
  6748. .width('100%')
  6749. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  6750. .margin({ top: 10, bottom: 10 })
  6751. .justifyContent(FlexAlign.Start)
  6752. Row() {
  6753. Text('年份:')
  6754. .fontSize(14)
  6755. .fontColor($r('app.color.text_color'))
  6756. .margin({ left: 22 })
  6757. TextInput({ text: item.year })
  6758. .height(40)
  6759. .maxLines(1)
  6760. .fontSize(14)
  6761. .type(InputType.Number)
  6762. .layoutWeight(1)
  6763. .fontColor($r('app.color.text_color'))
  6764. .margin({ right: 20, left: 10 })
  6765. .onChange((val: string) => {
  6766. this.yearStr = val
  6767. })
  6768. }
  6769. .width('100%')
  6770. .margin({ top: 10, bottom: 10 })
  6771. .justifyContent(FlexAlign.Start)
  6772. Row() {
  6773. Text('音轨号:')
  6774. .fontSize(14)
  6775. .fontColor($r('app.color.text_color'))
  6776. .margin({ left: 22 })
  6777. TextInput({ text:item.track=='未知'?'': item.track })
  6778. .height(40)
  6779. .maxLines(1)
  6780. .fontSize(14)
  6781. .type(InputType.Number)
  6782. .layoutWeight(1)
  6783. .fontColor($r('app.color.text_color'))
  6784. .margin({ right: 20, left: 10 })
  6785. .onChange((val: string) => {
  6786. this.trackStr = val
  6787. })
  6788. }
  6789. .width('100%')
  6790. .margin({ top: 10, bottom: 10 })
  6791. .justifyContent(FlexAlign.Start)
  6792. Row() {
  6793. Text('碟号:')
  6794. .fontSize(14)
  6795. .fontColor($r('app.color.text_color'))
  6796. .margin({ left: 22 })
  6797. TextInput({ text:item.disc })
  6798. .height(40)
  6799. .maxLines(1)
  6800. .fontSize(14)
  6801. .type(InputType.Number)
  6802. .layoutWeight(1)
  6803. .fontColor($r('app.color.text_color'))
  6804. .margin({ right: 20, left: 10 })
  6805. .onChange((val: string) => {
  6806. this.discStr = val
  6807. })
  6808. }
  6809. .width('100%')
  6810. .margin({ top: 10, bottom: 10 })
  6811. .justifyContent(FlexAlign.Start)
  6812. Row() {
  6813. Text('风格:')
  6814. .fontSize(14)
  6815. .fontColor($r('app.color.text_color'))
  6816. .margin({ left: 22 })
  6817. TextInput({ text: item.genre })
  6818. .height(40)
  6819. .maxLines(1)
  6820. .fontSize(14)
  6821. .layoutWeight(1)
  6822. .fontColor($r('app.color.text_color'))
  6823. .margin({ right: 20, left: 10 })
  6824. .onChange((val: string) => {
  6825. this.genreStr = val
  6826. })
  6827. }
  6828. .width('100%')
  6829. .margin({ top: 10, bottom: 10 })
  6830. .justifyContent(FlexAlign.Start)
  6831. Row() {
  6832. Text('专辑艺术家:')
  6833. .fontSize(14)
  6834. .fontColor($r('app.color.text_color'))
  6835. .margin({ left: 22 })
  6836. TextInput({ text: item.ALBUMARTIST })
  6837. .height(40)
  6838. .maxLines(1)
  6839. .fontSize(14)
  6840. .layoutWeight(1)
  6841. .fontColor($r('app.color.text_color'))
  6842. .margin({ right: 20, left: 10 })
  6843. .onChange((val: string) => {
  6844. this.albumArtistStr = val
  6845. })
  6846. }
  6847. .width('100%')
  6848. .margin({ top: 10, bottom: 10 })
  6849. .justifyContent(FlexAlign.Start)
  6850. Row() {
  6851. Text('作曲:')
  6852. .fontSize(14)
  6853. .fontColor($r('app.color.text_color'))
  6854. .margin({ left: 22 })
  6855. TextInput({ text: item.COMPOSER })
  6856. .height(40)
  6857. .maxLines(1)
  6858. .fontSize(14)
  6859. .layoutWeight(1)
  6860. .fontColor($r('app.color.text_color'))
  6861. .margin({ right: 20, left: 10 })
  6862. .onChange((val: string) => {
  6863. this.composerStr = val
  6864. })
  6865. }
  6866. .width('100%')
  6867. .margin({ top: 10, bottom: 10 })
  6868. .justifyContent(FlexAlign.Start)
  6869. Row() {
  6870. Text('作词:')
  6871. .fontSize(14)
  6872. .fontColor($r('app.color.text_color'))
  6873. .margin({ left: 22 })
  6874. TextInput({ text: item.LYRICIST })
  6875. .height(40)
  6876. .maxLines(1)
  6877. .fontSize(14)
  6878. .layoutWeight(1)
  6879. .fontColor($r('app.color.text_color'))
  6880. .margin({ right: 20, left: 10 })
  6881. .onChange((val: string) => {
  6882. this.lyricistStr = val
  6883. })
  6884. }
  6885. .width('100%')
  6886. .margin({ top: 10, bottom: 10 })
  6887. .justifyContent(FlexAlign.Start)
  6888. Row() {
  6889. Text('注释:')
  6890. .fontSize(14)
  6891. .fontColor($r('app.color.text_color'))
  6892. .margin({ left: 22 })
  6893. TextInput({ text: item.COMMENT })
  6894. .height(40)
  6895. .maxLines(1)
  6896. .fontSize(14)
  6897. .layoutWeight(1)
  6898. .fontColor($r('app.color.text_color'))
  6899. .margin({ right: 20, left: 10 })
  6900. .onChange((val: string) => {
  6901. this.commentStr = val
  6902. })
  6903. }
  6904. .width('100%')
  6905. .margin({ top: 10, bottom: 10 })
  6906. .justifyContent(FlexAlign.Start)
  6907. Row() {
  6908. Button('保存')
  6909. .fontColor(Color.White)
  6910. .layoutWeight(1)
  6911. .height(50)
  6912. .width(100)
  6913. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6914. .backgroundColor(this.themeColor)
  6915. .stateEffect(true)
  6916. .margin({ right: 20, bottom: 20 })
  6917. .onClick(async () => {
  6918. this.doEdit(item)
  6919. })
  6920. Button('取消')
  6921. .fontColor(Color.White)
  6922. .layoutWeight(1)
  6923. .height(50)
  6924. .width(100)
  6925. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6926. .backgroundColor(this.themeColor)
  6927. .stateEffect(true)
  6928. .margin({ left: 20, bottom: 20 })
  6929. .onClick(async () => {
  6930. if(this.isGridMusic){
  6931. this.longItemFilePath =''
  6932. }else{
  6933. this.isShowEdit = false
  6934. }
  6935. this.setEditStrEmpty()
  6936. if(this.isShowPlay){
  6937. this.isShowEdit = false
  6938. }
  6939. })
  6940. }
  6941. .margin({
  6942. left: 38,
  6943. right: 38,
  6944. top: 10,
  6945. bottom: 10
  6946. })
  6947. .width(250)
  6948. .height(60)
  6949. }
  6950. }
  6951. .margin({ bottom: 20 })
  6952. }
  6953. setEditStrEmpty(){
  6954. this.imagePathStr = ''
  6955. this.lyricConStr = ''
  6956. this.artistStr = ''
  6957. this.titleStr = ''
  6958. this.ablumStr = ''
  6959. this.genreStr = ''
  6960. this.yearStr = ''
  6961. this.trackStr = ''
  6962. this.albumArtistStr = ''
  6963. this.composerStr = ''
  6964. this.lyricistStr = ''
  6965. this.commentStr = ''
  6966. this.discStr = ''
  6967. }
  6968. initEditFields(item?: VideoItem) {
  6969. if (!item) {
  6970. this.setEditStrEmpty()
  6971. return
  6972. }
  6973. this.imagePathStr = ''
  6974. this.titleStr = item.name ?? ''
  6975. this.artistStr = item.artist ?? ''
  6976. this.ablumStr = item.album ?? ''
  6977. this.genreStr = item.genre ?? ''
  6978. this.yearStr = item.year ?? ''
  6979. this.trackStr = item.track ?? ''
  6980. this.albumArtistStr = item.ALBUMARTIST ?? ''
  6981. this.composerStr = item.COMPOSER ?? ''
  6982. this.lyricistStr = item.LYRICIST ?? ''
  6983. this.commentStr = item.COMMENT ?? ''
  6984. this.discStr = item.disc ?? ''
  6985. this.lyricConStr = item.lyricContent ?? ''
  6986. }
  6987. private syncEditedFields(target?: VideoItem) {
  6988. if (!target) {
  6989. return
  6990. }
  6991. target.name = this.titleStr
  6992. target.artist = this.artistStr
  6993. target.album = this.ablumStr
  6994. target.lyricContent = this.lyricConStr
  6995. target.year = this.yearStr
  6996. target.genre = this.genreStr
  6997. target.track = this.trackStr
  6998. target.ALBUMARTIST = this.albumArtistStr
  6999. target.COMPOSER = this.composerStr
  7000. target.LYRICIST = this.lyricistStr
  7001. target.COMMENT = this.commentStr
  7002. target.disc = this.discStr
  7003. }
  7004. private replaceItemInList(list: Array<VideoItem> | undefined, filePath: string,
  7005. apply?: (next: Array<VideoItem>) => void) {
  7006. if (!list || ArrayUtil.isEmpty(list)) {
  7007. return
  7008. }
  7009. const index = list.findIndex((video: VideoItem) => video.filePath === filePath)
  7010. if (index < 0) {
  7011. return
  7012. }
  7013. const nextList = [...list]
  7014. this.syncEditedFields(nextList[index])
  7015. apply?.(nextList)
  7016. }
  7017. private syncListsAfterEdit(filePath: string) {
  7018. this.replaceItemInList(this.videoLocalList, filePath, (next: Array<VideoItem>) => {
  7019. this.videoLocalList = next
  7020. this.dataSource.pushArrayData(next)
  7021. })
  7022. this.replaceItemInList(this.songList, filePath, (next: Array<VideoItem>) => {
  7023. this.songList = next
  7024. this.sonDataSource.pushArrayData(next)
  7025. })
  7026. this.replaceItemInList(this.favList, filePath, (next: Array<VideoItem>) => {
  7027. this.favList = next
  7028. })
  7029. this.replaceItemInList(this.historyList, filePath, (next: Array<VideoItem>) => {
  7030. this.historyList = next
  7031. })
  7032. this.replaceItemInList(this.currentSongList, filePath, (next: Array<VideoItem>) => {
  7033. this.currentSongList = next
  7034. })
  7035. this.replaceItemInList(this.mediaKuList, filePath, (next: Array<VideoItem>) => {
  7036. this.mediaKuList = next
  7037. })
  7038. this.replaceItemInList(this.filteredList, filePath, (next: Array<VideoItem>) => {
  7039. this.filteredList = next
  7040. })
  7041. this.replaceItemInList(this.artistList, filePath, (next: Array<VideoItem>) => {
  7042. this.artistList = next
  7043. })
  7044. this.replaceItemInList(this.albumList, filePath, (next: Array<VideoItem>) => {
  7045. this.albumList = next
  7046. })
  7047. this.listRefreshKey++
  7048. }
  7049. @Builder
  7050. detailSheet(item:VideoItem) {
  7051. Scroll() {
  7052. Column() {
  7053. this.songDetail(item)
  7054. }
  7055. }
  7056. .width('100%')
  7057. .height('100%')
  7058. }
  7059. @Builder
  7060. songDetail(currentItem:VideoItem) {
  7061. Column() {
  7062. if (currentItem) {
  7063. Row() {
  7064. Stack() {
  7065. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.music_red') :
  7066. currentItem.pixelMapPath)
  7067. .fillColor(this.themeColor)
  7068. .height(80)
  7069. .width(80)
  7070. .borderRadius(10)
  7071. .opacity(this.opacityItem)// 绑定透明度
  7072. .margin({ left: 22 })
  7073. }
  7074. Column() {
  7075. Column() {
  7076. Text(currentItem.name)
  7077. .fontSize(16)
  7078. .maxLines(1)
  7079. .animation({
  7080. duration: 555,
  7081. curve: 'Linear',
  7082. })
  7083. .fontColor($r('app.color.text_color'))
  7084. .margin({ left: 15 })
  7085. }
  7086. .height('100%')
  7087. .width('100%')
  7088. .justifyContent(FlexAlign.Center)
  7089. .alignItems(HorizontalAlign.Start)
  7090. }
  7091. .height('100%')
  7092. }
  7093. .width('100%')
  7094. .height(90)
  7095. .justifyContent(FlexAlign.SpaceBetween)
  7096. Row() {
  7097. Text('艺术家:')
  7098. .fontSize(14)
  7099. .fontColor($r('app.color.text_color'))
  7100. .margin({ left: 22 })
  7101. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  7102. .fontSize(14)
  7103. .fontColor($r('app.color.text_color'))
  7104. .margin({ left: 10 })
  7105. .layoutWeight(1)
  7106. }
  7107. .width('100%')
  7108. .margin({ top: 10, bottom: 10 })
  7109. .justifyContent(FlexAlign.Start)
  7110. Row() {
  7111. Text('专辑名:')
  7112. .fontSize(14)
  7113. .fontColor($r('app.color.text_color'))
  7114. .margin({ left: 22 })
  7115. Text(currentItem?.album ?currentItem.album : '未知专辑')
  7116. .fontSize(14)
  7117. .margin({ left: 10 })
  7118. .fontColor($r('app.color.text_color'))
  7119. .layoutWeight(1)
  7120. }
  7121. .width('100%')
  7122. .margin({ top: 10, bottom: 10 })
  7123. .justifyContent(FlexAlign.Start)
  7124. Row() {
  7125. Text('时长:')
  7126. .fontSize(14)
  7127. .fontColor($r('app.color.text_color'))
  7128. .margin({ left: 22 })
  7129. Text(StrUtil.isEmpty(currentItem.duration)?
  7130. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  7131. .fontSize(14)
  7132. .margin({ left: 10 })
  7133. .fontColor($r('app.color.text_color'))
  7134. .layoutWeight(1)
  7135. }
  7136. .width('100%')
  7137. .margin({ top: 10, bottom: 10 })
  7138. .justifyContent(FlexAlign.Start)
  7139. Row() {
  7140. Text('采样率:')
  7141. .fontSize(14)
  7142. .fontColor($r('app.color.text_color'))
  7143. .margin({ left: 22 })
  7144. Text(Utility.convertToKHz(currentItem.sampleRate))
  7145. .fontSize(14)
  7146. .margin({ left: 10 })
  7147. .fontColor($r('app.color.text_color'))
  7148. .layoutWeight(1)
  7149. }
  7150. .width('100%')
  7151. .margin({ top: 10, bottom: 10 })
  7152. .justifyContent(FlexAlign.Start)
  7153. Row() {
  7154. Text('比特率:')
  7155. .fontSize(14)
  7156. .fontColor($r('app.color.text_color'))
  7157. .margin({ left: 22 })
  7158. Text(currentItem.bit_rate)
  7159. .fontSize(14)
  7160. .margin({ left: 10 })
  7161. .fontColor($r('app.color.text_color'))
  7162. .layoutWeight(1)
  7163. }
  7164. .width('100%')
  7165. .margin({ top: 10, bottom: 10 })
  7166. .justifyContent(FlexAlign.Start)
  7167. Row() {
  7168. Text('位深:')
  7169. .fontSize(14)
  7170. .fontColor($r('app.color.text_color'))
  7171. .margin({ left: 22 })
  7172. Text(`${currentItem.bits_per_raw_sample} bits`)
  7173. .fontSize(14)
  7174. .margin({ left: 10 })
  7175. .fontColor($r('app.color.text_color'))
  7176. .layoutWeight(1)
  7177. }
  7178. .width('100%')
  7179. .margin({ top: 10, bottom: 10 })
  7180. .justifyContent(FlexAlign.Start)
  7181. Row() {
  7182. Text('声道:')
  7183. .fontSize(14)
  7184. .fontColor($r('app.color.text_color'))
  7185. .margin({ left: 22 })
  7186. Text(`${currentItem.channels}`)
  7187. .fontSize(14)
  7188. .margin({ left: 10 })
  7189. .fontColor($r('app.color.text_color'))
  7190. .layoutWeight(1)
  7191. }
  7192. .width('100%')
  7193. .margin({ top: 10, bottom: 10 })
  7194. .justifyContent(FlexAlign.Start)
  7195. Row() {
  7196. Text('声道布局:')
  7197. .fontSize(14)
  7198. .fontColor($r('app.color.text_color'))
  7199. .margin({ left: 22 })
  7200. Text(`${currentItem.channel_layout}`)
  7201. .fontSize(14)
  7202. .margin({ left: 10 })
  7203. .fontColor($r('app.color.text_color'))
  7204. .layoutWeight(1)
  7205. }
  7206. .width('100%')
  7207. .margin({ top: 10, bottom: 10 })
  7208. .justifyContent(FlexAlign.Start)
  7209. Row() {
  7210. Text('起始播放点:')
  7211. .fontSize(14)
  7212. .fontColor($r('app.color.text_color'))
  7213. .margin({ left: 22 })
  7214. Text(`${currentItem.start_time}`)
  7215. .fontSize(14)
  7216. .margin({ left: 10 })
  7217. .fontColor($r('app.color.text_color'))
  7218. .layoutWeight(1)
  7219. }
  7220. .width('100%')
  7221. .margin({ top: 10, bottom: 10 })
  7222. .justifyContent(FlexAlign.Start)
  7223. Row() {
  7224. Text('风格:')
  7225. .fontSize(14)
  7226. .fontColor($r('app.color.text_color'))
  7227. .margin({ left: 22 })
  7228. Text(currentItem.genre)
  7229. .fontSize(14)
  7230. .margin({ left: 10 })
  7231. .fontColor($r('app.color.text_color'))
  7232. .layoutWeight(1)
  7233. }
  7234. .width('100%')
  7235. .margin({ top: 10, bottom: 10 })
  7236. .justifyContent(FlexAlign.Start)
  7237. Row() {
  7238. Text('发行时间:')
  7239. .fontSize(14)
  7240. .fontColor($r('app.color.text_color'))
  7241. .margin({ left: 22 })
  7242. Text(currentItem.year)
  7243. .fontSize(14)
  7244. .margin({ left: 10 })
  7245. .fontColor($r('app.color.text_color'))
  7246. .layoutWeight(1)
  7247. }
  7248. .width('100%')
  7249. .margin({ top: 10, bottom: 10 })
  7250. .justifyContent(FlexAlign.Start)
  7251. Row() {
  7252. Text('质量评分:')
  7253. .fontSize(14)
  7254. .fontColor($r('app.color.text_color'))
  7255. .margin({ left: 22 })
  7256. Text(currentItem.probe_score+"")
  7257. .fontSize(14)
  7258. .margin({ left: 10 })
  7259. .fontColor($r('app.color.text_color'))
  7260. .layoutWeight(1)
  7261. }
  7262. .width('100%')
  7263. .margin({ top: 10, bottom: 10 })
  7264. .justifyContent(FlexAlign.Start)
  7265. Row() {
  7266. Text('音轨号:')
  7267. .fontSize(14)
  7268. .fontColor($r('app.color.text_color'))
  7269. .margin({ left: 22 })
  7270. Text(currentItem.track)
  7271. .fontSize(14)
  7272. .margin({ left: 10 })
  7273. .fontColor($r('app.color.text_color'))
  7274. .layoutWeight(1)
  7275. }
  7276. .width('100%')
  7277. .margin({ top: 10, bottom: 10 })
  7278. .justifyContent(FlexAlign.Start)
  7279. Row() {
  7280. Text('碟号:')
  7281. .fontSize(14)
  7282. .fontColor($r('app.color.text_color'))
  7283. .margin({ left: 22 })
  7284. Text(currentItem.disc)
  7285. .fontSize(14)
  7286. .margin({ left: 10 })
  7287. .fontColor($r('app.color.text_color'))
  7288. .layoutWeight(1)
  7289. }
  7290. .width('100%')
  7291. .margin({ top: 10, bottom: 10 })
  7292. .justifyContent(FlexAlign.Start)
  7293. Row() {
  7294. Text('专辑艺术家:')
  7295. .fontSize(14)
  7296. .fontColor($r('app.color.text_color'))
  7297. .margin({ left: 22 })
  7298. Text(currentItem.ALBUMARTIST)
  7299. .fontSize(14)
  7300. .margin({ left: 10 })
  7301. .fontColor($r('app.color.text_color'))
  7302. .layoutWeight(1)
  7303. }
  7304. .width('100%')
  7305. .margin({ top: 10, bottom: 10 })
  7306. .justifyContent(FlexAlign.Start)
  7307. Row() {
  7308. Text('作曲家:')
  7309. .fontSize(14)
  7310. .fontColor($r('app.color.text_color'))
  7311. .margin({ left: 22 })
  7312. Text(currentItem.COMPOSER)
  7313. .fontSize(14)
  7314. .margin({ left: 10 })
  7315. .fontColor($r('app.color.text_color'))
  7316. .layoutWeight(1)
  7317. }
  7318. .width('100%')
  7319. .margin({ top: 10, bottom: 10 })
  7320. .justifyContent(FlexAlign.Start)
  7321. Row() {
  7322. Text('作词家:')
  7323. .fontSize(14)
  7324. .fontColor($r('app.color.text_color'))
  7325. .margin({ left: 22 })
  7326. Text(currentItem.LYRICIST)
  7327. .fontSize(14)
  7328. .margin({ left: 10 })
  7329. .fontColor($r('app.color.text_color'))
  7330. .layoutWeight(1)
  7331. }
  7332. .width('100%')
  7333. .margin({ top: 10, bottom: 10 })
  7334. .justifyContent(FlexAlign.Start)
  7335. Row() {
  7336. Text('注释:')
  7337. .fontSize(14)
  7338. .fontColor($r('app.color.text_color'))
  7339. .margin({ left: 22 })
  7340. Text(currentItem.COMMENT)
  7341. .fontSize(14)
  7342. .margin({ left: 10 })
  7343. .fontColor($r('app.color.text_color'))
  7344. .layoutWeight(1)
  7345. }
  7346. .width('100%')
  7347. .margin({ top: 10, bottom: 10 })
  7348. .justifyContent(FlexAlign.Start)
  7349. Row() {
  7350. Text('格式:')
  7351. .fontSize(14)
  7352. .fontColor($r('app.color.text_color'))
  7353. .margin({ left: 22 })
  7354. Text(Utility.formatMimeType(currentItem.mimeType))
  7355. .fontSize(14)
  7356. .margin({ left: 10 })
  7357. .fontColor($r('app.color.text_color'))
  7358. .layoutWeight(1)
  7359. }
  7360. .width('100%')
  7361. .margin({ top: 10, bottom: 10 })
  7362. .justifyContent(FlexAlign.Start)
  7363. Row() {
  7364. Text('播放次数:')
  7365. .fontSize(14)
  7366. .fontColor($r('app.color.text_color'))
  7367. .margin({ left: 22 })
  7368. Text(currentItem.playCount?.toString())
  7369. .fontSize(14)
  7370. .margin({ left: 10 })
  7371. .fontColor($r('app.color.text_color'))
  7372. .layoutWeight(1)
  7373. }
  7374. .width('100%')
  7375. .margin({ top: 10, bottom: 10 })
  7376. .justifyContent(FlexAlign.Start)
  7377. Row() {
  7378. Text('流数量:')
  7379. .fontSize(14)
  7380. .fontColor($r('app.color.text_color'))
  7381. .margin({ left: 22 })
  7382. Text(currentItem.nb_streams?.toString())
  7383. .fontSize(14)
  7384. .margin({ left: 10 })
  7385. .fontColor($r('app.color.text_color'))
  7386. .layoutWeight(1)
  7387. }
  7388. .width('100%')
  7389. .margin({ top: 10, bottom: 10 })
  7390. .justifyContent(FlexAlign.Start)
  7391. Row() {
  7392. Text('文件大小:')
  7393. .fontSize(14)
  7394. .fontColor($r('app.color.text_color'))
  7395. .margin({ left: 22 })
  7396. Text(currentItem.size)
  7397. .fontSize(14)
  7398. .margin({ left: 10 })
  7399. .fontColor($r('app.color.text_color'))
  7400. .layoutWeight(1)
  7401. }
  7402. .width('100%')
  7403. .margin({ top: 10, bottom: 10 })
  7404. .justifyContent(FlexAlign.Start)
  7405. Row() {
  7406. Text('文件名:')
  7407. .fontSize(14)
  7408. .fontColor($r('app.color.text_color'))
  7409. .margin({ left: 22 })
  7410. Text(currentItem.fileName)
  7411. .fontSize(14)
  7412. .margin({ left: 10 })
  7413. .fontColor($r('app.color.text_color'))
  7414. .layoutWeight(1)
  7415. }
  7416. .width('100%')
  7417. .margin({ top: 10, bottom: 10 })
  7418. .justifyContent(FlexAlign.Start)
  7419. Row() {
  7420. Text('修改时间:')
  7421. .fontSize(14)
  7422. .fontColor($r('app.color.text_color'))
  7423. .margin({ left: 22 })
  7424. Text(currentItem.cTime)
  7425. .fontSize(14)
  7426. .margin({ left: 10 })
  7427. .fontColor($r('app.color.text_color'))
  7428. .layoutWeight(1)
  7429. }
  7430. .width('100%')
  7431. .margin({ top: 10, bottom: 10 })
  7432. .justifyContent(FlexAlign.Start)
  7433. Row() {
  7434. Text('存放目录:')
  7435. .fontSize(14)
  7436. .fontColor($r('app.color.text_color'))
  7437. .margin({ left: 22 })
  7438. Text(currentItem.filePath)
  7439. .fontSize(12)
  7440. .margin({ left: 10 })
  7441. .fontColor($r('app.color.text_color'))
  7442. .layoutWeight(1)
  7443. }
  7444. .margin({ top: 10, bottom: 10 })
  7445. .width('100%')
  7446. .justifyContent(FlexAlign.Start)
  7447. Row() {
  7448. Text('内嵌歌词:')
  7449. .fontSize(14)
  7450. .fontColor($r('app.color.text_color'))
  7451. .margin({ left: 22 })
  7452. Text(currentItem.lyricContent)
  7453. .fontSize(12)
  7454. .copyOption(CopyOptions.InApp)
  7455. .margin({ left: 10 })
  7456. .fontColor($r('app.color.text_color'))
  7457. .layoutWeight(1)
  7458. }
  7459. .margin({ top: 10, bottom: 10 })
  7460. .width('100%')
  7461. .justifyContent(FlexAlign.Start)
  7462. }
  7463. }
  7464. .margin({ bottom: 20 })
  7465. }
  7466. //定时关闭布局
  7467. @Builder
  7468. TimeCloseSheet() {
  7469. Scroll() {
  7470. Column() {
  7471. this.TimeClose()
  7472. }
  7473. }
  7474. .width('100%')
  7475. .height('100%')
  7476. }
  7477. //倒计时关闭音乐,退出App功能实现。
  7478. @State selectedMinutes: number = 0 // 0表示未开启
  7479. @State remainingSeconds: number = 0
  7480. // 预设时间选项
  7481. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  7482. private formatTime(seconds: number): string {
  7483. const mins = Math.floor(seconds / 60)
  7484. const secs = seconds % 60
  7485. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  7486. }
  7487. // 开始倒计时
  7488. private handleTimeSelect(minutes: number) {
  7489. if (minutes === this.selectedMinutes) {
  7490. this.stopCountdown();
  7491. this.selectedMinutes = 0;
  7492. return;
  7493. }
  7494. this.selectedMinutes = minutes;
  7495. this.remainingSeconds = minutes * 60;
  7496. this.startCountdown(); // 新增调用
  7497. }
  7498. @Builder
  7499. TimeClose() {
  7500. Column() {
  7501. // 倒计时显示区域
  7502. Text(this.selectedMinutes > 0 ?
  7503. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  7504. "定时关闭未开启")
  7505. .fontSize(17)
  7506. .fontColor($r('app.color.text_color'))
  7507. .margin({ top: 2, bottom: 8 });
  7508. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  7509. ForEach(this.presetTimes, (minutes: number, index: number) => {
  7510. // 单行时间选项容器
  7511. Row() {
  7512. // 文字描述区域
  7513. Text(this.getDisplayText(minutes))
  7514. .fontSize(15)
  7515. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  7516. $r('app.color.text_color'))// 选中态颜色变化
  7517. .textAlign(TextAlign.Start)
  7518. .layoutWeight(1); // 占据剩余空间
  7519. // 复选框样式的选择器
  7520. Row() {
  7521. if (minutes === this.selectedMinutes) {
  7522. // 选中状态 - 带勾号的圆形复选框
  7523. Row() {
  7524. // 使用系统内置的勾号图标
  7525. Image($r('sys.media.ohos_ic_public_ok'))
  7526. .width(14)
  7527. .height(14)
  7528. .fillColor(Color.White)
  7529. }
  7530. .width(24)
  7531. .height(24)
  7532. .borderRadius(12)
  7533. .backgroundColor(this.themeColor)
  7534. .justifyContent(FlexAlign.Center)
  7535. .alignItems(VerticalAlign.Center)
  7536. } else {
  7537. // 未选中状态的圆形边框
  7538. Row()
  7539. .width(24)
  7540. .height(24)
  7541. .borderRadius(12)
  7542. .border({
  7543. width: 2,
  7544. color: $r('app.color.text_color'),
  7545. style: BorderStyle.Solid
  7546. })
  7547. .backgroundColor(Color.Transparent)
  7548. }
  7549. }
  7550. .width(24)
  7551. .height(24)
  7552. .margin({ left: 20 })
  7553. .justifyContent(FlexAlign.Center)
  7554. .alignItems(VerticalAlign.Center)
  7555. }
  7556. .width('100%')
  7557. .padding({
  7558. top: 18,
  7559. bottom: 18,
  7560. left: 18,
  7561. right: 18
  7562. })
  7563. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  7564. $r('app.color.bottom_control_background')) // 选中背景高亮
  7565. .borderRadius(12)
  7566. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7567. .margin({ bottom: 18 })
  7568. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  7569. });
  7570. }
  7571. .width('100%')
  7572. .padding(16)
  7573. }
  7574. }
  7575. // 获取显示文本
  7576. private getDisplayText(minutes: number): string {
  7577. if (minutes === -1) {
  7578. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  7579. }
  7580. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  7581. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  7582. }
  7583. // 处理选择事件
  7584. private handleSelect(minutes: number): void {
  7585. if (minutes === -1) { // 自定义
  7586. // 弹出自定义时间对话框
  7587. DialogHelper.showTextInputDialog({
  7588. title: '自定义时间',
  7589. maskColor: Color.Transparent,
  7590. inputType: InputType.Number,
  7591. text: '',
  7592. onChange: (text) => {
  7593. console.error("onChange: " + text);
  7594. },
  7595. onAction: (action, dialogId, content) => {
  7596. if (action == DialogAction.TWO) {
  7597. const customMinutes = Number(content);
  7598. if (customMinutes > 0) {
  7599. this.handleTimeSelect(customMinutes); // 设置自定义时间
  7600. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  7601. }
  7602. }
  7603. }
  7604. });
  7605. } else {
  7606. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  7607. }
  7608. }
  7609. // 添加定时器引用
  7610. private timerId: number = -1;
  7611. // 启动/重置倒计时
  7612. private startCountdown() {
  7613. // 清除旧定时器
  7614. if (this.timerId !== -1) {
  7615. clearInterval(this.timerId);
  7616. }
  7617. // 创建新定时器
  7618. if (this.selectedMinutes > 0) {
  7619. this.timerId = setInterval(() => {
  7620. if (this.remainingSeconds === 15) {
  7621. this.showConfirmationDialog();
  7622. }
  7623. if (this.remainingSeconds > 0) {
  7624. this.remainingSeconds -= 1;
  7625. } else {
  7626. this.stopCountdown();
  7627. this.handleTimeout();
  7628. }
  7629. }, 1000);
  7630. }
  7631. }
  7632. // 15倒计时后再次提示显示确认是否关闭App对话框
  7633. private showConfirmationDialog() {
  7634. DialogHelper.showAlertDialog({
  7635. backgroundColor: $r('app.color.btn_green'),
  7636. title: '确认关闭',
  7637. maskColor: Color.Transparent,
  7638. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  7639. borderStyle: BorderStyle.Dashed,
  7640. primaryButton: '暂不关闭',
  7641. secondaryButton: '确定',
  7642. onAction: (action) => {
  7643. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  7644. this.stopCountdown();
  7645. this.selectedMinutes = 0
  7646. } else if (action == DialogAction.TWO) {
  7647. }
  7648. }
  7649. })
  7650. }
  7651. // 停止倒计时
  7652. private stopCountdown() {
  7653. if (this.timerId !== -1) {
  7654. clearInterval(this.timerId);
  7655. this.timerId = -1;
  7656. }
  7657. }
  7658. // 超时处理
  7659. private handleTimeout() {
  7660. // 执行播放器关闭逻辑
  7661. this.selectedMinutes = 0;
  7662. ToastUtil.showToast(" 定时关闭已完成");
  7663. this.stop(); // 假设存在的播放器实例
  7664. //退出APP
  7665. const mContext = getContext(this) as common.UIAbilityContext
  7666. mContext.terminateSelf();
  7667. AvSessionController.getInstance(true).unregisterSessionListener()
  7668. }
  7669. //倒计时关闭音乐,退出App功能实现结束。
  7670. //播放列表的拖动List 重新排序
  7671. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  7672. //左滑操作 移动文件 重命名 删除等操作
  7673. @Builder
  7674. sonButton(item: VideoItem, index: number, filePath: string) {
  7675. Row() {
  7676. //加入下一首播放
  7677. Button() {
  7678. Image($r('app.media.next_to_play'))
  7679. .fillColor(Color.White)
  7680. .width(20)
  7681. }
  7682. .width(40)
  7683. .height(40)
  7684. .type(ButtonType.Circle)
  7685. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  7686. .backgroundColor(this.themeColor)
  7687. .margin(5)
  7688. .onClick(() => {
  7689. this.addToNextPlay(item);
  7690. })
  7691. Button() {
  7692. Image($r('app.media.close'))
  7693. .fillColor(Color.White)
  7694. .width(20)
  7695. }
  7696. .width(40)
  7697. .height(40)
  7698. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  7699. .type(ButtonType.Circle)
  7700. .backgroundColor(this.themeColor)
  7701. .margin(5)
  7702. .onClick(() => {
  7703. this.songList.splice(Number(index), 1)
  7704. this.sonDataSource.pushArrayData(this.songList)
  7705. })
  7706. Button() {
  7707. Image($r('app.media.share2'))
  7708. .fillColor(Color.White)
  7709. .width(20)
  7710. }
  7711. .width(40)
  7712. .height(40)
  7713. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  7714. .type(ButtonType.Circle)
  7715. .backgroundColor(this.themeColor)
  7716. .margin(5)
  7717. .onClick(() => {
  7718. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  7719. })
  7720. }
  7721. }
  7722. itemMoveSon(index: number, newIndex: number): void {
  7723. if (newIndex < 0 || newIndex >= this.songList.length) {
  7724. return;
  7725. }
  7726. let tmp = this.songList.splice(index, 1);
  7727. this.songList.splice(newIndex, 0, tmp[0]);
  7728. this.sonDataSource.pushArrayData(this.songList)
  7729. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  7730. if(this.modeType==4&&this.playlistTable){
  7731. updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
  7732. }
  7733. }
  7734. @Builder
  7735. PlayList() {
  7736. List({ scroller: this.playListScroller }) {
  7737. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  7738. ListItem() {
  7739. this.MusicItemSon(item, index)
  7740. }
  7741. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  7742. .animation({
  7743. duration: 666,
  7744. curve: 'ease-in-out' // 可选动画曲线
  7745. })
  7746. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  7747. TransitionEffect.scale({ x: 0, y: 0 })))
  7748. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  7749. //拖动List关键代码开始
  7750. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  7751. .zIndex(this.dragItem === index ? 1 : 0)
  7752. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  7753. .gesture(
  7754. GestureGroup(GestureMode.Sequence,
  7755. LongPressGesture({ repeat: true })
  7756. .onAction((event?: GestureEvent) => {
  7757. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  7758. this.scaleItem = index
  7759. })
  7760. })
  7761. .onActionEnd(() => {
  7762. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  7763. this.scaleItem = -1
  7764. })
  7765. }),
  7766. PanGesture({ fingers: 1, direction: null, distance: 0 })
  7767. .onActionStart(() => {
  7768. this.dragItem = index // 记录当前拖动项索引
  7769. this.dragRefOffset = 0 // 重置偏移基准
  7770. })
  7771. .onActionUpdate((event: GestureEvent) => {
  7772. this.offsetY = event.offsetY - this.dragRefOffset;
  7773. this.neighborItem = -1;
  7774. let indexA = this.songList.indexOf(item);
  7775. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  7776. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  7777. let value: number = 0;
  7778. if (this.offsetY < 0) {
  7779. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  7780. this.neighborItem = indexA - 1;
  7781. this.neighborScale = 1 - value / 20;
  7782. } else if (this.offsetY > 0) {
  7783. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  7784. this.neighborItem = indexA + 1;
  7785. this.neighborScale = 1 - value / 20;
  7786. }
  7787. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  7788. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  7789. this.offsetY -= this.ITEM_INTV;
  7790. this.dragRefOffset += this.ITEM_INTV;
  7791. this.itemMoveSon(indexA, indexA + 1);
  7792. });
  7793. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  7794. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  7795. this.offsetY += this.ITEM_INTV;
  7796. this.dragRefOffset -= this.ITEM_INTV;
  7797. this.itemMoveSon(indexA, indexA - 1);
  7798. });
  7799. }
  7800. })
  7801. .onActionEnd((event: GestureEvent) => {
  7802. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  7803. this.dragItem = -1
  7804. this.neighborItem = -1
  7805. })
  7806. animateTo({
  7807. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  7808. }, () => {
  7809. this.scaleItem = -1
  7810. })
  7811. })
  7812. )
  7813. .onCancel(() => {
  7814. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  7815. this.dragItem = -1
  7816. this.neighborItem = -1
  7817. })
  7818. animateTo({
  7819. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  7820. }, () => {
  7821. this.scaleItem = -1
  7822. })
  7823. })
  7824. ) //拖动List关键代码结束
  7825. .onClick(() => {
  7826. this.doPlay(item, index, true)
  7827. })
  7828. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  7829. }
  7830. .width('100%')
  7831. .height('100%')
  7832. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  7833. // .animation({ duration: 500, curve: Curve.Ease }))
  7834. .cachedCount(10)
  7835. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  7836. .gesture(PinchGesture({ fingers: 2 })
  7837. .onActionEnd((event: GestureEvent) => {
  7838. this.setSonListTwoFingers()
  7839. })
  7840. .onActionUpdate(e => {
  7841. this.scaleValue = this.pinchValue * e.scale
  7842. })
  7843. .onActionStart(e => {
  7844. }))
  7845. .padding({
  7846. bottom: 0
  7847. })
  7848. }
  7849. setSonListTwoFingers() {
  7850. this.pinchValue = this.scaleValue;
  7851. Logger.info('this.pinchValue = ' + this.pinchValue);
  7852. if (this.pinchValue >= 1) {
  7853. this.sonTwoFingerType++
  7854. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  7855. if (this.sonTwoFingerType > 3) {
  7856. this.sonTwoFingerType = 1
  7857. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  7858. }
  7859. } else {
  7860. this.sonTwoFingerType--
  7861. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  7862. if (this.sonTwoFingerType < 1) {
  7863. this.sonTwoFingerType = 1
  7864. }
  7865. }
  7866. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  7867. this.pinchValue = 1;
  7868. this.scaleValue = 1;
  7869. }
  7870. @State sonTwoFingerType:number = 3
  7871. @Builder
  7872. private MusicItemSon(item: VideoItem, index?: number) {
  7873. Button({ type: ButtonType.Normal, stateEffect: true }) {
  7874. Row() {
  7875. Stack() {
  7876. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  7877. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  7878. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  7879. .alt($r('app.media.music_red'))
  7880. .fillColor(this.themeColor)
  7881. .borderRadius('100%')
  7882. .clip(true)
  7883. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  7884. .draggable(false)// 禁止长按手势拖动
  7885. .autoResize(true) // 重采样,可减少内存占用
  7886. .margin({ left: 20 })
  7887. }
  7888. .width('15%')
  7889. Column() {
  7890. Column() {
  7891. Text(this.isShowFileName?item.fileName :item.name)
  7892. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  7893. .fontColor(this.curIndex === index ? this.themeColor :
  7894. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  7895. .maxLines(1)
  7896. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  7897. Row() {
  7898. Column(){
  7899. Text(item.md5Str?.includes('Lossless')?
  7900. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  7901. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  7902. .padding({ top: 3,right:6,left:6,bottom:3 })
  7903. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  7904. $r('app.color.text_color'))
  7905. .fontWeight(500)
  7906. .borderRadius(12)
  7907. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  7908. .backgroundColor('#FFC107')
  7909. }
  7910. .padding({ top: 8 })
  7911. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  7912. item.artist + ' ' + item?.duration)
  7913. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  7914. .padding({ top: 8 })
  7915. .maxLines(1)
  7916. .fontColor(this.curIndex === index ? this.themeColor :
  7917. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  7918. .margin({ left: this.sonTwoFingerType == 3 ? 5 : 3 })
  7919. Blank()
  7920. Text(item.size)
  7921. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  7922. .padding({ top: 8 })
  7923. .maxLines(1)
  7924. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  7925. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  7926. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  7927. .margin({ left: 10 })
  7928. }
  7929. }
  7930. .height('100%')
  7931. .width('100%')
  7932. .justifyContent(FlexAlign.Center)
  7933. .alignItems(HorizontalAlign.Start)
  7934. }
  7935. .height('100%')
  7936. .width('65%')
  7937. Column() {
  7938. ImageAnimator()
  7939. .images(this.imagesF)// 动画数组
  7940. .duration(1000)// 持续
  7941. .state(this.animationState)// 动画状态
  7942. .fillMode(FillMode.Forwards)
  7943. .width(18)
  7944. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  7945. Visibility.None)
  7946. .height(18)
  7947. .iterations(-1) // 播放次数
  7948. }
  7949. .width('20%')
  7950. }
  7951. }
  7952. .backgroundColor(Color.Transparent)
  7953. .width('100%')
  7954. .reuseId('son_item')
  7955. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  7956. .shadow(this.scaleItem === index ? {
  7957. radius: 70,
  7958. color: '#15000000',
  7959. offsetX: 0,
  7960. offsetY: 0
  7961. } :
  7962. {
  7963. radius: 0,
  7964. color: '#15000000',
  7965. offsetX: 0,
  7966. offsetY: 0
  7967. })
  7968. .animation({ curve: Curve.Sharp, duration: 300 })
  7969. }
  7970. @Builder
  7971. MusicPlayBuilder() {
  7972. Column() {
  7973. this.IjkMusicPlayerView()
  7974. }
  7975. .transition(TransitionEffect.asymmetric(
  7976. TransitionEffect.opacity(1),
  7977. TransitionEffect.OPACITY
  7978. ))
  7979. .visualEffect(deviceInfo.sdkApiVersion>=20&&this.bgController?
  7980. new hdsEffect.HdsEffectBuilder()
  7981. .shaderEffect({
  7982. effectType: hdsEffect.EffectType.UV_BACKGROUND_FLOW_LIGHT,
  7983. animation: {
  7984. duration: 10000,
  7985. iterations: -1,
  7986. autoPlay: true,
  7987. onFinish: ()=> {
  7988. console.info('Succeeded in finishing');
  7989. }
  7990. },
  7991. controller: this.bgController,
  7992. })
  7993. .buildEffect():null)
  7994. .height('100%')
  7995. .width('100%')
  7996. .onDisAppear(() => {
  7997. this.translateY = 0;
  7998. })
  7999. .translate({ y: this.translateY })
  8000. .gesture(
  8001. PanGesture(this.panOption)
  8002. .onActionUpdate((event?: GestureEvent) => {
  8003. if (event) {
  8004. // 只允许向下滑动,向上滑动时限制为0
  8005. this.translateY = Math.max(0, event.offsetY);
  8006. this.getUIContext().animateTo({
  8007. duration: 500,
  8008. curve: Curve.Sharp
  8009. }, () => {
  8010. this.scaleValueImage = Math.min(1, Math.max(0.3, 1 - event.offsetY / 260));
  8011. console.info('onecold scaleValueImage:', this.scaleValueImage)
  8012. this.scaleValueText =Math.min(1, Math.max(0.6, 1 - event.offsetY / 300));
  8013. })
  8014. }
  8015. })
  8016. .onActionEnd((event?: GestureEvent) => {
  8017. // 使用更低的阈值和滑动速度判断
  8018. const minDistance = 300; // 最小滑动距离 100vp
  8019. const minVelocity = 500; // 最小滑动速度
  8020. // 获取滑动速度(如果可用)
  8021. const velocity = event?.velocityY || 0;
  8022. // 判断是否应该关闭:距离足够 或者 速度足够快
  8023. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  8024. if (shouldClose) {
  8025. // 添加关闭动画
  8026. this.getUIContext().animateTo({
  8027. duration: 600,
  8028. curve: Curve.Friction
  8029. }, () => {
  8030. this.isShowPlay = false;
  8031. this.scaleValueImage = 1
  8032. this.scaleValueText = 1
  8033. this.translateY = 0;
  8034. })
  8035. } else {
  8036. // 回弹动画
  8037. this.getUIContext().animateTo({
  8038. duration: 600,
  8039. curve: Curve.Friction
  8040. }, () => {
  8041. this.scaleValueImage = 1
  8042. this.scaleValueText = 1
  8043. this.translateY = 0;
  8044. })
  8045. }
  8046. })
  8047. )
  8048. }
  8049. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  8050. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  8051. HeightBreakpoint.HEIGHT_LG;
  8052. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  8053. @State topBarHeight: number = 50
  8054. @State barOpacity: number = 1
  8055. @State barBottomOpacity: number = 1
  8056. private hideDone: boolean = false;
  8057. @State currentYOffset: number = 0;
  8058. @State bottomBarHeight: number = 68;
  8059. private isHiding: boolean = false;
  8060. //是否是Pura X外屏,或者小屏幕
  8061. isPuraWP() {
  8062. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  8063. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  8064. }
  8065. //是否是Pura X外屏,或者小屏幕,手机横屏
  8066. /**
  8067. * 是否是Pura X外屏,或者小屏幕,手机横屏
  8068. * @returns
  8069. */
  8070. isCoverOpacity() {
  8071. if (this.isPuraWP()) {
  8072. return true
  8073. }
  8074. if (this.isPhoneLan()) {
  8075. return true
  8076. }
  8077. if (deviceInfo.marketName.includes('Pura X')
  8078. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  8079. return true
  8080. }
  8081. return false
  8082. }
  8083. //是不是手机横屏
  8084. isPhoneLan() {
  8085. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  8086. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  8087. LogUtil.info('hicar isPhoneLan width= ' + this.windowWidth);
  8088. LogUtil.info('hicar isPhoneLan height= ' + this.windowHeight);
  8089. LogUtil.info(`twocold hicarWindow size: ${this.windowWidth}x${this.windowHeight}, this.isHiCarStatus: ${this.isHiCarStatus}`);
  8090. LogUtil.info(`twocold hicar Window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall: ${this.isHiCarSmall()}`);
  8091. if (this.isHiCarKuanBianPing()) {
  8092. return true
  8093. }
  8094. if (this.isHiCar()) {
  8095. return false
  8096. }
  8097. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8098. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  8099. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  8100. return true
  8101. }
  8102. return false
  8103. }
  8104. //是不是1920x720的hicar的屏幕分辨率
  8105. isHiCarKuanBianPing(){
  8106. if(!this.isHiCar()){
  8107. return false
  8108. }
  8109. const hiCarAspectRatios: HiCarAspectRatio[] = [
  8110. { ratio: 1920 / 720, name: "1920x720" },
  8111. ];
  8112. const currentRatio: number = this.windowWidth / this.windowHeight;
  8113. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  8114. LogUtil.info('twocold isHiCarKuanBianPing currentRatio = ' + currentRatio)
  8115. for (const hiCarRatio of hiCarAspectRatios) {
  8116. LogUtil.info('twocold isHiCarKuanBianPing hiCarRatio= ' + hiCarRatio.ratio)
  8117. LogUtil.info('twocold isHiCarKuanBianPing Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  8118. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  8119. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  8120. //宽扁平的尺寸设置列表展示
  8121. this.twoFingerType ==3
  8122. this.isGridMusic = false
  8123. return true;
  8124. }
  8125. }
  8126. return false;
  8127. }
  8128. //是不是hicar的屏幕分辨率
  8129. isHiCarSmall() {
  8130. if(!this.isHiCar()){
  8131. return false
  8132. }
  8133. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  8134. {
  8135. this.columns = 6
  8136. return false
  8137. }
  8138. const hiCarAspectRatios: HiCarAspectRatio[] = [
  8139. { ratio: 800 / 480, name: "800x480" },
  8140. { ratio: 1280 / 720, name: "1280x720" },
  8141. { ratio: 1920 / 1080, name: "1920x1080" },
  8142. ];
  8143. const currentRatio: number = this.windowWidth / this.windowHeight;
  8144. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  8145. LogUtil.info('twocold isHiCarSmall currentRatio = ' + currentRatio)
  8146. for (const hiCarRatio of hiCarAspectRatios) {
  8147. LogUtil.info('twocold isHiCarSmall hiCarRatio= ' + hiCarRatio.ratio)
  8148. LogUtil.info('twocold isHiCarSmall Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  8149. LogUtil.info('twocold isHiCarSmall isHiCarStatus= ' + this.isHiCarStatus);
  8150. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  8151. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  8152. //宽扁平的尺寸设置列表展示
  8153. return true;
  8154. }
  8155. }
  8156. return false;
  8157. }
  8158. isHiCar() {
  8159. return this.isHiCarStatus&&this.curDisplayIsHiCar;
  8160. }
  8161. //是不是正常的手机竖屏
  8162. isPhonePortrait() {
  8163. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  8164. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  8165. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  8166. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8167. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  8168. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  8169. return true
  8170. }
  8171. return false
  8172. }
  8173. @State showSpeedDialog: boolean = false
  8174. @State longPressSpeed: number = 3 //长按默认倍数
  8175. @Builder
  8176. SpeedDialog() {
  8177. Stack() {
  8178. Column() {
  8179. Text('已切换至' + this.longPressSpeed + '倍速播放')
  8180. .fontColor(Color.White)
  8181. .visibility(Visibility.Hidden)
  8182. }
  8183. .backgroundColor(Color.Black)
  8184. .borderRadius(20)
  8185. .padding({
  8186. top: 10,
  8187. right: 20,
  8188. left: 15,
  8189. bottom: 20
  8190. })
  8191. .opacity(0.6)
  8192. Text('已切换至' + this.longPressSpeed + '倍速播放')
  8193. .fontColor(Color.White)
  8194. }
  8195. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  8196. .zIndex(5)
  8197. .margin({ top: 80 })
  8198. }
  8199. @Builder
  8200. IjkMusicPlayerView() {
  8201. Stack() {
  8202. if(canIUse("SystemCapability.UIDesign.HDSComponent.Core")
  8203. &&deviceInfo.sdkApiVersion>=20&&this.sceneBgController){
  8204. HdsVisualComponent()
  8205. .scene(HdsSceneType.DUAL_EDGE_FLOW_LIGHT_WITH_BACKGROUND_MASK, this.sceneBgController, () => {
  8206. console.info('Succeeded in finishing');
  8207. })
  8208. .width('100%')
  8209. .height('100%')
  8210. .visibility(this.isShowBgLiuGUANG?Visibility.Visible:Visibility.None)
  8211. }
  8212. Column() {
  8213. Column() {
  8214. //播放标题
  8215. Column() {
  8216. this.PlayTitle()
  8217. }
  8218. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  8219. .width('100%')
  8220. .margin({ top: 0 })
  8221. .height(PlayConstants.HEIGHT)
  8222. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  8223. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  8224. if (this.showSpeedDialog) {
  8225. this.SpeedDialog()
  8226. }
  8227. Stack() {
  8228. //手势拖动快进
  8229. Column()
  8230. .width(CommonConstants.FULL_PERCENT)
  8231. .height('100%')
  8232. .gesture(
  8233. GestureGroup(GestureMode.Parallel,
  8234. // 长按屏幕倍数播放
  8235. LongPressGesture({ repeat: true })
  8236. .onAction(() => {
  8237. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8238. this.showSpeedDialog = true;
  8239. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  8240. }
  8241. })
  8242. .onActionEnd(() => {
  8243. this.showSpeedDialog = false;
  8244. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  8245. }),
  8246. //双击屏幕暂停或者播放
  8247. TapGesture({ count: 2 })
  8248. .onAction((event: GestureEvent) => {
  8249. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8250. ToastUtil.showToast('已暂停')
  8251. }
  8252. console.info('onecold playOrPause 6693')
  8253. this.playOrPause()
  8254. })
  8255. )
  8256. )
  8257. }
  8258. .height('65%')
  8259. Swiper() {
  8260. this.CoverInfo()
  8261. this.PlayerLyrics()
  8262. }
  8263. .onChange((index: number) => {
  8264. this.currentSwiperIndex = index
  8265. })
  8266. .indicator(false)
  8267. .displayCount(new BreakpointType({
  8268. sm: 1,
  8269. md: 2,
  8270. lg: 2,
  8271. xl: 2,
  8272. xxl: 2
  8273. }).getValue(this.currentBreakpoint))
  8274. .clip(false)
  8275. .loop(false)
  8276. .autoPlay(false)
  8277. // .interval(8000)
  8278. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  8279. .height('100%')
  8280. .hitTestBehavior(HitTestMode.Transparent)
  8281. Image($r('app.media.icon_replay'))
  8282. .objectFit(ImageFit.Auto)
  8283. .width('120px')
  8284. .height('120px')
  8285. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  8286. .border({ width: 0 })
  8287. .visibility(Visibility.None)
  8288. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  8289. .onClick(() => {
  8290. console.info('onecold startPlayOrResumePlay 6744')
  8291. this.startPlayOrResumePlay();
  8292. })
  8293. }
  8294. .width(CommonConstants.FULL_PERCENT)
  8295. .height(CommonConstants.FULL_PERCENT)
  8296. .justifyContent(FlexAlign.End)
  8297. }
  8298. .justifyContent(FlexAlign.End)
  8299. .margin({ bottom: 8 })
  8300. }
  8301. .backgroundImage(!this.isMusicBGCover||StrUtil.isEmpty(this.cover)?null: this.cover)
  8302. .backgroundImageSize(this.isPuraWP()||!this.isMusicBGCover ? { width: '100%' } : { height: '150%', width: '100%' })
  8303. .animation({
  8304. duration: 666,
  8305. curve: 'ease-in-out' // 可选动画曲线
  8306. })
  8307. .backgroundBlurStyle((this.isPuraWP() && this.currentSwiperIndex === 0) ||!this.isMusicBGCover
  8308. ? BlurStyle.NONE :
  8309. BlurStyle.BACKGROUND_ULTRA_THICK)
  8310. .hitTestBehavior(HitTestMode.Transparent)
  8311. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  8312. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  8313. .onClick(() => {
  8314. if(this.isHiCar())
  8315. return
  8316. if(this.is_auto_hide_progress){
  8317. this.is_auto_hide_progress = false
  8318. }
  8319. this.startAutoHide()
  8320. })
  8321. }
  8322. @State progressValue: number = 0;
  8323. @State currentTime: string = "00:00";
  8324. @State totalTime: string = "00:00";
  8325. @State loadingVisible: Visibility = Visibility.None;
  8326. @State replayVisible: Visibility = Visibility.None;
  8327. @State slideEnable: boolean = false;
  8328. @State aspRatio: number = 0.5;
  8329. @State mContext: object | undefined = undefined;
  8330. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  8331. @State mFirst: boolean = true;
  8332. @State mDestroyPage: boolean = false;
  8333. @State playSpeed: number = 1;
  8334. @State oldSeconds: number = 0;
  8335. @State isSeekTo: boolean = false;
  8336. @State isCurrentTime: boolean = false;
  8337. @State videoWidth: string = '100%';
  8338. @State videoHeight: string = '100%';
  8339. @State initAspectRatio: number = 1;
  8340. @State videoAspectRatio: number = this.initAspectRatio;
  8341. @State videoUrl: string = '';
  8342. private last: number = 0;
  8343. @State videoParentAspectRatio: number = this.initAspectRatio;
  8344. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  8345. @State CONTROL_PlayStatus: number = PlayStatus.INIT;
  8346. @State PROGRESS_MAX_VALUE: number = 100;
  8347. @State updateProgressTimer: number = 0;
  8348. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  8349. @State name: string = '';
  8350. // @State loop: boolean = false;
  8351. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  8352. @State multiple: string = '1.0X';
  8353. xcomponentController: XComponentController = new XComponentController()
  8354. private panOptionBright: PanGestureOptions =
  8355. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  8356. private panOptionVolume: PanGestureOptions =
  8357. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  8358. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  8359. //手势的音量控制和亮度控制
  8360. private positionX: number = PlayConstants.POSITION_X;
  8361. private positionY: number = PlayConstants.POSITION_Y;
  8362. private windowClass: window.Window = globalThis.windowClass
  8363. @State volume: number = 0.5;
  8364. @State volumeSmall: boolean = false
  8365. @State autoParseMusicName: boolean = true
  8366. @State isShowFileName: boolean = false
  8367. @State isLongNameRoLL: boolean = true//长歌名滚动
  8368. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  8369. @State bright: number = PlayConstants.BRIGHT;
  8370. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  8371. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  8372. @State screenWidth: number = 0
  8373. @State screenHeight: number = 0
  8374. @State statusBarHeight: number = 0
  8375. @State isYesFull: boolean = false
  8376. private seekValue: number = 0
  8377. @State isVideoLock: boolean = false; // Whether the video playback is locked
  8378. eventHub = getContext().eventHub;
  8379. //投播组件
  8380. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  8381. private castController: avSession.AVCastController | undefined = undefined;
  8382. @State isCastPlaying: boolean = false;
  8383. @State currentTime2: number = 0;
  8384. @State currentStringTime: string = '00:00';
  8385. @State duration: number = 0;
  8386. @State isReady: boolean = false;
  8387. @State durationTime: number = 0;
  8388. @State durationStringTime: string = '00:00';
  8389. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  8390. // @State isPlaying: boolean = false;
  8391. private castSeek: boolean = false;
  8392. private castItem: avSession.AVQueueItem | undefined = undefined;
  8393. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  8394. @State rotateAngle2: number = -9
  8395. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  8396. @State cover: string | undefined = '';
  8397. @State artist: string | undefined = ''
  8398. // 1.初始化controller
  8399. private lyricController: LyricController = new LyricController()
  8400. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  8401. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  8402. private parser = new LyricParser()
  8403. @State randomColor: string = 'rgb(0,0,0)'
  8404. @State randomShakenX: number = 0
  8405. @State randomShakenY: number = 0
  8406. @State lyricTextSize: number = 24
  8407. @State lyricContent: string = ''
  8408. @State isDebug: boolean = false
  8409. @State isHightLightCenter: boolean = true
  8410. /**
  8411. * 初始化歌词加载与展示逻辑
  8412. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  8413. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  8414. * @param isApi2 是否使用API2获取歌词(可选)
  8415. *
  8416. * 主要流程:
  8417. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  8418. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  8419. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  8420. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  8421. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  8422. * 6. 解析失败或读取失败时,清空歌词显示。
  8423. *
  8424. * 注意事项:
  8425. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  8426. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  8427. * - 歌词内容解析后通过lyricController驱动UI渲染。
  8428. */
  8429. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  8430. if (StrUtil.isEmpty(lyricPath)) {
  8431. return
  8432. }
  8433. this.initPipLyricSetting()
  8434. this.lyricControllerSingle
  8435. .setTextSize(15)
  8436. .setCacheSize(4)
  8437. .setTextColor("#FFFFFF")
  8438. .setHighlightColor("#FFFFFF")
  8439. .setHighlightScale(1.2)
  8440. .setEmptyHint("")
  8441. .setAlignMode('center')
  8442. .setAnimationDuration(500)
  8443. .setSingleLine(true)
  8444. this.lyricContent = ''
  8445. this.lyricController
  8446. .setTextSize(this.currentLyricSize)
  8447. .setCacheSize(4)
  8448. .setTextColor("#DDDDDD")
  8449. .setHighlightColor("#FFFFFF")
  8450. .setEmptyHint("")
  8451. .setAnimationDuration(1000)
  8452. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  8453. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  8454. this.setBlurDegree(this.blurDegree, false)
  8455. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  8456. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  8457. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  8458. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  8459. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  8460. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  8461. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  8462. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  8463. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  8464. this.lyricController.setTextWeight(this.lyricTextWeight)
  8465. this.showSingleLyric = false
  8466. this.timeOffset = 0
  8467. this.lyricController.setLyric(null)
  8468. this.lyricControllerSingle.setLyric(null)
  8469. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  8470. console.log("onecold lyricPath =" + lyricPath)
  8471. let neiqianLrc = ''
  8472. let lyContent = this.currentSong?.lyricContent
  8473. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  8474. neiqianLrc = lyContent
  8475. }
  8476. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast&&!isLocal&&!isLocal) {
  8477. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  8478. //赋值给this.lyricContent,播控中心才可以显示歌词
  8479. this.lyricContent = neiqianLrc
  8480. // 将文件内容按行分割成字符串数组
  8481. let lines = neiqianLrc.split('\n').map(line => line.trim());
  8482. // 3.解析歌词
  8483. let lyric = this.parser.parse(lines);
  8484. // 4.设置歌词
  8485. this.lyricController.setLyric(lyric);
  8486. this.lyricControllerXF.setLyric(lyric)
  8487. this.lyricControllerSingle.setLyric(lyric)
  8488. return
  8489. }
  8490. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  8491. && !Utility.isVideoByExtension(this.videoUrl))) {
  8492. if (this.currentSong !== undefined) {
  8493. // ToastUtil.showShort('正在为你搜索在线歌词!')
  8494. //判断是不是赞助会员,是会员的话才开启歌词功能
  8495. // if (!this.isDebug) {
  8496. // if (!Utility.isNoble()) {
  8497. // LogUtil.debug("onecold 不是赞助会员")
  8498. // return
  8499. // }
  8500. // if(!Utility.isPassInstallTime(33)){
  8501. // LogUtil.debug("onecold not pass time")
  8502. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  8503. // return
  8504. // }
  8505. // }
  8506. let artist = this.currentSong?.artist
  8507. if (artist === undefined) {
  8508. artist = ''
  8509. }
  8510. if (isApi2 === undefined) {
  8511. isApi2 = false
  8512. }
  8513. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  8514. // LogUtil.debug("onecold res =" + res)
  8515. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  8516. if (StrUtil.isNotEmpty(res)) {
  8517. this.lyricContent = res
  8518. let lines = res.split('\n').map(line => line.trim());
  8519. // 3.解析歌词
  8520. let lyric = this.parser.parse(lines);
  8521. // 4.设置歌词
  8522. this.lyricController.setLyric(lyric);
  8523. this.lyricControllerXF.setLyric(lyric)
  8524. this.lyricControllerSingle.setLyric(lyric)
  8525. this.showSingleLyric = true
  8526. // 4.保存歌词文件lyric到本地
  8527. //2025年8月28日歌词不再加密下载
  8528. this.saveDataToFile(res, lyricPath, false)
  8529. } else {
  8530. this.lyricController.setLyric(null)
  8531. this.lyricControllerXF.setLyric(null)
  8532. this.lyricControllerSingle.setLyric(null)
  8533. if (isOnLineAndToast) {
  8534. ToastUtil.showShort('未获取到歌词!')
  8535. }
  8536. }
  8537. } else {
  8538. this.lyricController.setLyric(null)
  8539. this.lyricControllerXF.setLyric(null)
  8540. this.lyricControllerSingle.setLyric(null)
  8541. if (isOnLineAndToast) {
  8542. ToastUtil.showShort('未获取到歌词!')
  8543. }
  8544. }
  8545. })
  8546. } else {
  8547. this.lyricController.setLyric(null)
  8548. this.lyricControllerXF.setLyric(null)
  8549. this.lyricControllerSingle.setLyric(null)
  8550. if (isOnLineAndToast) {
  8551. ToastUtil.showShort('未获取到歌词!')
  8552. }
  8553. }
  8554. return
  8555. }
  8556. try {
  8557. let isJiaMi = false;
  8558. let realLyricPath = lyricPath
  8559. if (FileUtil.accessSync(jiaMilyricPath)) {
  8560. isJiaMi = true
  8561. realLyricPath = jiaMilyricPath
  8562. console.info("onecold 找到加密本地歌词 ");
  8563. } else {
  8564. isJiaMi = false
  8565. realLyricPath = lyricPath
  8566. console.info("onecold 找到本地歌词 ");
  8567. }
  8568. // 3.读取文件内容并指定编码为 UTF-8
  8569. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  8570. const stat = await fileIo.stat(file.fd);
  8571. const arrayBuffer = new ArrayBuffer(stat.size);
  8572. fs.read(file.fd, arrayBuffer)
  8573. .then((readLen: number) => {
  8574. console.info("read file data succeed");
  8575. // let buf = buffer.from(arrayBuffer, 0, readLen);
  8576. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  8577. // 检查 buf 是否为空
  8578. if (buf.length === 0) {
  8579. throw new Error("Buffer is empty after reading the file");
  8580. }
  8581. try {
  8582. // 检测文件编码
  8583. // let detectedEncoding = chardet.detect(buf);
  8584. // console.info("onecoldT Detected encoding: " + detectedEncoding);
  8585. let detectedEncoding = this.detect(arrayBuffer)
  8586. console.info("onecoldT Detected encoding: " + detectedEncoding);
  8587. // 使用检测到的编码解码,解决中文乱码问题
  8588. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  8589. console.info("onecoldT Detected textDecoder: " + textDecoder);
  8590. let fileContent = textDecoder.decode(buf);
  8591. console.info(`onecoldT The content of file1: ${fileContent}`);
  8592. //解密
  8593. if (isJiaMi) {
  8594. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  8595. }
  8596. console.info(`onecold The content of file2: ${fileContent}`);
  8597. this.lyricContent = fileContent
  8598. if(isLocal){//编辑标签选择本地歌词需要赋值给this.lyricConStr
  8599. this.lyricConStr = fileContent
  8600. }
  8601. // 将文件内容按行分割成字符串数组
  8602. let lines = fileContent.split('\n').map(line => line.trim());
  8603. console.info(`onecold The content of file: ${fileContent}`);
  8604. // 3.解析歌词
  8605. let lyric = this.parser.parse(lines);
  8606. // 4.设置歌词
  8607. this.lyricController.setLyric(lyric);
  8608. this.lyricControllerXF.setLyric(lyric)
  8609. this.lyricControllerSingle.setLyric(lyric)
  8610. this.showSingleLyric = true
  8611. console.info(`The content of file: ${fileContent}`);
  8612. } catch (chardetError) {
  8613. console.error("chardet.detect failed with error: " + chardetError.message);
  8614. this.lyricController.setLyric(null);
  8615. this.lyricControllerXF.setLyric(null)
  8616. this.lyricControllerSingle.setLyric(null)
  8617. }
  8618. })
  8619. .catch((err: BusinessError) => {
  8620. this.lyricController.setLyric(null)
  8621. this.lyricControllerXF.setLyric(null)
  8622. this.lyricControllerSingle.setLyric(null)
  8623. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  8624. })
  8625. .catch((err: Error) => {
  8626. this.lyricController.setLyric(null)
  8627. this.lyricControllerXF.setLyric(null)
  8628. this.lyricControllerSingle.setLyric(null)
  8629. console.error("read file 2 data failed with error message: " + err.message);
  8630. })
  8631. .finally(() => {
  8632. fs.closeSync(file);
  8633. });
  8634. } catch (error) {
  8635. this.lyricController.setLyric(null)
  8636. this.lyricControllerSingle.setLyric(null)
  8637. this.lyricControllerXF.setLyric(null)
  8638. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  8639. }
  8640. }
  8641. detect(data: ArrayBuffer): string {
  8642. //创建检测对象
  8643. let detector: UniversalDetector = new UniversalDetector();
  8644. // 传入检测数据并实时判断编码格式
  8645. detector.handleData(data, 0, data.byteLength);
  8646. // 标记检测数据 读取结束
  8647. detector.dataEnd();
  8648. // 获取检测结果
  8649. let detected: string = detector.getDetectedCharset();
  8650. // 释放资源
  8651. detector.reset();
  8652. return detected;
  8653. }
  8654. //初始化悬浮歌词的自定义设置
  8655. initPipLyricSetting() {
  8656. this.lyricControllerXF
  8657. .setTextSize(this.currentLyricSize)
  8658. .setCacheSize(4)
  8659. .setTextColor("#DDDDDD")
  8660. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  8661. .setEmptyHint("")
  8662. .setAnimationDuration(1000)
  8663. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  8664. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  8665. this.setBlurDegree(this.blurDegreePip, true)
  8666. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  8667. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  8668. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  8669. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  8670. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  8671. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  8672. this.lyricControllerXF.setHightLightCenter(true)
  8673. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  8674. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  8675. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  8676. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  8677. if (this.pipBgIndex === 0) {
  8678. if (this.cover) {
  8679. this.pipBg = this.cover
  8680. } else {
  8681. this.pipBg = this.imageColor
  8682. }
  8683. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  8684. }
  8685. }
  8686. //根据item返回歌词内容
  8687. async getLyricContent(item: VideoItem): Promise<string> {
  8688. let neiqianLrc = ''
  8689. let lyContent = item?.lyricContent
  8690. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  8691. neiqianLrc = lyContent
  8692. return neiqianLrc
  8693. }
  8694. try {
  8695. //取数据库里面的歌词lyContent
  8696. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  8697. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  8698. console.log("onecold Lyrics:", lyricContent);
  8699. neiqianLrc = lyricContent
  8700. return neiqianLrc
  8701. }
  8702. } catch (error) {
  8703. console.error("Error fetching lyrics:", error);
  8704. }
  8705. try {
  8706. let filePath = item.filePath;
  8707. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  8708. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  8709. let isJiaMi = false;
  8710. let realLyricPath = lyricPath;
  8711. if (FileUtil.accessSync(jiaMilyricPath)) {
  8712. isJiaMi = true;
  8713. realLyricPath = jiaMilyricPath;
  8714. console.info("onecold 找到加密本地歌词");
  8715. } else {
  8716. console.info("onecold 找到本地歌词");
  8717. }
  8718. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  8719. const stat = await fileIo.stat(file.fd);
  8720. const arrayBuffer = new ArrayBuffer(stat.size);
  8721. const readLen = await fs.read(file.fd, arrayBuffer);
  8722. console.info("read file data succeed");
  8723. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  8724. if (buf.length === 0) {
  8725. throw new Error("Buffer is empty after reading the file");
  8726. }
  8727. // let detectedEncoding = chardet.detect(buf);
  8728. let detectedEncoding = this.detect(arrayBuffer)
  8729. console.info("Detected encoding: " + detectedEncoding);
  8730. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  8731. let fileContent = textDecoder.decode(buf);
  8732. console.info(`onecold The content of file1: ${fileContent}`);
  8733. if (isJiaMi) {
  8734. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  8735. }
  8736. console.info(`onecold The content of file2: ${fileContent}`);
  8737. fs.closeSync(file);
  8738. return fileContent;
  8739. } catch (error) {
  8740. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  8741. return '';
  8742. }
  8743. }
  8744. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  8745. if (StrUtil.isEmpty(filePath)) {
  8746. return
  8747. }
  8748. try {
  8749. //将content进行加密
  8750. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  8751. let lyricContent = ''
  8752. if (isJiaMi) {
  8753. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  8754. } else {
  8755. lyricContent = content
  8756. }
  8757. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  8758. // 清空文件内容
  8759. await fileIo.truncate(file.fd, 0);
  8760. await fileIo.write(file.fd, lyricContent);
  8761. await fileIo.close(file);
  8762. console.log('onecold lyric file Data saved successfully.');
  8763. } catch (error) {
  8764. console.error('onecold lyric file Failed to save data:', error);
  8765. }
  8766. }
  8767. // 定义开始旋转的方法
  8768. // 定时器用于一百毫秒执行一次旋转角度
  8769. @State timer: number = 0
  8770. @State rotateAngle: number = 0
  8771. //封面旋转动画
  8772. animationRoFun() {
  8773. if (this.isPlaying && !this.isCoverRectangle) {
  8774. this.timer = setInterval(() => {
  8775. this.rotateAngle += 1
  8776. }, 100)
  8777. this.startRotation()
  8778. } else {
  8779. clearInterval(this.timer)
  8780. this.stopRotation()
  8781. }
  8782. }
  8783. // 定义开始旋转的方法
  8784. startRotation() {
  8785. if (this.isPlaying) {
  8786. animateTo({
  8787. duration: 777,
  8788. iterations: 1,
  8789. curve: Curve.Linear
  8790. }, () => {
  8791. this.rotateAngle2 = -9
  8792. })
  8793. }
  8794. }
  8795. // 回调,暂停和播放按钮回调,下一首和上一首
  8796. playChange() {
  8797. // if(this.isCoverRectangle){
  8798. // return
  8799. // }
  8800. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8801. this.setIsPlaying(true)
  8802. this.animationState = AnimationStatus.Running
  8803. } else {
  8804. this.setIsPlaying(false)
  8805. this.animationState = AnimationStatus.Paused
  8806. }
  8807. AppStorage.setOrCreate('animationState', this.animationState);
  8808. }
  8809. // 定义停止旋转的方法
  8810. stopRotation() {
  8811. if (this.isCoverRectangle) {
  8812. this.rotateAngle = 0
  8813. } else {
  8814. //唱针以左上角为点选择逆时针40度
  8815. animateTo({
  8816. duration: 1000,
  8817. curve: Curve.Linear,
  8818. iterations: 1,
  8819. }, () => {
  8820. this.rotateAngle2 = -45;
  8821. });
  8822. }
  8823. }
  8824. @Builder
  8825. private LyricsTopItem() {
  8826. Row() {
  8827. Stack() {
  8828. Image(this.cover)
  8829. .height(58)
  8830. .width(58)
  8831. .alt($r('app.media.alt'))
  8832. .borderRadius(8)
  8833. .clickEffect({ level: ClickEffectLevel.HEAVY })
  8834. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  8835. .shadow({
  8836. radius: 22,
  8837. type: ShadowType.BLUR,
  8838. color: 'on_primary'
  8839. })
  8840. }
  8841. .width('18%')
  8842. Column() {
  8843. Column() {
  8844. Text(this.name)
  8845. .fontSize(16)
  8846. .maxLines(1)
  8847. .fontWeight(FontWeight.Bolder)
  8848. .fontColor(this.currentLyricColor)
  8849. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  8850. Row() {
  8851. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  8852. .fontSize(13)
  8853. .fontWeight(FontWeight.Bold)
  8854. .padding({ top: 8 })
  8855. .fontColor(this.currentLyricColor)
  8856. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  8857. Blank()
  8858. }
  8859. }
  8860. .height('100%')
  8861. .width('100%')
  8862. .justifyContent(FlexAlign.Center)
  8863. .alignItems(HorizontalAlign.Start)
  8864. }
  8865. .height('100%')
  8866. .width('65%')
  8867. Column() {
  8868. Image($r('app.media.lyric'))
  8869. .width(28)
  8870. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8871. .margin({ right: 30 })
  8872. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8873. .onClick(() => {
  8874. this.isLyricSetting = !this.isLyricSetting;
  8875. })
  8876. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  8877. height: '95%',
  8878. dragBar: true,
  8879. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8880. showClose: true,
  8881. blurStyle: BlurStyle.Thin,
  8882. backgroundColor: Color.Transparent,
  8883. // title: { title: $r('app.string.lyric_setting') }
  8884. })
  8885. }
  8886. .width('18%')
  8887. }
  8888. .width('82%')
  8889. .height(58)
  8890. .justifyContent(FlexAlign.SpaceBetween)
  8891. }
  8892. //歌词显示
  8893. @Builder
  8894. PlayerLyrics() {
  8895. Column() {
  8896. Column() {
  8897. this.LyricsTopItem()
  8898. }
  8899. .height(this.isPuraWP() ? 15 : 58)
  8900. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  8901. Visibility.None : Visibility.Visible)
  8902. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  8903. .width("100%")
  8904. Column() {
  8905. LyricView2({
  8906. controller: this.lyricController,
  8907. enableSeek: true,
  8908. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  8909. seekLineColor: "#80ffffff", // 滑动定位线颜色
  8910. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  8911. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  8912. if (!this.isPlaying) {
  8913. console.info('onecold startPlayOrResumePlay 7527')
  8914. this.startPlayOrResumePlay()
  8915. }
  8916. else {
  8917. this.isSeekTo = true;
  8918. this.mDestroyPage = false;
  8919. this.showLoadIng();
  8920. this.seekTo(position + "");
  8921. this.isSeekTo = false;
  8922. }
  8923. return true
  8924. }
  8925. })
  8926. .width("100%")
  8927. .layoutWeight(1)
  8928. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  8929. if (this.isPhoneLan()) {
  8930. Column() {
  8931. this.playProgressView()
  8932. // this.playCenterView()
  8933. }
  8934. .margin({ bottom: 30, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  8935. }
  8936. }
  8937. .position({
  8938. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  8939. (this.isPuraWP() ? 58 : 99)
  8940. })
  8941. .justifyContent(FlexAlign.Center)
  8942. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  8943. }
  8944. }
  8945. @Builder
  8946. SingleLyricView() {
  8947. Column() {
  8948. Column() {
  8949. LyricView2({
  8950. controller: this.lyricControllerSingle,
  8951. enableSeek: false,
  8952. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  8953. seekLineColor: "#80ffffff", // 滑动定位线颜色
  8954. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  8955. })
  8956. }
  8957. .height(66)
  8958. .margin({ bottom: 20 })
  8959. }
  8960. }
  8961. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  8962. @Builder
  8963. BottomControl() {
  8964. Column() {
  8965. this.TopPlayProgressView()
  8966. //播放 暂停,下一首,上一首
  8967. this.playCenterView()
  8968. //播放进度条
  8969. this.BottomView()
  8970. }
  8971. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  8972. }
  8973. //播放控制上一首 下一首 暂停和播放
  8974. @Builder
  8975. playCenterView(){
  8976. Row() {
  8977. Button({type:ButtonType.Circle,stateEffect:true}){
  8978. //更多功能
  8979. Image($r('app.media.menu'))
  8980. .width(24)
  8981. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8982. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  8983. height: '99%',
  8984. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  8985. dragBar: true,
  8986. showClose: true,
  8987. blurStyle: BlurStyle.Thin,
  8988. backgroundColor: Color.Transparent,
  8989. })
  8990. }
  8991. .height(45)
  8992. .width(45)
  8993. .margin({ left: 5 })
  8994. .backgroundColor(Color.Transparent)
  8995. .onClick(() => {
  8996. this.isShowMoreView = !this.isShowMoreView;
  8997. })
  8998. Button({type:ButtonType.Circle,stateEffect:true}){
  8999. Image($r('app.media.ic_previous'))
  9000. .width(33)
  9001. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9002. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9003. }
  9004. .height(45)
  9005. .width(45)
  9006. .onClick(async () => {
  9007. await this.playPrevious()
  9008. })
  9009. .backgroundColor(Color.Transparent)
  9010. Button({type:ButtonType.Circle,stateEffect:true}){
  9011. Column() {
  9012. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  9013. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  9014. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  9015. .width(this.isPhoneLan()?45:55)
  9016. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9017. .fillColor(Color.White)
  9018. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9019. }
  9020. }
  9021. .onClick(async () => {
  9022. this.playOrPause()
  9023. })
  9024. .backgroundColor(Color.Transparent)
  9025. .layoutWeight(1)
  9026. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9027. Image($r('app.media.ic_next'))
  9028. .width(33)
  9029. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9030. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9031. }
  9032. .height(45)
  9033. .width(45)
  9034. .backgroundColor(Color.Transparent)
  9035. .onClick(async () => {
  9036. await this.playNext();
  9037. })
  9038. this.fullButton()
  9039. }
  9040. .width('95%')
  9041. .margin({ bottom:this.isCoverOpacity()?0:15 })
  9042. .justifyContent(FlexAlign.SpaceEvenly)
  9043. }
  9044. @Builder
  9045. TopPlayProgressView(){
  9046. Row() {
  9047. Column(){
  9048. Row(){
  9049. Stack(){
  9050. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  9051. .fontColor([Color.White])
  9052. .fontSize(21)
  9053. .effectStrategy(1)
  9054. Text(this.fastForwardSeconds)
  9055. .fontColor(Color.White)
  9056. .fontSize(10)
  9057. .fontWeight(FontWeight.Bold)
  9058. }
  9059. .margin({left:12,bottom:6})
  9060. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  9061. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9062. .onClick(()=>{
  9063. this.backForward()
  9064. })
  9065. Slider({
  9066. value: this.progressValue,
  9067. min: 0,
  9068. max: this.PROGRESS_MAX_VALUE,
  9069. step: 1,
  9070. style: SliderStyle.InSet
  9071. })
  9072. .height(20)
  9073. .blockColor('rgba(255,255,255,1)')
  9074. .trackColor('rgba(255,255,255,0.3)')
  9075. .selectedColor(Color.White)
  9076. .trackThickness(4)
  9077. .layoutWeight(1)
  9078. .showSteps(false)
  9079. .showTips(true)
  9080. .alignSelf(ItemAlign.Center)
  9081. .enabled(this.slideEnable)
  9082. .onChange((value: number, mode: SliderChangeMode) => {
  9083. // if (mode == 2) {
  9084. this.isSeekTo = true;
  9085. this.mDestroyPage = false;
  9086. this.showLoadIng();
  9087. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  9088. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  9089. this.seekTo(seekValue + "");
  9090. // this.setProgress()
  9091. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  9092. this.isSeekTo = false;
  9093. // }
  9094. })
  9095. Stack(){
  9096. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  9097. .fontColor([Color.White])
  9098. .fontSize(21)
  9099. .effectStrategy(1)
  9100. Text(this.fastForwardSeconds)
  9101. .fontColor(Color.White)
  9102. .fontSize(10)
  9103. .fontWeight(FontWeight.Bold)
  9104. }
  9105. .margin({right:10,bottom:6})
  9106. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  9107. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9108. .onClick(()=>{
  9109. this.fastForward()
  9110. })
  9111. }
  9112. .padding({ right: 7,left:22 })
  9113. Row(){
  9114. Text(this.currentTime)
  9115. .fontSize(10)
  9116. .fontColor(Color.White)
  9117. Blank()
  9118. .layoutWeight(1)
  9119. Text(this.totalTime)
  9120. .fontSize(10)
  9121. .fontColor(Color.White)
  9122. }
  9123. .justifyContent(FlexAlign.Start)
  9124. .padding({ right: 18,left:36 })
  9125. }
  9126. }
  9127. //x5的竖屏模式需要99%
  9128. .width(this.isLandscape?'80%':'93%')
  9129. .justifyContent(FlexAlign.Center)
  9130. .margin({bottom:3})
  9131. .animation({
  9132. duration: 666,
  9133. curve: 'ease-in-out' // 可选动画曲线
  9134. })
  9135. }
  9136. //播放进度条
  9137. @Builder
  9138. BottomView(){
  9139. Row() {
  9140. Button({type:ButtonType.Circle,stateEffect:true}){
  9141. Column() {
  9142. if (this.playType === 0) {
  9143. Image($r('app.media.loop'))
  9144. .width(27)
  9145. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9146. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9147. } else if (this.playType === 1) {
  9148. Image($r('app.media.single'))
  9149. .width(27)
  9150. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9151. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9152. } else if (this.playType === 2) {
  9153. Image($r('app.media.normal_play'))
  9154. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9155. .width(27)
  9156. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9157. } else if (this.playType === 3) {
  9158. Image($r('app.media.random'))
  9159. .width(27)
  9160. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9161. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9162. }
  9163. }
  9164. }
  9165. .layoutWeight(1)
  9166. .margin({ left: 5 })
  9167. .height(45)
  9168. .width(45)
  9169. .backgroundColor(Color.Transparent)
  9170. .onClick(async () => {
  9171. this.setLoopMode()
  9172. })
  9173. if(this.currentSong){
  9174. Button({type:ButtonType.Circle,stateEffect:true}){
  9175. Column() {
  9176. Image($r('app.media.rename2'))
  9177. .width(21)
  9178. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9179. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9180. }
  9181. }
  9182. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  9183. height: '99%',
  9184. dragBar: true,
  9185. showClose: true,
  9186. preferType: SheetType.BOTTOM,
  9187. title: { title: '编辑标签' }
  9188. })
  9189. .height(45)
  9190. .width(45)
  9191. .layoutWeight(1)
  9192. .backgroundColor(Color.Transparent)
  9193. .onClick(async () => {
  9194. this.initEditFields(this.currentSong)
  9195. this.tempLyricContent = this.lyricContent
  9196. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  9197. this.lyricConStr = this.tempLyricContent
  9198. }
  9199. this.isShowEdit = !this.isShowEdit;
  9200. })
  9201. }
  9202. Button({type:ButtonType.Circle,stateEffect:true}){
  9203. Column() {
  9204. Image($r('app.media.lyric'))
  9205. .width(26)
  9206. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9207. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9208. }
  9209. }
  9210. .height(45)
  9211. .width(45)
  9212. .layoutWeight(1)
  9213. .backgroundColor(Color.Transparent)
  9214. .onClick(async () => {
  9215. this.isLyricSetting = !this.isLyricSetting;
  9216. })
  9217. //播放列表
  9218. Button({type:ButtonType.Circle,stateEffect:true}){
  9219. Image($r('app.media.hm_playlist'))
  9220. .width(24)
  9221. .fillColor(Color.White)
  9222. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9223. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9224. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  9225. height: '95%',
  9226. dragBar: true,
  9227. showClose: true,
  9228. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9229. blurStyle: BlurStyle.Thin,
  9230. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  9231. title: {
  9232. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  9233. + `(${this.songList.length}首)`
  9234. }
  9235. })
  9236. }
  9237. .layoutWeight(1)
  9238. .height(45)
  9239. .width(45)
  9240. .backgroundColor(Color.Transparent)
  9241. .onClick(() => {
  9242. this.isShowSheetView = !this.isShowSheetView;
  9243. if(this.isPlayListBgGrass){
  9244. this.isFrontWhite = true
  9245. }else{
  9246. this.isFrontWhite = false
  9247. }
  9248. this.scrollIndex()
  9249. })
  9250. }
  9251. .width(this.isLandscape?'88%':'95%')
  9252. .justifyContent(FlexAlign.SpaceAround)
  9253. .height(30)
  9254. .animation({
  9255. duration: 666,
  9256. curve: 'ease-in-out' // 可选动画曲线
  9257. })
  9258. }
  9259. @Builder
  9260. fullButton(){
  9261. Button({type:ButtonType.Circle,stateEffect:true}){
  9262. Column() {
  9263. Image($r('app.media.full_4'))
  9264. .width(25)
  9265. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9266. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9267. }
  9268. }
  9269. .layoutWeight(1)
  9270. .backgroundColor(Color.Transparent)
  9271. .height(45)
  9272. .width(45)
  9273. .onClick(async () => {
  9274. if (this.isLandscape) {
  9275. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  9276. } else {
  9277. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  9278. }
  9279. })
  9280. }
  9281. //旧版本播放进度条
  9282. @Builder
  9283. playProgressView() {
  9284. Row() {
  9285. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9286. Column() {
  9287. if (this.playType === 0) {
  9288. Image($r('app.media.loop'))
  9289. .width($r('app.float.control_image_width'))
  9290. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9291. } else if (this.playType === 1) {
  9292. Image($r('app.media.single'))
  9293. .width($r('app.float.control_image_width'))
  9294. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9295. } else if (this.playType === 2) {
  9296. Image($r('app.media.normal_play'))
  9297. .width($r('app.float.control_image_width'))
  9298. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9299. } else if (this.playType === 3) {
  9300. Image($r('app.media.random'))
  9301. .width($r('app.float.control_image_width'))
  9302. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9303. }
  9304. }
  9305. }
  9306. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  9307. .animation({
  9308. duration: 666,
  9309. curve: 'ease-in-out' // 可选动画曲线
  9310. })
  9311. .backgroundColor(Color.Transparent)
  9312. .margin({ right: 10 })
  9313. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9314. .onClick(async () => {
  9315. this.setLoopMode()
  9316. })
  9317. Text(this.currentTime)
  9318. .fontSize($r('app.float.slider_font_size'))
  9319. .fontColor(Color.White)
  9320. .margin(3)
  9321. Slider({
  9322. value: this.progressValue,
  9323. min: 0,
  9324. max: this.PROGRESS_MAX_VALUE,
  9325. step: 1,
  9326. style: SliderStyle.OutSet
  9327. })
  9328. .width('600px')
  9329. .blockColor('rgba(255,255,255,1)')
  9330. .trackColor('rgba(255,255,255,0.3)')
  9331. .selectedColor(Color.White)
  9332. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  9333. .layoutWeight(1)
  9334. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  9335. .showSteps(false)
  9336. .showTips(true)
  9337. .enabled(this.slideEnable)
  9338. .onChange((value: number, mode: SliderChangeMode) => {
  9339. // if (mode == 2) {
  9340. this.isSeekTo = true;
  9341. this.mDestroyPage = false;
  9342. this.showLoadIng();
  9343. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  9344. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  9345. this.seekTo(seekValue + "");
  9346. // this.setProgress()
  9347. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  9348. this.isSeekTo = false;
  9349. // }
  9350. })
  9351. Text(this.totalTime)
  9352. .fontSize($r('app.float.slider_font_size'))
  9353. .fontColor(Color.White)
  9354. .margin(3)
  9355. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  9356. //播放列表
  9357. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9358. Image($r('app.media.hm_playlist'))
  9359. .width($r('app.float.control_image_width'))
  9360. .fillColor(Color.White)
  9361. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9362. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  9363. height: '95%',
  9364. dragBar: true,
  9365. showClose: true,
  9366. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9367. blurStyle: BlurStyle.Thin,
  9368. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  9369. title: {
  9370. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  9371. + `(${this.songList.length}首)`
  9372. }
  9373. })
  9374. }
  9375. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  9376. .animation({
  9377. duration: 666,
  9378. curve: 'ease-in-out' // 可选动画曲线
  9379. })
  9380. .backgroundColor(Color.Transparent)
  9381. .margin({ right: 20, left: 10 })
  9382. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9383. .onClick(() => {
  9384. this.isShowSheetView = !this.isShowSheetView;
  9385. if (this.isPlayListBgGrass) {
  9386. this.isFrontWhite = true
  9387. } else {
  9388. this.isFrontWhite = false
  9389. }
  9390. this.scrollIndex()
  9391. })
  9392. }
  9393. //x5的竖屏模式需要99%
  9394. .width(this.isPhonePortrait() ? '93.4%'
  9395. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  9396. .height(this.isPhoneLan() ? 25 : 33)
  9397. .animation({
  9398. duration: 666,
  9399. curve: 'ease-in-out' // 可选动画曲线
  9400. })
  9401. }
  9402. isBigScreen() {
  9403. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  9404. return true
  9405. }
  9406. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  9407. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  9408. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  9409. return false
  9410. } else {
  9411. return true
  9412. }
  9413. return false
  9414. }
  9415. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  9416. @State isCoverRectangle: boolean = false
  9417. @State isCoverTop: boolean = true
  9418. // 添加控制缩放的状态变量
  9419. @State scaleValueImage: number = 1
  9420. @State scaleValueText: number = 1
  9421. @Builder
  9422. CoverInfo() {
  9423. Column() {
  9424. //如果是方形,判断是不是封面在顶部,如果不是顶部,显示musicNameInfo, 如果是圆形显示musicNameInfo
  9425. if (this.isCoverRectangle) {
  9426. if (!this.isCoverTop) {
  9427. this.musicNameInfo(false)
  9428. }
  9429. } else {
  9430. this.musicNameInfo(false)
  9431. }
  9432. Stack() {
  9433. // 唱片旋转效果
  9434. Image($r('app.media.ic_music_disc'))
  9435. .width(245)
  9436. .height(245)
  9437. .margin({ right: 20, left: 20 ,top:this.isCoverRectangle||this.isLandscape?0:43})
  9438. .aspectRatio(1)
  9439. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  9440. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  9441. .borderRadius('100%')
  9442. .align(Alignment.Center)
  9443. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  9444. .rotate({
  9445. angle: this.rotateAngle,
  9446. centerX: "50%",
  9447. centerY: "50%",
  9448. })
  9449. .animation({
  9450. duration: 100,
  9451. curve: Curve.Linear
  9452. })
  9453. .shadow({
  9454. radius: 22,
  9455. type: ShadowType.BLUR,
  9456. color: 'on_primary'
  9457. })
  9458. Column() {
  9459. if (this.isCoverTop && this.isCoverRectangle) {
  9460. Image(this.cover)
  9461. .height(this.isHiCar()?(px2vp(this.windowHeight)*0.46):
  9462. this.isCoverOpacity()?(px2vp(this.windowHeight)*0.6):'auto')
  9463. .width(this.isHiCar()||this.isCoverOpacity()?'auto':this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '88%')
  9464. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  9465. .alt($r('app.media.alt'))
  9466. .margin({ right: 8, left: 8, top: 8 })
  9467. .aspectRatio(1)
  9468. .geometryTransition('cover') // 绑定标识符
  9469. .opacity(this.opacityValueImage)
  9470. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  9471. // 设置左下角为缩放中心点
  9472. centerX: '0%',
  9473. centerY: '100%' })
  9474. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  9475. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  9476. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  9477. .clip(true)
  9478. .rotate({
  9479. x: 0,
  9480. y: 0,
  9481. z: 1,
  9482. angle: this.rotateAngle
  9483. })
  9484. .shadow({
  9485. radius: 22,
  9486. type: ShadowType.BLUR,
  9487. color: 'on_primary'
  9488. })
  9489. .onClick(() => {
  9490. })
  9491. // .visualEffect(new hdsEffect.HdsEffectBuilder()
  9492. // .shaderEffect({
  9493. // effectType: hdsEffect.EffectType.DUAL_EDGE_FLOW_LIGHT,
  9494. // animation: {
  9495. // duration: 4000,
  9496. // iterations: -1,
  9497. // autoPlay: true,
  9498. // onFinish: () => {
  9499. // console.info('Succeeded in finishing');
  9500. // }
  9501. // },
  9502. // controller: this.controller,
  9503. // params: {
  9504. // firstEdgeFlowLight: {
  9505. // startPos: 0,
  9506. // endPos: 1.0,
  9507. // color: '#1AD0F1',
  9508. // },
  9509. // secondEdgeFlowLight: {
  9510. // startPos: 0.5,
  9511. // endPos: 1.5,
  9512. // color: '#FFA4E5',
  9513. // }
  9514. // }
  9515. // })
  9516. // .buildEffect())
  9517. this.musicNameInfo(false)
  9518. } else {
  9519. Image(this.cover)
  9520. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  9521. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 162))
  9522. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  9523. .alt($r('app.media.alt'))
  9524. .geometryTransition('cover') // 绑定标识符
  9525. .margin({ right: 20, left: 20,top:this.isCoverRectangle||this.isLandscape?0:43 })
  9526. .aspectRatio(1)
  9527. .opacity(this.opacityValueImage)
  9528. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  9529. // 设置左下角为缩放中心点
  9530. centerX: '0%',
  9531. centerY: '100%' })
  9532. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  9533. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  9534. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  9535. .align(Alignment.Center)//
  9536. .clip(true)
  9537. .shadow({
  9538. radius: 22,
  9539. type: ShadowType.BLUR,
  9540. color: 'on_primary'
  9541. })
  9542. .rotate({
  9543. x: 0,
  9544. y: 0,
  9545. z: 1,
  9546. angle: this.rotateAngle
  9547. })
  9548. .onClick(() => {
  9549. })
  9550. }
  9551. if (this.isPhoneLan()) {
  9552. Text(this.name)
  9553. .fontSize(18)
  9554. .fontWeight(FontWeight.Bold)
  9555. .margin({ top: 13 })
  9556. .textOverflow({ overflow: TextOverflow.Ellipsis })
  9557. .maxLines(1)
  9558. .width('99%')
  9559. .textAlign(TextAlign.Center)
  9560. .fontColor(Color.White)
  9561. }
  9562. }
  9563. // 唱针以左上角为点选择逆时针40度
  9564. Image($r('app.media.ic_music_cover_hand'))
  9565. .height(130)
  9566. .margin({ bottom: 220, top: 0 })
  9567. .align(Alignment.Top)
  9568. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  9569. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  9570. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  9571. Column({ space: 8 }) {
  9572. Text(this.name)
  9573. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  9574. .fontWeight(FontWeight.Bold)
  9575. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9576. .maxLines(1)
  9577. .width('48%')
  9578. .textAlign(TextAlign.Center)
  9579. .fontColor(Color.White)
  9580. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  9581. Text(this.artist)
  9582. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  9583. .fontColor(Color.White)
  9584. .fontWeight(FontWeight.Bold)
  9585. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  9586. }
  9587. .justifyContent(FlexAlign.Start)
  9588. .zIndex(1)
  9589. .geometryTransition('name')
  9590. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  9591. }
  9592. .margin({
  9593. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  9594. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  9595. top: this.isCoverOpacity() ? 0 : 20
  9596. })
  9597. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  9598. this.SingleLyricView()
  9599. }
  9600. if (this.isPhoneLan()) {
  9601. Column() {
  9602. this.playCenterView()
  9603. // this.playProgressView()
  9604. }
  9605. .position({ left: 28, bottom: 38 })
  9606. } else {
  9607. this.BottomControl()
  9608. }
  9609. }
  9610. .width(CommonConstants.FULL_PERCENT)
  9611. .clip(true)
  9612. }
  9613. @Builder
  9614. private musicNameInfo(isHidden: boolean) {
  9615. Row(){
  9616. Column({ space: 8 }) {
  9617. Text(this.name)
  9618. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 20)
  9619. .fontWeight(FontWeight.Bold)
  9620. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9621. .maxLines(1)
  9622. .width('99%')
  9623. .textAlign(TextAlign.Start)
  9624. .fontColor(Color.White)
  9625. Text(this.artist + ' ' + this.currentSong?.album)
  9626. .fontSize(this.isCoverOpacity() ? 12 : 15)
  9627. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9628. .fontColor(Color.White)
  9629. .textAlign(TextAlign.Start)
  9630. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  9631. .width('99%')
  9632. .maxLines(1)
  9633. }
  9634. .zIndex(1)
  9635. .geometryTransition('name') // 绑定标识符
  9636. .layoutWeight(1)
  9637. .margin({ left: 15 })
  9638. Blank()
  9639. Row(){
  9640. Button({type:ButtonType.Circle,stateEffect:true}){
  9641. //添加或取消收藏
  9642. SymbolGlyph(Utility.getIsFav(this.favList,this.currentSong)?
  9643. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'))
  9644. .fontSize(22)
  9645. .fontColor([Color.White])
  9646. .alignSelf(ItemAlign.Center)
  9647. // .width(24)
  9648. .clickEffect({level:ClickEffectLevel.MIDDLE})
  9649. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9650. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9651. .onClick(async () => {
  9652. if(this.currentSong){
  9653. this.doFav(this.currentSong)
  9654. }
  9655. })
  9656. }
  9657. .margin({ left: 15,right:3 })
  9658. .backgroundColor(Color.Transparent)
  9659. .width(45)
  9660. .height(45)
  9661. }
  9662. }
  9663. .width('90%')
  9664. .scale({ x: this.scaleValueText, y: this.scaleValueText }) // 添加缩放效果
  9665. .margin({ top: this.isCoverOpacity() ? 10 : isHidden ? 20 : 10 })
  9666. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  9667. }
  9668. @Builder
  9669. private PlayTitle() {
  9670. Row() {
  9671. Row() {
  9672. Image($r('app.media.ic_back_down'))
  9673. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  9674. .hitTestBehavior(HitTestMode.Transparent)
  9675. Text(this.name + ' ' + this.artist)
  9676. .fontColor(Color.White)
  9677. .fontSize($r('app.float.title_font_size'))
  9678. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9679. .maxLines(1)
  9680. .visibility(Visibility.None)
  9681. .margin({ left: 2, right: 30 })
  9682. }
  9683. .layoutWeight(1)
  9684. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9685. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  9686. .onClick(() => {
  9687. this.setShowPlayFalse()
  9688. })
  9689. Column() {
  9690. AVCastPicker({
  9691. normalColor: Color.White,
  9692. onStateChange: this.onStateVastChange
  9693. })
  9694. .width(24)
  9695. .height(24)
  9696. }
  9697. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  9698. }
  9699. .width(PlayConstants.ROW_WIDTH)
  9700. }
  9701. @Builder
  9702. lyricSettingSheet(isPip: boolean) {
  9703. Scroll() {
  9704. this.lyricSetting(isPip)
  9705. }
  9706. .width('100%')
  9707. .height('100%')
  9708. }
  9709. @Builder
  9710. lyricSetting(isPip: boolean) {
  9711. Column() {
  9712. // 时间调节模块
  9713. if (!isPip) {
  9714. this.BuildTimeControls()
  9715. }
  9716. // 字号控制模块
  9717. this.BuildFontControls(isPip)
  9718. }
  9719. }
  9720. // 歌词时间偏移状态
  9721. @State timeOffset: number = 0.0
  9722. @State currentLyricColor: string = '#FFFFFF'
  9723. @State currentLyricColorPip: string = '#FFFFFF'
  9724. @State currentHighLightLyricColor: string = '#FF4081'
  9725. @State currentHighLightLyricColorPip: string = '#FF4081'
  9726. // 歌词字号状态
  9727. @State currentLyricSize: number = 20
  9728. @State currentLyricSizePip: number = 20
  9729. // 高亮歌词放大倍数
  9730. @State currentHightLyricSize: number = 1.2
  9731. @State currentHightLyricSizePip: number = 1.2
  9732. @State currentLyricLineSpace: number = 10
  9733. @State currentLyricLineSpacePip: number = 10
  9734. @State currentLyricAlignMode: number = 1
  9735. @State currentLyricAlignModePip: number = 1
  9736. @State blurDegree: number = 2
  9737. @State blurDegreePip: number = 2
  9738. @State isShowSelectColor: boolean = false
  9739. @State isShowHLSelectColor: boolean = false
  9740. @State isShowPipBgSelectColor: boolean = false
  9741. @State pipLyWidth: number = 330
  9742. @State pipLyHeight: number = 120
  9743. // 构建颜色选择器
  9744. @Builder
  9745. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  9746. Row({ space: 10 }) {
  9747. HSBColorPicker({
  9748. color: '#FFFFFF',
  9749. radius: 8,
  9750. layout: HSBColorPickerLayout.COLUMN,
  9751. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  9752. '#fa7105'],
  9753. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  9754. this.changeLyricColor(value, isPip, isBGPip)
  9755. })
  9756. .height(250)
  9757. .layoutWeight(1)
  9758. .padding(25)
  9759. }
  9760. .width('66%')
  9761. }
  9762. @State isOpenPip: boolean = false
  9763. @State pipBgIndex: number = 0
  9764. // 构建字号控制器
  9765. @Builder
  9766. BuildFontControls(isPip: boolean) {
  9767. Column() {
  9768. if (isPip) {
  9769. Column() {
  9770. Row() {
  9771. Text('悬浮歌词')
  9772. .margin({ left: 18 })
  9773. .fontSize(15)
  9774. .fontColor(Color.White)
  9775. .fontWeight(480)
  9776. .layoutWeight(1)
  9777. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  9778. .selectedColor(this.themeColor)
  9779. .switchPointColor(Color.White)
  9780. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9781. .margin({ right: 18 })
  9782. .onChange((checked: boolean) => {
  9783. this.isOpenPip = checked;
  9784. if (this.isOpenPip) {
  9785. this.startPip()
  9786. } else {
  9787. this.stopPip()
  9788. }
  9789. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  9790. })
  9791. .width(50)
  9792. .height(30);
  9793. }
  9794. .height(55)
  9795. }
  9796. .backgroundColor(Color.Transparent)
  9797. .borderRadius(15)
  9798. .margin({
  9799. left: 30,
  9800. right: 30,
  9801. top: 0,
  9802. bottom: 20
  9803. })
  9804. .padding(0)
  9805. .border({
  9806. color: Color.White,
  9807. width: 1.8
  9808. })
  9809. }else{
  9810. Column() {
  9811. Row() {
  9812. Text('单行歌词')
  9813. .margin({ left: 18 })
  9814. .fontSize(15)
  9815. .fontColor(Color.White)
  9816. .fontWeight(480)
  9817. .layoutWeight(1)
  9818. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  9819. .selectedColor(this.themeColor)
  9820. .switchPointColor(Color.White)
  9821. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9822. .margin({ right: 18 })
  9823. .onChange((checked: boolean) => {
  9824. this.isShowSingleLineLyric = checked;
  9825. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  9826. })
  9827. .width(50)
  9828. .height(30);
  9829. }
  9830. .height(55)
  9831. }
  9832. .backgroundColor(Color.Transparent)
  9833. .borderRadius(15)
  9834. .margin({
  9835. left: 30,
  9836. right: 30,
  9837. top: 10,
  9838. bottom: 10
  9839. })
  9840. .padding(0)
  9841. .border({
  9842. color: Color.White,
  9843. width: 1.8
  9844. })
  9845. }
  9846. Row() {
  9847. Text(`歌词居中:`)
  9848. .fontSize(14)
  9849. .fontColor(Color.White)
  9850. .margin({ left: 2 })
  9851. Row() {
  9852. ForEach(['居中', '居左'], (size: string, index: number) => {
  9853. Button(size)
  9854. .width(60)
  9855. .height(28)
  9856. .fontSize(12)
  9857. .fontColor('#FFFFFF')
  9858. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  9859. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  9860. .border({
  9861. color: (!isPip && this.currentLyricAlignMode === index) ||
  9862. (isPip && this.currentLyricAlignModePip === index) ?
  9863. '#007DFF' : '#DDDDDD',
  9864. width: 1.8
  9865. })
  9866. .onClick(() => {
  9867. this.setLyricAlignMode(index, isPip)
  9868. })
  9869. .margin({ left: 10, right: 8 })
  9870. })
  9871. }
  9872. .width('76%')
  9873. Blank()
  9874. }
  9875. .margin({
  9876. top: 10,
  9877. bottom: 10,
  9878. right: 20,
  9879. left: 20
  9880. })
  9881. if (isPip) {
  9882. Row() {
  9883. Text(`悬浮背景:`)
  9884. .fontSize(14)
  9885. .fontColor(Color.White)
  9886. Select([
  9887. { value: CommonConstants.PIP_LYRIC_BG[0] },
  9888. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  9889. .font({ size: 13, weight: FontWeight.Medium })
  9890. .fontColor(Color.White)
  9891. .margin({ left: 10 })
  9892. .selected(this.pipBgIndex)
  9893. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  9894. .onSelect(async (_index: number, text?: string | undefined) => {
  9895. this.pipBgIndex = _index
  9896. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  9897. if (this.pipBgIndex === 0) {
  9898. if (this.cover) {
  9899. this.pipBg = this.cover
  9900. } else {
  9901. this.pipBg = this.imageColor
  9902. }
  9903. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  9904. } else {
  9905. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  9906. }
  9907. })
  9908. Column() {
  9909. }
  9910. .backgroundColor(this.pipBg)
  9911. .margin({ left: 10, right: 10 })
  9912. .borderRadius(20)
  9913. .height(28)
  9914. .width(28)
  9915. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9916. Row() {
  9917. SymbolGlyph($r('sys.symbol.paintbrush'))
  9918. .fontColor([Color.White])
  9919. .effectStrategy(1)
  9920. Text(`选择颜色`)
  9921. .fontSize(13)
  9922. .margin({ left: 10 })
  9923. .fontColor(Color.White)
  9924. }
  9925. }
  9926. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  9927. .backgroundColor(Color.Transparent)
  9928. .border({
  9929. color: '#FFFFFF',
  9930. radius: 20,
  9931. width: 1.8
  9932. })
  9933. .height(36)
  9934. .width(110)
  9935. .onClick(() => {
  9936. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  9937. })
  9938. .bindPopup(this.isShowPipBgSelectColor, {
  9939. builder: this.SelectColor(false, isPip, true),
  9940. placement: Placement.Top,
  9941. mask: { color: '#33000000' },
  9942. enableArrow: false, //是否显示箭头
  9943. showInSubWindow: false,
  9944. onStateChange: (e) => {
  9945. if (!e.isVisible) {
  9946. this.isShowPipBgSelectColor = false
  9947. }
  9948. }
  9949. })
  9950. }
  9951. .width('76%')
  9952. .margin({ bottom: 5, right: 45, left: 20 })
  9953. }
  9954. if (!isPip) {
  9955. Row() {
  9956. Text(`高亮居中:`)
  9957. .fontSize(14)
  9958. .fontColor(Color.White)
  9959. Column() {
  9960. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  9961. .selectedColor(this.themeColor)
  9962. .switchPointColor(Color.White)
  9963. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9964. .onChange((checked: boolean) => {
  9965. this.isHightLightCenter = checked;
  9966. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  9967. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  9968. })
  9969. .width(50)
  9970. .height(30)
  9971. .alignSelf(ItemAlign.Start)
  9972. .margin({ left: 12 })
  9973. Blank()
  9974. }
  9975. .width('76%')
  9976. }
  9977. .margin({
  9978. left: 20,
  9979. right: 15,
  9980. top: 10,
  9981. bottom: 10
  9982. })
  9983. }
  9984. Row() {
  9985. Text(`歌词颜色:`)
  9986. .fontSize(14)
  9987. .fontColor(Color.White)
  9988. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  9989. .fontSize(15)
  9990. .fontColor(Color.White)
  9991. .margin({ left: 12, right: 12 })
  9992. Column() {
  9993. }
  9994. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  9995. .margin({ right: 12 })
  9996. .borderRadius(20)
  9997. .height(28)
  9998. .width(28)
  9999. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10000. Row() {
  10001. SymbolGlyph($r('sys.symbol.paintbrush'))
  10002. .fontColor([Color.White])
  10003. .effectStrategy(1)
  10004. Text(`选择颜色`)
  10005. .fontSize(13)
  10006. .margin({ left: 10 })
  10007. .fontColor(Color.White)
  10008. }
  10009. }
  10010. .backgroundColor(Color.Transparent)
  10011. .border({
  10012. color: '#FFFFFF',
  10013. radius: 20,
  10014. width: 1.8
  10015. })
  10016. .height(36)
  10017. .width(110)
  10018. .onClick(() => {
  10019. this.isShowSelectColor = !this.isShowSelectColor
  10020. })
  10021. .bindPopup(this.isShowSelectColor, {
  10022. builder: this.SelectColor(false, isPip),
  10023. placement: Placement.Top,
  10024. mask: { color: '#33000000' },
  10025. enableArrow: false, //是否显示箭头
  10026. showInSubWindow: false,
  10027. onStateChange: (e) => {
  10028. if (!e.isVisible) {
  10029. this.isShowSelectColor = false
  10030. }
  10031. }
  10032. })
  10033. }
  10034. .width('76%')
  10035. .margin({
  10036. top: 10,
  10037. bottom: 10,
  10038. right: 45,
  10039. left: 20
  10040. })
  10041. Row() {
  10042. Text(`高亮颜色:`)
  10043. .fontSize(14)
  10044. .fontColor(Color.White)
  10045. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  10046. .fontSize(15)
  10047. .fontColor(Color.White)
  10048. .margin({ left: 12, right: 12 })
  10049. Column() {
  10050. }
  10051. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  10052. .margin({ right: 12 })
  10053. .borderRadius(20)
  10054. .height(28)
  10055. .width(28)
  10056. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10057. Row() {
  10058. SymbolGlyph($r('sys.symbol.paintbrush'))
  10059. .fontColor([Color.White])
  10060. .effectStrategy(1)
  10061. Text(`选择颜色`)
  10062. .fontSize(13)
  10063. .margin({ left: 10 })
  10064. .fontColor(Color.White)
  10065. }
  10066. }
  10067. .backgroundColor(Color.Transparent)
  10068. .border({
  10069. color: '#FFFFFF',
  10070. radius: 20,
  10071. width: 1.8
  10072. })
  10073. .height(36)
  10074. .width(110)
  10075. .onClick(() => {
  10076. this.isShowHLSelectColor = !this.isShowHLSelectColor
  10077. })
  10078. .bindPopup(this.isShowHLSelectColor, {
  10079. builder: this.SelectColor(true, isPip),
  10080. placement: Placement.Top,
  10081. mask: { color: '#33000000' },
  10082. enableArrow: false, //是否显示箭头
  10083. showInSubWindow: false,
  10084. onStateChange: (e) => {
  10085. if (!e.isVisible) {
  10086. this.isShowHLSelectColor = false
  10087. }
  10088. }
  10089. })
  10090. }
  10091. .width('76%')
  10092. .margin({
  10093. top: 10,
  10094. bottom: 10,
  10095. right: 45,
  10096. left: 20
  10097. })
  10098. if (isPip) {
  10099. Row() {
  10100. Text(`显示宽度:`)
  10101. .fontSize(14)
  10102. .fontColor(Color.White)
  10103. Slider({
  10104. value: this.pipLyWidth,
  10105. min: 10,
  10106. max: 800,
  10107. step: 1,
  10108. style: SliderStyle.OutSet
  10109. })
  10110. .blockColor(this.themeColor)
  10111. .trackColor($r('app.color.speed_text_color'))
  10112. .selectedColor(Color.White)
  10113. .trackThickness(6)
  10114. .onChange((value: number) => {
  10115. this.pipLyWidth = value
  10116. if (this.pipController) {
  10117. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10118. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  10119. }
  10120. })
  10121. .width('76%')
  10122. }
  10123. .margin({
  10124. left: 20,
  10125. right: 15,
  10126. top: 5,
  10127. bottom: 5
  10128. })
  10129. Row() {
  10130. Text(`显示高度:`)
  10131. .fontSize(14)
  10132. .fontColor(Color.White)
  10133. Slider({
  10134. value: this.pipLyHeight,
  10135. min: 10,
  10136. max: 1000,
  10137. step: 1,
  10138. style: SliderStyle.OutSet
  10139. })
  10140. .blockColor(this.themeColor)
  10141. .trackColor($r('app.color.speed_text_color'))
  10142. .selectedColor(Color.White)
  10143. .trackThickness(6)
  10144. .onChange((value: number) => {
  10145. this.pipLyHeight = value
  10146. if (this.pipController) {
  10147. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10148. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  10149. }
  10150. })
  10151. .width('76%')
  10152. }
  10153. .margin({
  10154. left: 20,
  10155. right: 15,
  10156. top: 5,
  10157. bottom: 5
  10158. })
  10159. }
  10160. Row() {
  10161. Text(`歌词字号:`)
  10162. .fontSize(14)
  10163. .fontColor(Color.White)
  10164. Slider({
  10165. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  10166. min: 12,
  10167. max: 30,
  10168. step: 0.1,
  10169. style: SliderStyle.OutSet
  10170. })
  10171. .blockColor(this.themeColor)
  10172. .trackColor($r('app.color.speed_text_color'))
  10173. .selectedColor(Color.White)
  10174. .trackThickness(6)
  10175. .onChange((value: number) => {
  10176. this.setLyricTextSize(value, isPip)
  10177. })
  10178. .width('76%')
  10179. }
  10180. .margin({
  10181. left: 20,
  10182. right: 15,
  10183. top: 5,
  10184. bottom: 5
  10185. })
  10186. Row() {
  10187. Text(`高亮倍数:`)
  10188. .fontSize(14)
  10189. .fontColor(Color.White)
  10190. Slider({
  10191. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  10192. min: 1,
  10193. max: 2,
  10194. step: 0.1,
  10195. style: SliderStyle.OutSet
  10196. })
  10197. .blockColor(this.themeColor)
  10198. .trackColor($r('app.color.speed_text_color'))
  10199. .selectedColor(Color.White)
  10200. .trackThickness(6)
  10201. .onChange((value: number) => {
  10202. this.setHighLyricTextSize(value, isPip)
  10203. })
  10204. .width('76%')
  10205. }
  10206. .margin({
  10207. left: 20,
  10208. right: 15,
  10209. top: 5,
  10210. bottom: 5
  10211. })
  10212. Row() {
  10213. Text(`歌词间隙:`)
  10214. .fontSize(14)
  10215. .fontColor(Color.White)
  10216. Slider({
  10217. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  10218. min: 0,
  10219. max: 100,
  10220. step: 1,
  10221. style: SliderStyle.OutSet
  10222. })
  10223. .blockColor(this.themeColor)
  10224. .trackColor($r('app.color.speed_text_color'))
  10225. .selectedColor(Color.White)
  10226. .trackThickness(6)
  10227. .onChange((value: number) => {
  10228. this.setLyricLineSpace(value, isPip)
  10229. })
  10230. .width('76%')
  10231. }
  10232. .margin({
  10233. left: 20,
  10234. right: 15,
  10235. top: 5,
  10236. bottom: 5
  10237. })
  10238. //取值间隔为100,默认为400,取值越大,字体越粗
  10239. Row() {
  10240. Text(`歌词字重:`)
  10241. .fontSize(14)
  10242. .fontColor(Color.White)
  10243. Slider({
  10244. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  10245. min: 100,
  10246. max: 900,
  10247. step: 100,
  10248. style: SliderStyle.OutSet
  10249. })
  10250. .blockColor(this.themeColor)
  10251. .trackColor($r('app.color.speed_text_color'))
  10252. .selectedColor(Color.White)
  10253. .trackThickness(6)
  10254. .onChange((value: number) => {
  10255. if (isPip) {
  10256. this.lyricTextWeightPip = value
  10257. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  10258. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  10259. } else {
  10260. this.lyricTextWeight = value
  10261. this.lyricController.setTextWeight(this.lyricTextWeight)
  10262. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  10263. }
  10264. })
  10265. .width('76%')
  10266. }
  10267. .margin({
  10268. left: 20,
  10269. right: 15,
  10270. top: 5,
  10271. bottom: 5
  10272. })
  10273. if (!isPip) {
  10274. Row() {
  10275. Text(`歌词模糊:`)
  10276. .fontSize(14)
  10277. .fontColor(Color.White)
  10278. Slider({
  10279. value: isPip ? this.blurDegreePip : this.blurDegree,
  10280. min: 0,
  10281. max: 5,
  10282. step: 0.1,
  10283. style: SliderStyle.OutSet
  10284. })
  10285. .blockColor(this.themeColor)
  10286. .trackColor($r('app.color.speed_text_color'))
  10287. .selectedColor(Color.White)
  10288. .trackThickness(6)
  10289. .onChange((value: number) => {
  10290. this.setBlurDegree(value, isPip)
  10291. })
  10292. .width('76%')
  10293. }
  10294. .margin({
  10295. left: 20,
  10296. right: 15,
  10297. top: 5,
  10298. bottom: 15
  10299. })
  10300. }
  10301. Row() {
  10302. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  10303. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  10304. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  10305. }
  10306. .justifyContent(FlexAlign.Center)
  10307. .margin({ top: 3, bottom: 10 })
  10308. }
  10309. }
  10310. private setBlurDegree(index: number, isPip: boolean) {
  10311. if (isPip) {
  10312. this.blurDegreePip = index
  10313. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  10314. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  10315. } else {
  10316. this.blurDegree = index
  10317. this.lyricController.setBlurDegree(this.blurDegree)
  10318. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  10319. }
  10320. }
  10321. private setLyricAlignMode(index: number, isPip: boolean) {
  10322. if (isPip) {
  10323. this.currentLyricAlignModePip = index
  10324. if (this.currentLyricAlignModePip === 1) {
  10325. this.lyricControllerXF.setAlignMode("left")
  10326. } else {
  10327. this.lyricControllerXF.setAlignMode("center")
  10328. }
  10329. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  10330. } else {
  10331. this.currentLyricAlignMode = index
  10332. if (this.currentLyricAlignMode === 1) {
  10333. this.lyricController.setAlignMode("left")
  10334. } else {
  10335. this.lyricController.setAlignMode("center")
  10336. }
  10337. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  10338. }
  10339. }
  10340. private setLyricTextSize(index: number, isPip: boolean) {
  10341. if (isPip) {
  10342. this.currentLyricSizePip = index
  10343. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  10344. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  10345. } else {
  10346. this.currentLyricSize = index
  10347. this.lyricController.setTextSize(this.currentLyricSize)
  10348. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  10349. }
  10350. }
  10351. private setHighLyricTextSize(scale: number, isPip: boolean) {
  10352. if (isPip) {
  10353. this.currentHightLyricSizePip = scale
  10354. this.lyricControllerXF
  10355. .setHighlightScale(this.currentHightLyricSizePip)
  10356. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  10357. } else {
  10358. this.currentHightLyricSize = scale
  10359. this.lyricController
  10360. .setHighlightScale(this.currentHightLyricSize)
  10361. PreferencesUtil.putSync('HighLyricTextSize', scale)
  10362. }
  10363. }
  10364. private setLyricLineSpace(index: number, isPip: boolean) {
  10365. if (isPip) {
  10366. this.currentLyricLineSpacePip = index
  10367. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  10368. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  10369. } else {
  10370. this.currentLyricLineSpace = index
  10371. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  10372. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  10373. }
  10374. }
  10375. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  10376. LogUtil.info('onecold isBG = ' + isBG)
  10377. if (isBG) { //如果是设置悬浮背景
  10378. this.pipBg = color
  10379. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  10380. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  10381. return
  10382. }
  10383. if (isPip) {
  10384. this.currentLyricColorPip = color
  10385. this.lyricControllerXF
  10386. .setTextColor(this.currentLyricColorPip)
  10387. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  10388. } else {
  10389. this.currentLyricColor = color
  10390. this.lyricController
  10391. .setTextColor(this.currentLyricColor)
  10392. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  10393. }
  10394. }
  10395. private changeLyricHightLightColor(color: string, isPip: boolean) {
  10396. if (isPip) {
  10397. this.currentHighLightLyricColorPip = color
  10398. this.lyricControllerXF
  10399. .setHighlightColor(this.currentHighLightLyricColorPip)
  10400. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  10401. } else {
  10402. this.currentHighLightLyricColor = color
  10403. this.lyricController
  10404. .setHighlightColor(this.currentHighLightLyricColor)
  10405. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  10406. }
  10407. }
  10408. // 构建时间控制器
  10409. @Builder
  10410. BuildTimeControls() {
  10411. Column() {
  10412. // 时间显示
  10413. Text(this.getTimeText())
  10414. .fontSize(18)
  10415. .fontColor(Color.White)
  10416. .margin({ bottom: 10 })
  10417. Row() {
  10418. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  10419. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  10420. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  10421. }
  10422. .justifyContent(FlexAlign.Center)
  10423. }
  10424. .margin({ top: 12, bottom: 8 })
  10425. }
  10426. // 精度按钮组件
  10427. @Builder
  10428. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  10429. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10430. Column() {
  10431. Image(icon)
  10432. .width(28)
  10433. .margin({ bottom: 5 })
  10434. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  10435. Text(label)
  10436. .fontSize(12)
  10437. .fontColor('#FFFFFF')
  10438. }
  10439. }
  10440. .backgroundColor(Color.Transparent)
  10441. .enabled(!this.isButtonDisabled(step))
  10442. .onClick(() => this.handlePrecisionAdjust(step))
  10443. .padding(5)
  10444. .width(66)
  10445. .height(66)
  10446. .margin({ left: 18, right: 18 })
  10447. .border({
  10448. color: '#FFFFFF',
  10449. width: 1.8
  10450. })
  10451. }
  10452. private handlePrecisionAdjust(step: number) {
  10453. if (step === 0) {
  10454. this.timeOffset = 0
  10455. return
  10456. }
  10457. // 精度处理:保留1位小数
  10458. const newOffset = Number((this.timeOffset + step).toFixed(5))
  10459. // 边界保护(±15.0秒)
  10460. if (newOffset < -30.0 || newOffset > 30.0) {
  10461. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  10462. return
  10463. }
  10464. // 状态更新
  10465. this.timeOffset = newOffset
  10466. }
  10467. // 按钮禁用逻辑
  10468. private isButtonDisabled(step: number): boolean {
  10469. const futureOffset = this.timeOffset + step
  10470. return (futureOffset < -30.0) || (futureOffset > 30.0)
  10471. }
  10472. // 时间显示文本升级
  10473. private getTimeText(): string {
  10474. const absValue = Math.abs(this.timeOffset)
  10475. return this.timeOffset === 0
  10476. ? '歌词时间已重置'
  10477. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  10478. }
  10479. // 导入 本地歌词 搜索歌词
  10480. @Builder
  10481. pushLyricButton(icon: Resource, step: number, label: string) {
  10482. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10483. Row() {
  10484. Image(icon)
  10485. .width(14)
  10486. .margin({ left: 13 })
  10487. Text(label)
  10488. .fontSize(12)
  10489. .margin({ left: 6 })
  10490. .fontColor('#FFFFFF')
  10491. }
  10492. }
  10493. .onClick(() => {
  10494. switch (step) {
  10495. case 0:
  10496. this.callFilePickerSelectFileForLyric()
  10497. break;
  10498. case 1:
  10499. //判断有没有设置api
  10500. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  10501. this.isLyricSetting = false
  10502. this.showTipsDialog()
  10503. return
  10504. }
  10505. if (StrUtil.isNotEmpty(this.videoUrl)) {
  10506. ToastUtil.showToast('正在获取')
  10507. this.isLyricSetting = false
  10508. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  10509. this.initLyric(lyricPath, true);
  10510. }
  10511. break;
  10512. }
  10513. })
  10514. .padding(5)
  10515. .width(110)
  10516. .backgroundColor(Color.Transparent)
  10517. .height(40)
  10518. .margin({ left: 6, right: 6 })
  10519. .border({
  10520. color: '#FFFFFF',
  10521. radius: 20,
  10522. width: 1.8
  10523. })
  10524. }
  10525. showVipDialog() {
  10526. DialogHelper.showCustomContentDialog({
  10527. dialogId: 'vip',
  10528. title: "友情提示",
  10529. autoCancel: false, //点击遮障层时,不关闭弹窗
  10530. backCancel: true, //点击返回键,不关闭弹窗
  10531. contentBuilder: () => {
  10532. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  10533. },
  10534. buttons: [],
  10535. })
  10536. }
  10537. //去赞助的自定义内容
  10538. @Builder
  10539. customVipBuilder(content: string) {
  10540. Column() {
  10541. Text(content)
  10542. .fontColor(Color.Gray)
  10543. .fontSize(16)
  10544. .alignSelf(ItemAlign.Start)
  10545. .margin({ bottom: 15 })
  10546. .fontSize(16)
  10547. Row() {
  10548. Button('取消')
  10549. .fontColor(Color.White)
  10550. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  10551. .height(50)
  10552. .layoutWeight(1)
  10553. .stateEffect(true)
  10554. .margin({ right: 6 })
  10555. .onClick(() => {
  10556. DialogHelper.closeDialog('vip'); //关闭弹框
  10557. })
  10558. Button('开通')
  10559. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  10560. .layoutWeight(1)
  10561. .height(50)
  10562. .backgroundColor(this.themeColor)
  10563. .stateEffect(true)
  10564. .margin({ left: 6 })
  10565. .onClick(() => {
  10566. DialogHelper.closeDialog('vip'); //关闭弹框
  10567. this.isShowPlay = false
  10568. this.mType = 1 //跳转到用户中心
  10569. // router.pushUrl({
  10570. // url: 'pages/VipPage'
  10571. // }, router.RouterMode.Single);
  10572. })
  10573. }
  10574. }
  10575. .width("100%")
  10576. .padding(10)
  10577. }
  10578. showTipsDialog() {
  10579. DialogHelper.showCustomContentDialog({
  10580. dialogId: 'tips',
  10581. title: "友情提示",
  10582. autoCancel: false, //点击遮障层时,不关闭弹窗
  10583. backCancel: true, //点击返回键,不关闭弹窗
  10584. contentBuilder: () => {
  10585. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  10586. },
  10587. buttons: [],
  10588. })
  10589. }
  10590. @Builder
  10591. customTipsBuilder(content: string) {
  10592. Column() {
  10593. Text(content)
  10594. .fontColor(Color.Gray)
  10595. .fontSize(16)
  10596. .alignSelf(ItemAlign.Start)
  10597. .margin({ bottom: 15 })
  10598. .fontSize(16)
  10599. Row() {
  10600. Button('取消')
  10601. .fontColor(Color.White)
  10602. .backgroundColor(this.themeColor)
  10603. .height(50)
  10604. .layoutWeight(1)
  10605. .stateEffect(true)
  10606. .margin({ right: 6 })
  10607. .onClick(() => {
  10608. DialogHelper.closeDialog('tips'); //关闭弹框
  10609. })
  10610. Button('跳转')
  10611. .fontColor(Color.White)//
  10612. .layoutWeight(1)
  10613. .height(50)
  10614. .backgroundColor(this.themeColor)
  10615. .stateEffect(true)
  10616. .margin({ left: 6 })
  10617. .onClick(() => {
  10618. DialogHelper.closeDialog('tips'); //关闭弹框
  10619. this.isShowEdit = false
  10620. this.longItemFilePath = ''
  10621. // if(this.isGridMusic&&!this.isShowPlay){
  10622. // this.longItemFilePath== ''
  10623. // }else{
  10624. // this.isShowEdit = false
  10625. // }
  10626. this.isShowMoreView = false;
  10627. this.isShowPlay = false
  10628. this.mType = 4
  10629. // router.pushUrl({
  10630. // url: 'pages/SettingPage'
  10631. // }, router.RouterMode.Single);
  10632. })
  10633. }
  10634. }
  10635. .width("100%")
  10636. .padding(10)
  10637. }
  10638. @Builder
  10639. PlayMoreSheet() {
  10640. Column() {
  10641. this.MoreList()
  10642. }
  10643. .width('100%')
  10644. .height('100%')
  10645. }
  10646. @Builder
  10647. MoreList() {
  10648. Scroll() {
  10649. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  10650. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  10651. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10652. Row() {
  10653. if (more.id === 3&&this.currentSong) {
  10654. Image(more.image)
  10655. .width(24)
  10656. .height(24)
  10657. .margin({ left: 10, right: 10 })
  10658. Text(more.title)
  10659. .fontSize(16)
  10660. .fontColor(Color.White)
  10661. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  10662. height: this.isCoverOpacity() ? '95%' : '95%',
  10663. dragBar: true,
  10664. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  10665. showClose: true,
  10666. blurStyle: BlurStyle.Thin,
  10667. backgroundColor: Color.Transparent,
  10668. title: { title: '歌曲信息' }
  10669. })
  10670. } else if (more.id === 15 && this.currentSong) { //编辑标签
  10671. Image(more.image)
  10672. .width(24)
  10673. .height(24)
  10674. .margin({ left: 10, right: 10 })
  10675. Text(more.title)
  10676. .fontSize(16)
  10677. .fontColor(Color.White)
  10678. } else if (more.id === 5) { //定时关闭
  10679. Image(more.image)
  10680. .width(24)
  10681. .height(24)
  10682. .margin({ left: 10, right: 10 })
  10683. Text(more.title)
  10684. .fontSize(16)
  10685. .fontColor(Color.White)
  10686. .onClick(() => {
  10687. this.doMore(more.id)
  10688. })
  10689. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  10690. height: this.isCoverOpacity() ? '95%' : '95%',
  10691. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  10692. dragBar: true,
  10693. showClose: true,
  10694. title: { title: $r('app.string.time_close') }
  10695. })
  10696. } else if (more.id === 2) { //歌词设置
  10697. Image(more.image)
  10698. .width(24)
  10699. .height(24)
  10700. .margin({ left: 10, right: 10 })
  10701. Text(more.title)
  10702. .fontSize(16)
  10703. .fontColor(Color.White)
  10704. } else if (more.id === 16) { //悬浮歌词设置
  10705. Image(more.image)
  10706. .width(24)
  10707. .height(24)
  10708. .margin({ left: 10, right: 10 })
  10709. Text(more.title)
  10710. .fontSize(16)
  10711. .fontColor(Color.White)
  10712. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  10713. height: this.isCoverOpacity() ? '95%' : '95%',
  10714. dragBar: true,
  10715. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  10716. showClose: true,
  10717. blurStyle: BlurStyle.Thin,
  10718. backgroundColor: Color.Transparent,
  10719. title: { title: '悬浮歌词' }
  10720. })
  10721. } else if (more.id === 11) {
  10722. Image(more.image)
  10723. .width(24)
  10724. .height(24)
  10725. .margin({ left: 10, right: 10 })
  10726. Text(more.title)
  10727. .fontSize(16)
  10728. .fontColor(Color.White)
  10729. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  10730. height: this.isCoverOpacity() ? '95%' : '60%',
  10731. dragBar: true,
  10732. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  10733. showClose: true,
  10734. blurStyle: BlurStyle.Thin,
  10735. backgroundColor: Color.Transparent,
  10736. title: { title: '跳过头尾' }
  10737. })
  10738. } else if (more.id === 12) { //投播
  10739. AVCastPicker({
  10740. customPicker: (): void => this.TPImageBuilder(more),
  10741. onStateChange: (state) => {
  10742. if (state == AVCastPickerState.STATE_APPEARING) {
  10743. console.log(' The picker starts showing.');
  10744. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  10745. console.log(' The picker finishes presenting.');
  10746. }
  10747. },
  10748. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  10749. sessionType: 'video'
  10750. })
  10751. .id('AVCastPicker')
  10752. } else {
  10753. Image(more.image)
  10754. .width(24)
  10755. .height(24)
  10756. .fillColor(Color.White)
  10757. .margin({ left: 10, right: 10 })
  10758. .onClick(() => {
  10759. this.doMore(more.id)
  10760. })
  10761. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  10762. .fontSize(16)
  10763. .fontColor(Color.White)
  10764. .onClick(() => {
  10765. this.doMore(more.id)
  10766. })
  10767. Select([//倍速
  10768. { value: '0.25x' },
  10769. { value: '0.5x' },
  10770. { value: '0.75x' },
  10771. { value: '1x' },
  10772. { value: '1.25x' },
  10773. { value: '1.5x' },
  10774. { value: '1.75x' },
  10775. { value: '2x' },
  10776. { value: '3x' }])
  10777. .font({ size: 16, weight: FontWeight.Medium })
  10778. .fontColor($r('sys.color.white'))
  10779. .margin({ left: 25 })
  10780. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  10781. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  10782. .value(Utility.optimizedFormat(this.playSpeed))
  10783. .onSelect(async (_index: number, text?: string | undefined) => {
  10784. let speed = parseFloat(text?.replace('x', '') || '1');
  10785. if (!CommonConstants.video_speed_list.includes(speed)) {
  10786. speed = 1;
  10787. }
  10788. this.playSpeed = speed
  10789. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  10790. })
  10791. Slider({
  10792. value: this.volume,
  10793. min: 0,
  10794. max: 1,
  10795. step: 0.1,
  10796. style: SliderStyle.OutSet
  10797. })
  10798. .margin({ left: 18, right: 8 })
  10799. .blockColor(this.themeColor)
  10800. .trackColor($r('app.color.speed_text_color'))
  10801. .selectedColor(Color.White)
  10802. .trackThickness(9)
  10803. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  10804. .onChange((value: number) => {
  10805. this.volume = value;
  10806. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  10807. PreferencesUtil.putSync('DefalutVolume',this.volume)
  10808. })
  10809. .layoutWeight(1)
  10810. Blank()
  10811. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  10812. .selectedColor(this.themeColor)
  10813. .switchPointColor(Color.White)
  10814. .margin({ right: 15 })
  10815. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10816. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  10817. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  10818. if (more.id == 6) {
  10819. this.isMusicMemoryPlay = checked;
  10820. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  10821. if (this.isMusicMemoryPlay) {
  10822. ToastUtil.showToast('记忆播放已开启')
  10823. } else {
  10824. ToastUtil.showToast('记忆播放已关闭')
  10825. }
  10826. }
  10827. })
  10828. .width(48)
  10829. .height(24);
  10830. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  10831. .selectedColor(this.themeColor)
  10832. .switchPointColor(Color.White)
  10833. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10834. .margin({ right: 15 })
  10835. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  10836. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  10837. if (more.id == 7) {
  10838. this.isMusicBGCover = checked;
  10839. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  10840. if (this.isMusicBGCover) {
  10841. ToastUtil.showToast('播放背景随音乐封面已开启')
  10842. } else {
  10843. ToastUtil.showToast('播放背景随音乐封面已关闭')
  10844. }
  10845. }
  10846. })
  10847. .width(48)
  10848. .height(24);
  10849. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  10850. .selectedColor(this.themeColor)
  10851. .switchPointColor(Color.White)
  10852. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10853. .margin({ right: 15 })
  10854. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  10855. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  10856. if (more.id == 8) {
  10857. this.isSavePlayMode = checked;
  10858. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  10859. if (this.isSavePlayMode) {
  10860. ToastUtil.showToast('保存播放模式已开启')
  10861. } else {
  10862. ToastUtil.showToast('保存播放模式已关闭')
  10863. }
  10864. }
  10865. })
  10866. .width(48)
  10867. .height(24);
  10868. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  10869. .selectedColor(this.themeColor)
  10870. .switchPointColor(Color.White)
  10871. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10872. .margin({ right: 15 })
  10873. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  10874. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  10875. if (more.id == 13) {
  10876. this.isCoverRectangle = checked;
  10877. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  10878. if (this.isCoverRectangle) {
  10879. ToastUtil.showToast('封面方形已开启')
  10880. this.animationRoFun()
  10881. } else {
  10882. ToastUtil.showToast('封面圆形已开启')
  10883. this.animationRoFun()
  10884. }
  10885. }
  10886. })
  10887. .width(48)
  10888. .height(24);
  10889. Toggle({ type: ToggleType.Switch, isOn: this.isShowBgLiuGUANG })
  10890. .selectedColor(this.themeColor)
  10891. .switchPointColor(Color.White)
  10892. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10893. .margin({ right: 15 })
  10894. .visibility(more.id == 21 ? Visibility.Visible : Visibility.None)
  10895. .onChange((checked: boolean) => { // 是否开启背景流光效果
  10896. if (more.id == 21) {
  10897. this.isShowBgLiuGUANG = checked;
  10898. PreferencesUtil.putSync('isShowBgLiuGUANG',this.isShowBgLiuGUANG)
  10899. }
  10900. })
  10901. .width(48)
  10902. .height(24);
  10903. }
  10904. }
  10905. .width('100%')
  10906. .height(45)
  10907. .padding(15)
  10908. .backgroundColor(Color.Transparent)
  10909. .borderRadius(12)
  10910. .margin({ bottom: 6 })
  10911. }
  10912. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  10913. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  10914. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  10915. .backgroundColor(Color.Transparent)
  10916. .onClick(() => {
  10917. this.doMore(more.id)
  10918. })
  10919. });
  10920. }
  10921. .width('100%')
  10922. .padding(16)
  10923. }.margin({ bottom: 18 })
  10924. }
  10925. @Builder
  10926. TPImageBuilder(more: MoreItem): void {
  10927. Row() {
  10928. Image($r('app.media.tuoping'))
  10929. .width(22)
  10930. .height(22)
  10931. .margin({ left: 10, right: 10 })
  10932. Text(more.title)
  10933. .fontSize(16)
  10934. .fontColor(Color.White)
  10935. }
  10936. .width('100%')
  10937. .layoutWeight(1)
  10938. .alignItems(VerticalAlign.Center)
  10939. .justifyContent(FlexAlign.Start)
  10940. }
  10941. private moreItems: MoreItem[] = [
  10942. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  10943. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  10944. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  10945. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  10946. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  10947. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  10948. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  10949. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  10950. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  10951. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  10952. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  10953. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  10954. { id: 4, image: $r('app.media.share2'), title: '分享' },
  10955. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  10956. // { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  10957. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  10958. { id : 21, image: $r('app.media.music_red'), title: '开启背景流光' },
  10959. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  10960. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  10961. ];
  10962. @State isShowBgLiuGUANG: boolean = true;
  10963. @State isShowMoreView: boolean = false;
  10964. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  10965. @State isShowTimeCloseMore: boolean = false
  10966. @State isShowDetailMore: boolean = false
  10967. @State isMusicBGCover: boolean = true
  10968. @State isSavePlayMode: boolean = true
  10969. @State isLyricSetting: boolean = false
  10970. @State isJumpSetting: boolean = false
  10971. @State isShowEdit: boolean = false
  10972. @State showPipLyric: boolean = false
  10973. async setRingTone() {
  10974. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  10975. return
  10976. }
  10977. // 确定后的逻辑
  10978. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  10979. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  10980. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  10981. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  10982. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  10983. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  10984. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  10985. , this.videoUrl, this.name).then(res => {
  10986. LogUtil.info('onecold setFlag :' + res);
  10987. });
  10988. }
  10989. doMore(moreId: number) {
  10990. switch (moreId) {
  10991. case 2: //歌词
  10992. this.isLyricSetting = !this.isLyricSetting;
  10993. this.isShowMoreView = false
  10994. break;
  10995. case 3: //详情
  10996. this.isShowDetailMore = !this.isShowDetailMore;
  10997. break;
  10998. case 4: //分享
  10999. if (this.currentSong !== undefined) {
  11000. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  11001. }
  11002. this.isShowMoreView = false
  11003. break;
  11004. case 5: //定时关闭
  11005. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  11006. break;
  11007. case 10: //设为铃声
  11008. this.setRingTone()
  11009. this.isShowMoreView = false
  11010. break;
  11011. case 11: //跳过头尾
  11012. this.isJumpSetting = !this.isJumpSetting;
  11013. break;
  11014. case 13: //倍速
  11015. break;
  11016. case 14: //搜索封面
  11017. if (this.currentSong !== undefined) {
  11018. this.doSearchCover(this.currentSong)
  11019. }
  11020. this.isShowMoreView = false
  11021. break;
  11022. case 15: //编辑标签
  11023. this.initEditFields(this.currentSong)
  11024. this.tempLyricContent = this.lyricContent
  11025. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  11026. this.lyricConStr = this.tempLyricContent
  11027. }
  11028. this.isShowEdit = !this.isShowEdit;
  11029. break;
  11030. case 16: //悬浮歌词
  11031. this.showPipLyric = !this.showPipLyric;
  11032. break;
  11033. case 17: //横屏模式
  11034. if (this.isLandscape) {
  11035. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  11036. } else {
  11037. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  11038. }
  11039. this.isShowMoreView = false
  11040. break;
  11041. case 20://AB循环
  11042. this.isABSheet = !this.isABSheet
  11043. break;
  11044. }
  11045. }
  11046. //AB循环
  11047. @State isOpenAB:boolean = false
  11048. @State jumpATime:number = 0
  11049. @State jumpBTime:number = 0
  11050. @State isABSheet:boolean = false
  11051. @Builder
  11052. ABLoopSheet() {
  11053. ABLoopComptent({
  11054. jumpATime:this.jumpATime,
  11055. jumpBTime:this.jumpBTime,
  11056. onClickAItem: async ()=>{
  11057. if(this.mIjkMediaPlayer){
  11058. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  11059. }
  11060. },
  11061. onClickBItem: async ()=>{
  11062. if(this.mIjkMediaPlayer){
  11063. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  11064. if(this.jumpBTime<=this.jumpATime){
  11065. ToastUtil.showToast('设置B点时间不能小于A点时间')
  11066. this.jumpBTime = 0
  11067. }
  11068. }
  11069. },
  11070. onCancleButtonClick: async ()=>{
  11071. this.isOpenAB = false
  11072. this.isABSheet = false
  11073. },
  11074. onStartButtonClick: async ()=>{
  11075. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  11076. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  11077. return
  11078. }
  11079. this.isABSheet = false
  11080. this.startABLoop()
  11081. },
  11082. })
  11083. }
  11084. //开始AB循环
  11085. startABLoop(){
  11086. if(this.mIjkMediaPlayer){
  11087. this.seekTo(this.jumpATime+'')
  11088. this.isOpenAB = true
  11089. }
  11090. }
  11091. /**
  11092. * 切换横竖屏
  11093. *
  11094. */
  11095. setOrientation(orientation: number) {
  11096. this.windowClass.setPreferredOrientation(orientation).then(() => {
  11097. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  11098. }).catch((err: BusinessError) => {
  11099. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  11100. });
  11101. }
  11102. /**
  11103. * 画中画功能(悬浮歌词功能)
  11104. *
  11105. */
  11106. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  11107. pipController?: PiPWindow.PiPController;
  11108. navigationId: string = '';
  11109. @State curState: string = '';
  11110. @State curError: ResourceStr = '';
  11111. @State pipBg: string = '#E8E8E8'
  11112. @State buttonAction: string = '';
  11113. //开启画中画功能
  11114. async startPip() {
  11115. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  11116. if (!this.pipController) {
  11117. await this.createPipController();
  11118. }
  11119. if (!this.pipController) {
  11120. Logger.info(`[${TAG}] pipController create error`);
  11121. return;
  11122. }
  11123. await this.pipController.startPiP();
  11124. }
  11125. async stopPip() {
  11126. if (!this.pipController) {
  11127. Logger.info(`[${TAG}] pipController is not exist`);
  11128. return;
  11129. }
  11130. this.isOpenPip = false
  11131. await this.pipController.stopPiP();
  11132. }
  11133. async createPipController() {
  11134. this.pipController = await PiPWindow.create({
  11135. context: getContext(this),
  11136. componentController: this.xcomponentController,
  11137. navigationId: this.navigationId,
  11138. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  11139. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  11140. customUIController: this.nodeController,
  11141. });
  11142. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  11143. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  11144. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  11145. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  11146. this.onStateChange(state, reason);
  11147. });
  11148. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  11149. this.onActionEvent(event, status);
  11150. });
  11151. }
  11152. destroyPipController() {
  11153. if (!this.pipController) {
  11154. return;
  11155. }
  11156. this.pipController.off('stateChange');
  11157. this.pipController.off('controlPanelActionEvent');
  11158. this.pipController = undefined;
  11159. }
  11160. onStateChange(state: PiPWindow.PiPState, reason: string) {
  11161. switch (state) {
  11162. case PiPWindow.PiPState.ABOUT_TO_START:
  11163. this.curState = 'ABOUT_TO_START';
  11164. this.curError = $r('app.string.current_error_hint');
  11165. break;
  11166. case PiPWindow.PiPState.STARTED:
  11167. this.curState = 'STARTED';
  11168. this.curError = $r('app.string.current_error_hint');
  11169. break;
  11170. case PiPWindow.PiPState.ABOUT_TO_STOP:
  11171. this.curState = 'ABOUT_TO_STOP';
  11172. this.curError = $r('app.string.current_error_hint');
  11173. break;
  11174. case PiPWindow.PiPState.STOPPED:
  11175. this.curState = 'STOPPED';
  11176. this.curError = $r('app.string.current_error_hint');
  11177. this.stopPip()
  11178. this.destroyPipController()
  11179. break;
  11180. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  11181. this.curState = 'ABOUT_TO_RESTORE';
  11182. this.curError = $r('app.string.current_error_hint');
  11183. break;
  11184. case PiPWindow.PiPState.ERROR:
  11185. this.curState = 'ERROR';
  11186. this.curError = reason;
  11187. break;
  11188. default:
  11189. break;
  11190. }
  11191. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  11192. }
  11193. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  11194. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  11195. switch (event) {
  11196. case 'playbackStateChanged':
  11197. if (status === 0) {
  11198. this.pause();
  11199. } else {
  11200. console.info('onecold startPlayOrResumePlay 9869')
  11201. this.startPlayOrResumePlay();
  11202. }
  11203. break;
  11204. case 'nextVideo':
  11205. // 切换到下一个视频
  11206. this.playNext().catch(() => {
  11207. Logger.error('heanup onActionEvent playNext', `播放下一首失败`);
  11208. });
  11209. break;
  11210. case 'previousVideo':
  11211. // 切换到上一个视频
  11212. this.playPrevious().catch(() => {
  11213. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败`);
  11214. });
  11215. break;
  11216. case 'previousVideo':
  11217. // 切换到上一个视频
  11218. this.playPrevious().catch(() => {
  11219. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败:`);
  11220. });
  11221. break;
  11222. default:
  11223. }
  11224. this.buttonAction = event + `-status:${status}`;
  11225. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  11226. }
  11227. /**
  11228. * 画中画功能(悬浮歌词功能)结束
  11229. *
  11230. */
  11231. async doSearchCover(item: VideoItem): Promise<string> {
  11232. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  11233. this.isShowMoreView = false;
  11234. this.showTipsDialog();
  11235. return ''; // Return empty string when no API is configured
  11236. }
  11237. if (!item) {
  11238. return ''; // Return empty string if item is undefined
  11239. }
  11240. const artist = item?.artist || ''; // Use empty string if artist is missing
  11241. return this.searchCover(item, item.name, artist); // Await is not needed here as we return the promise directly
  11242. }
  11243. /**
  11244. *api搜索封面
  11245. *item,根据title和artist
  11246. */
  11247. searchCover(item: VideoItem, title: string, artist: string): Promise<string> {
  11248. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  11249. LogUtil.debug("onecold res =" + res);
  11250. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  11251. if (item.filePath == this.currentSong?.filePath) {
  11252. this.cover = res;
  11253. if (this.currentSong) {
  11254. this.currentSong.pixelMapPath = res;
  11255. }
  11256. }
  11257. // Update pixel map path but always return res regardless of success
  11258. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  11259. if (success) {
  11260. this.doUpdateData();
  11261. console.log("onecold 更新音乐封面成功,数据库已同步");
  11262. } else {
  11263. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  11264. }
  11265. // Note: We don't resolve/reject here because we already returned res
  11266. });
  11267. LogUtil.debug("onecold this.cover =" + this.cover);
  11268. }
  11269. return res; // Always return res regardless of updatePixelMapPath result
  11270. });
  11271. }
  11272. @State jumpTopTime: number = 0
  11273. @State jumpEndTime: number = 0
  11274. @State isOpenJump: boolean = false
  11275. @Builder
  11276. JumpTopEndSheet() {
  11277. Scroll() {
  11278. Column() {
  11279. Column() {
  11280. Text('仅对本播放列表有效')
  11281. .fontSize(16)
  11282. .fontColor($r('app.color.text_color'))
  11283. // 跳过头尾
  11284. Column() {
  11285. Row() {
  11286. Text('跳过片头:')
  11287. .fontSize(16)
  11288. .fontColor($r('app.color.text_color'))
  11289. Text(this.jumpTopTime + 's')
  11290. .fontSize(16)
  11291. .fontColor($r('app.color.text_color'))
  11292. }
  11293. .margin({ bottom: 5 })
  11294. Row() {
  11295. Slider({
  11296. value: this.jumpTopTime,
  11297. min: 0,
  11298. max: 120,
  11299. step: 1,
  11300. style: SliderStyle.OutSet
  11301. })
  11302. .blockColor(this.themeColor)
  11303. .trackColor($r('app.color.speed_text_color'))
  11304. .selectedColor(Color.White)
  11305. .trackThickness(8)
  11306. .onChange((value: number) => {
  11307. this.jumpTopTime = value;
  11308. })
  11309. .width('85%')
  11310. }
  11311. .alignItems(VerticalAlign.Top)
  11312. }
  11313. .margin({ top: 10, bottom: 10 })
  11314. // 跳过头尾
  11315. Column() {
  11316. Row() {
  11317. Text('跳过片尾:')
  11318. .fontSize(16)
  11319. .fontColor($r('app.color.text_color'))
  11320. Text(this.jumpEndTime + 's')
  11321. .fontSize(16)
  11322. .fontColor($r('app.color.text_color'))
  11323. }
  11324. .margin({ bottom: 5 })
  11325. Row() {
  11326. Slider({
  11327. value: this.jumpEndTime,
  11328. min: 0,
  11329. max: 120,
  11330. step: 1,
  11331. style: SliderStyle.OutSet
  11332. })
  11333. .blockColor(this.themeColor)
  11334. .trackColor($r('app.color.speed_text_color'))
  11335. .selectedColor(Color.White)
  11336. .trackThickness(8)
  11337. .onChange((value: number) => {
  11338. this.jumpEndTime = value;
  11339. })
  11340. .width('85%')
  11341. }
  11342. .alignItems(VerticalAlign.Top)
  11343. }
  11344. .margin({ top: 10, bottom: 10 })
  11345. Row() {
  11346. Button('保存设置')
  11347. .fontColor(Color.White)
  11348. .layoutWeight(1)
  11349. .height(40)
  11350. .width(80)
  11351. .backgroundColor(this.themeColor)
  11352. .stateEffect(true)
  11353. .margin({ left: 0, bottom: 20 })
  11354. .onClick(async () => {
  11355. if (!Utility.isNoble()) {
  11356. this.isJumpSetting = false
  11357. this.isShowMoreView = false
  11358. this.showVipDialog()
  11359. return
  11360. }
  11361. if (this.currentSong === undefined) {
  11362. return
  11363. }
  11364. if (this.modeType === 0) {
  11365. let parentPath = FileUtil.getParentPath(this.videoUrl)
  11366. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  11367. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  11368. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  11369. } else if (this.modeType === 1) { //媒体库
  11370. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  11371. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  11372. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  11373. } else if (this.modeType === 2) { //艺术家
  11374. if (this.currentSong?.artist) {
  11375. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  11376. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  11377. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  11378. }
  11379. } else if (this.modeType === 3) { //专辑
  11380. if (this.currentSong?.album) {
  11381. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  11382. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  11383. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  11384. }
  11385. }
  11386. ToastUtil.showShort("保存成功")
  11387. this.isJumpSetting = false
  11388. })
  11389. }
  11390. .margin({
  11391. left: 38,
  11392. right: 38,
  11393. top: 10,
  11394. bottom: 10
  11395. })
  11396. .width(120)
  11397. .height(50)
  11398. }
  11399. }
  11400. }
  11401. .width('100%')
  11402. .height('100%')
  11403. }
  11404. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  11405. private onStateVastChange(state: AVCastPickerState) {
  11406. if (state == AVCastPickerState.STATE_APPEARING) {
  11407. console.log('The picker starts showing.');
  11408. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  11409. console.log('The picker finishes presenting.');
  11410. }
  11411. }
  11412. private showSelectLyric() {
  11413. DialogHelper.showActionSheetDialog({
  11414. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  11415. // sheets: ["本地歌词", "搜索歌词"],
  11416. sheets: [
  11417. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  11418. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  11419. ],
  11420. maskColor: Color.Transparent,
  11421. backgroundColor: $r('app.color.bg_card'),
  11422. transition: AnimationHelper.transitionInDown(666),
  11423. onAction: (index) => {
  11424. switch (index) {
  11425. case 0:
  11426. this.callFilePickerSelectFileForLyric()
  11427. break;
  11428. case 1:
  11429. if (StrUtil.isNotEmpty(this.videoUrl)) {
  11430. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  11431. this.initLyric(lyricPath);
  11432. }
  11433. break;
  11434. }
  11435. }
  11436. })
  11437. }
  11438. // 拉起picker选择文件管理器
  11439. async callFilePickerSelectFileForLyric(): Promise<void> {
  11440. try {
  11441. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  11442. DocumentSelectOptions.maxSelectNumber = 1
  11443. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  11444. let documentPicker = new picker.DocumentViewPicker();
  11445. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  11446. Logger.info(TAG,
  11447. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  11448. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  11449. this.saveVideoDatasLyric(DocumentSelectResult)
  11450. }
  11451. }).catch((err: BusinessError) => {
  11452. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  11453. });
  11454. } catch (err) {
  11455. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  11456. }
  11457. }
  11458. async saveVideoDatasLyric(uris: string[]) {
  11459. if (ArrayUtil.isEmpty(uris)) {
  11460. return
  11461. }
  11462. let newUris: string[] = [];
  11463. for (let i = 0; i < uris.length; i++) {
  11464. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  11465. Logger.info(TAG, 'filePath uri: ' + filePath);
  11466. newUris.push(filePath)
  11467. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  11468. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  11469. fileIo.copyFileSync(file.fd, file2.fd)
  11470. fileIo.closeSync(file);
  11471. fileIo.closeSync(file2);
  11472. this.initLyric(filePath,false,false,true)
  11473. }
  11474. }
  11475. private initDelayPlay(context: object) {
  11476. this.mContext = context;
  11477. }
  11478. startPipLyric() {
  11479. if (this.pipController) {
  11480. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  11481. PiPWindow.PiPControlStatus.PLAY);
  11482. }
  11483. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  11484. if (this.isOpenPip) {
  11485. this.startPip()
  11486. } else {
  11487. this.stopPip()
  11488. }
  11489. }
  11490. //startOffset 从cue分轨时间开始播
  11491. private startPlayOrResumePlay(startOffset?:number) {
  11492. //针对dsf文件高采样率,统一转wav播放
  11493. const sampleRate = this.currentSong?.sampleRate||0
  11494. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  11495. console.info('onecold 采样率 ='+sampleRate)
  11496. let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  11497. console.info('onecold newDsfPath ='+newDsfPath)
  11498. if(!FileUtil.accessSync(newDsfPath)){
  11499. const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  11500. taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  11501. this.videoUrl = newDsfPath
  11502. this.startPlay(startOffset)
  11503. }).catch((e:object)=>{
  11504. console.info("task1 catch e: " + e);
  11505. })
  11506. }else{
  11507. this.videoUrl = newDsfPath
  11508. this.startPlay(startOffset)
  11509. }
  11510. }else{
  11511. this.startPlay(startOffset)
  11512. }
  11513. }
  11514. startPlay(startOffset?:number) {
  11515. this.startPipLyric()
  11516. this.mDestroyPage = false;
  11517. this.animationState = AnimationStatus.Running
  11518. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  11519. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  11520. this.stopProgressTask();
  11521. this.startProgressTask();
  11522. this.play(this.videoUrl.toString(),startOffset);
  11523. }
  11524. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  11525. this.mIjkMediaPlayer.start();
  11526. this.setProgress()
  11527. this.CONTROL_PlayStatus = PlayStatus.PLAY
  11528. }
  11529. this.setIsPlaying(true)
  11530. this.updateSessionPlayState(true)
  11531. this.watchStatus();
  11532. this.updateLastPlayTimeStr(this.videoUrl)
  11533. }
  11534. updateLastPlayTimeStr(filePath: string) {
  11535. // 检查是否为网络音频(WebDAV),如果是则不更新本地数据库
  11536. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  11537. Logger.info(`heanup 检测到网络音频播放,跳过数据库更新: ${filePath}`)
  11538. return;
  11539. }
  11540. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  11541. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  11542. if (success) {
  11543. this.getHistoryList(false)
  11544. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  11545. } else {
  11546. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  11547. }
  11548. });
  11549. }
  11550. private completionNum(num: number): string | number {
  11551. if (num < 10) {
  11552. return '0' + num;
  11553. } else {
  11554. return num;
  11555. }
  11556. }
  11557. private stringForTime(timeMs: number): string {
  11558. let totalSeconds: number | string = (timeMs / 1000);
  11559. let newSeconds: number | string = totalSeconds % 60;
  11560. let minutes: number | string = (totalSeconds / 60) % 60;
  11561. let hours: number | string = totalSeconds / 3600;
  11562. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  11563. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  11564. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  11565. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  11566. if (this.isCurrentTime) {
  11567. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  11568. this.oldSeconds = newSeconds
  11569. } else {
  11570. newSeconds = this.oldSeconds
  11571. }
  11572. }
  11573. newSeconds = this.completionNum(newSeconds);
  11574. if (hours > 0) {
  11575. return hours + ":" + minutes + ":" + newSeconds;
  11576. } else {
  11577. return minutes + ":" + newSeconds;
  11578. }
  11579. }
  11580. private setProgress() {
  11581. let position = this.mIjkMediaPlayer.getCurrentPosition();
  11582. let duration = this.mIjkMediaPlayer.getDuration();
  11583. let pos = 0;
  11584. if (duration > 0) {
  11585. this.slideEnable = true;
  11586. let curPercent = position / duration;
  11587. pos = curPercent * 100;
  11588. if (pos > this.PROGRESS_MAX_VALUE) {
  11589. this.progressValue = this.PROGRESS_MAX_VALUE
  11590. } else {
  11591. this.progressValue = pos;
  11592. }
  11593. }
  11594. // LogUtils.getInstance()
  11595. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  11596. this.totalTime = this.stringForTime(duration);
  11597. if (position > duration) {
  11598. position = duration;
  11599. }
  11600. this.isCurrentTime = true;
  11601. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  11602. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  11603. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  11604. this.currentTime = this.stringForTime(position);
  11605. this.isCurrentTime = false
  11606. if (this.mIjkMediaPlayer.isPlaying()) {
  11607. this.randomColor =
  11608. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  11609. //如果是开启AB循环
  11610. if(this.isOpenAB){
  11611. if(position >=this.jumpBTime){
  11612. this.seekTo(this.jumpATime+'')
  11613. return
  11614. }
  11615. }
  11616. // 判断是否播放到结束时间
  11617. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  11618. if (position >= duration - this.jumpEndTime * 1000) {
  11619. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  11620. this.CONTROL_PlayStatus = PlayStatus.INIT
  11621. this.startPlayOrResumePlay();
  11622. }else if (this.playType == 2) { //2:正常播放,单曲播完
  11623. this.showRePlay();
  11624. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  11625. this.progressValue = this.PROGRESS_MAX_VALUE;
  11626. this.slideEnable = false;
  11627. this.stop();
  11628. // ToastUtil.showToast('开始重新播放')
  11629. }else{
  11630. this.playNext().catch(() => {
  11631. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  11632. });
  11633. }
  11634. }
  11635. }
  11636. } else {
  11637. this.randomColor = 'rbg(0,0,0)'
  11638. }
  11639. }
  11640. private startProgressTask() {
  11641. let that = this;
  11642. this.updateProgressTimer = setInterval(() => {
  11643. //LogUtils.getInstance().LOGI("startProgressTask");
  11644. if (!that.mDestroyPage) {
  11645. that.setProgress();
  11646. }
  11647. }, 300);
  11648. }
  11649. private stopProgressTask() {
  11650. LogUtils.getInstance().LOGI("stopProgressTask");
  11651. clearInterval(this.updateProgressTimer);
  11652. }
  11653. private showLoadIng() {
  11654. this.loadingVisible = Visibility.Visible;
  11655. this.replayVisible = Visibility.None;
  11656. }
  11657. private hideLoadIng() {
  11658. this.loadingVisible = Visibility.None;
  11659. this.replayVisible = Visibility.None;
  11660. }
  11661. private showRePlay() {
  11662. this.loadingVisible = Visibility.None;
  11663. this.replayVisible = Visibility.Visible;
  11664. }
  11665. private async play(url: string,startOffset?:number) {
  11666. this.isShowBgLiuGUANG = PreferencesUtil.getBooleanSync('isShowBgLiuGUANG', true)
  11667. console.info('onecold this.url 1= '+url)
  11668. if(!url.toLowerCase().startsWith('http')){
  11669. let hasPermission = await PermissionUtil.activatePermission(url)
  11670. console.info('onecold this.hasPermission 1= '+hasPermission)
  11671. if(!url.includes(this.packName)){
  11672. const file = fs.openSync(url)
  11673. this.videoUrl = file.path
  11674. url= this.videoUrl
  11675. }
  11676. console.info('onecold this.hasPermission 1= '+hasPermission)
  11677. console.info('onecold this.videoUrl 1= '+this.videoUrl)
  11678. }
  11679. let that = this;
  11680. that.showLoadIng();
  11681. this.isOpenAB = false
  11682. //设置XComponent回调的context
  11683. if (!!this.mContext) {
  11684. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  11685. }
  11686. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  11687. this.mIjkMediaPlayer.reset();
  11688. }
  11689. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  11690. //设置debug模式
  11691. this.mIjkMediaPlayer.setDebug(false);
  11692. //初始化配置
  11693. this.mIjkMediaPlayer.native_setup();
  11694. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  11695. if(this.volumeSmall){
  11696. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  11697. this.mIjkMediaPlayer.setVolume('1', '1');
  11698. }else{
  11699. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  11700. }
  11701. }else{
  11702. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  11703. }
  11704. //设置视频源
  11705. this.mIjkMediaPlayer.setDataSource(url);
  11706. // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
  11707. const headers = new Map<string, string>();
  11708. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  11709. headers.set("Accept", "*/*");
  11710. if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
  11711. &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
  11712. //如果封面为空,则搜索封面
  11713. this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
  11714. }
  11715. // 如果是WebDAV网络音频,使用webdav_account_id获取认证信息(等待完成后再设置一次性头部)
  11716. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  11717. Logger.info(`heanup WebDAV歌曲认证 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
  11718. if (this.currentSong.webdav_account_id) {
  11719. try {
  11720. const webdavManager = RemoteDriveManager.getInstance();
  11721. const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  11722. if (webDavHeaders && webDavHeaders.size > 0) {
  11723. webDavHeaders.forEach((value, key) => headers.set(key, value));
  11724. Logger.info(`heanup 成功通过webdav_account_id获取并合并WebDAV认证头`);
  11725. } else {
  11726. Logger.warn(`heanup 通过webdav_account_id获取认证头失败,播放可能无法继续`);
  11727. }
  11728. } catch (error) {
  11729. const err = error as Error;
  11730. Logger.error(`heanup 获取WebDAV认证头时出错: ${err.message}`);
  11731. }
  11732. } else {
  11733. Logger.error(`heanup WebDAV歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法进行认证`);
  11734. }
  11735. }
  11736. // 统一设置带认证的请求头
  11737. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  11738. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  11739. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  11740. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  11741. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  11742. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  11743. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  11744. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  11745. // 缓冲和播放优化设置
  11746. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  11747. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  11748. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1"); // 预加载启动
  11749. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  11750. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  11751. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  11752. // 网络相关设置
  11753. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  11754. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  11755. // 重连设置
  11756. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  11757. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  11758. }
  11759. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  11760. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  11761. // }
  11762. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  11763. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  11764. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  11765. const fileSize = await this.getFileSize(this.videoUrl);
  11766. let bufferSize = 1 * 1024 ; // 默认缓冲区大小为1MB
  11767. if (fileSize > 3 * 1024 * 1024 * 1024) { // 文件大于3GB
  11768. bufferSize = 25 * 1024 * 1024; // 设置缓冲区大小为25MB
  11769. }
  11770. // 使用软件解码(通常比硬件解码更节省内存)
  11771. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", '0');
  11772. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", '0');
  11773. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", '1024');
  11774. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzeduration", '500000');
  11775. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  11776. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  11777. //停止预读的最小帧数
  11778. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  11779. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  11780. // 设置其他缓冲相关选项
  11781. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  11782. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  11783. //启动预加载
  11784. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  11785. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  11786. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  11787. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  11788. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  11789. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  11790. // 因此需要播放器丢包,才不会累积延时
  11791. // 这个和第三个参数packet-buffering无关。
  11792. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  11793. // 无限制收流
  11794. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  11795. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  11796. // 屏幕常亮
  11797. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  11798. // 设置超时
  11799. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  11800. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  11801. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  11802. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  11803. // 变速播放
  11804. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  11805. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  11806. let Speed = this.mIjkMediaPlayer.getSpeed()
  11807. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  11808. //是否开启循环播放
  11809. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  11810. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  11811. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  11812. if (height === 0) {
  11813. return;
  11814. }
  11815. const va = width / height;
  11816. const vpa = that.videoParentAspectRatio;
  11817. if (vpa > va) {
  11818. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  11819. } else {
  11820. that.videoWidth = '100%';
  11821. }
  11822. if (width && height) {
  11823. that.videoAspectRatio = width / height;
  11824. }
  11825. LogUtils.getInstance()
  11826. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  11827. that.hideLoadIng();
  11828. }
  11829. }
  11830. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  11831. let mOnPreparedListener: OnPreparedListener = {
  11832. onPrepared: async () => {
  11833. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  11834. try {
  11835. //保存碰一碰分享的当前的歌曲
  11836. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  11837. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  11838. await this.initLyric(lyricPath);
  11839. setTimeout(() => {
  11840. this.avSessionController.initAvSession(false);
  11841. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  11842. this.setAvSessionListener();
  11843. this.updateSessionPlayState(true)
  11844. this.setCurrentPlayMode()
  11845. }, 500)
  11846. if(startOffset&&startOffset>0){//cue分轨播放
  11847. this.seekTo(startOffset + "");
  11848. this.saveLastPlayList()
  11849. return
  11850. }
  11851. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  11852. let timeoutPlay = 0
  11853. if (StrUtil.isNotEmpty(this.videoUrl) &&
  11854. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  11855. timeoutPlay = 1000
  11856. }
  11857. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  11858. if (this.modeType === 0) { //文件夹
  11859. let parentPath = FileUtil.getParentPath(this.videoUrl)
  11860. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  11861. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  11862. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  11863. } else if (this.modeType === 1) { //媒体库
  11864. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  11865. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  11866. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  11867. } else if (this.modeType === 2) { //艺术家
  11868. if (this.currentSong?.artist) {
  11869. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  11870. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  11871. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  11872. }
  11873. } else if (this.modeType === 3) { //专辑
  11874. if (this.currentSong?.album) {
  11875. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  11876. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  11877. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  11878. }
  11879. }
  11880. this.duration = this.mIjkMediaPlayer.getDuration()
  11881. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  11882. if (this.mIjkMediaPlayer != null) {
  11883. let jumpTopTimeMs = this.jumpTopTime*1000;
  11884. if (jumpTopTimeMs <= this.duration) {
  11885. // 调用 seekTo 方法,跳到指定时间
  11886. if(PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY,true)){
  11887. console.log('onecold jumpTopTime = '+jumpTopTimeMs);
  11888. const position:number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  11889. console.log('onecold position = '+position);
  11890. if (position > jumpTopTimeMs) {
  11891. jumpTopTimeMs = position
  11892. }
  11893. }
  11894. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  11895. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  11896. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  11897. }
  11898. }, timeoutPlay)
  11899. } else {
  11900. // 提示用户无法跳过
  11901. ToastUtil.showToast('跳过时间超过视频时长');
  11902. }
  11903. }
  11904. } else {
  11905. this.jumpTopTime = 0
  11906. this.jumpEndTime = 0
  11907. console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  11908. console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  11909. console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  11910. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  11911. //记忆播放(每一首都会记忆播放)
  11912. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  11913. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  11914. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  11915. this.restorePlaybackPosition() //读取播放记忆功能
  11916. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  11917. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  11918. this.restorePlaybackPosition() //读取播放记忆功能
  11919. }
  11920. this.isFirstStartPlay = false
  11921. }, timeoutPlay)
  11922. } else {
  11923. this.isFirstStartPlay = false
  11924. }
  11925. }
  11926. this.saveLastPlayList()
  11927. } catch (error) {
  11928. let err: BusinessError = error as BusinessError;
  11929. console.error('onecold failed with err: ' + JSON.stringify(err));
  11930. }
  11931. }
  11932. }
  11933. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  11934. let mOnTimedTextListener: OnTimedTextListener = {
  11935. onTimedText: () => {
  11936. }
  11937. }
  11938. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  11939. let mOnCompletionListener: OnCompletionListener = {
  11940. onCompletion: () => {
  11941. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  11942. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  11943. // 异步调用playNext
  11944. this.playNext().catch(() => {
  11945. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  11946. });
  11947. } else if (this.playType == 1) { //1:单片重复播放
  11948. this.CONTROL_PlayStatus = PlayStatus.INIT
  11949. that.startPlayOrResumePlay();
  11950. } else if (this.playType == 2) { //2:正常播放,单曲播完
  11951. that.showRePlay();
  11952. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  11953. that.progressValue = this.PROGRESS_MAX_VALUE;
  11954. that.slideEnable = false;
  11955. that.stop();
  11956. // ToastUtil.showToast('开始重新播放')
  11957. } else if (this.playType == 3) { //3:随机播放
  11958. // 异步调用randomPlay
  11959. this.randomPlay().catch(() => {
  11960. Logger.error('heanup OnCompletionListener randomPlay', `随机播放失败`);
  11961. });
  11962. }
  11963. }
  11964. }
  11965. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  11966. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  11967. onBufferingUpdate: (percent: number) => {
  11968. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  11969. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  11970. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  11971. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  11972. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  11973. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  11974. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  11975. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  11976. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  11977. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  11978. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  11979. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  11980. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  11981. let Looping = this.mIjkMediaPlayer.isLooping()
  11982. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  11983. }
  11984. }
  11985. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  11986. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  11987. onSeekComplete: () => {
  11988. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  11989. console.info('onecold startPlayOrResumePlay 10643')
  11990. that.startPlayOrResumePlay();
  11991. }
  11992. }
  11993. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  11994. let mOnInfoListener: OnInfoListener = {
  11995. onInfo: (what: number, extra: number) => {
  11996. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  11997. that.hideLoadIng();
  11998. }
  11999. }
  12000. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  12001. let mOnErrorListener: OnErrorListener = {
  12002. onError: (what: number, extra: number) => {
  12003. this.stopProgressTask();
  12004. LogUtils.getInstance().LOGI("heanup OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  12005. LogUtils.getInstance().LOGI('heanup 播放错误,歌曲详情:' + JSON.stringify(this.currentSong))
  12006. // 检查是否为WebDAV播放错误
  12007. let isWebDavError = false;
  12008. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.currentSong.filePath) {
  12009. try {
  12010. const globalContext = GlobalContext.getContext();
  12011. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  12012. if (webDavAuthInfo) {
  12013. isWebDavError = true;
  12014. }
  12015. } catch (error) {
  12016. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  12017. }
  12018. }
  12019. if (isWebDavError) {
  12020. Logger.error(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  12021. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  12022. // this.currentWebDavAuthInfo = null;
  12023. Logger.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  12024. // 根据错误代码提供更具体的错误信息
  12025. let errorMessage = "WebDAV播放失败";
  12026. if (what === -1) { // 网络错误
  12027. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  12028. } else if (what === -1004) { // HTTP 404
  12029. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  12030. } else if (what === -1001) { // 超时
  12031. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  12032. } else if (what === -1003) { // 无法解析主机
  12033. errorMessage = "无法连接到WebDAV服务器";
  12034. }
  12035. ToastUtil.showToast(errorMessage);
  12036. } else {
  12037. if (StrUtil.isNotEmpty(this.videoUrl) &&
  12038. !this.videoUrl.startsWith('http://') &&
  12039. !this.videoUrl.startsWith('https://') &&
  12040. !FileUtil.accessSync(this.videoUrl)) {
  12041. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  12042. } else {
  12043. ToastUtil.showToast(getContext()
  12044. .resourceManager
  12045. .getStringByNameSync("Honey_the_video_is_playing_errant_The_system_is_wandering"))
  12046. }
  12047. }
  12048. that.hideLoadIng();
  12049. }
  12050. }
  12051. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  12052. this.mIjkMediaPlayer.setMessageListener();
  12053. this.mIjkMediaPlayer.prepareAsync();
  12054. this.mIjkMediaPlayer.start();
  12055. }
  12056. //保存最后播放的那首歌和已经对应的播放列表
  12057. saveLastPlayList() {
  12058. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  12059. PreferencesUtil.putSync('LastMusicList', this.songList)
  12060. }
  12061. // 清空播放记录
  12062. clearVideoHistory() {
  12063. this.table.clearPlayHistory((success: boolean, error?: string) => {
  12064. if (success) {
  12065. this.historyList = [];
  12066. this.updateListData(this.historyList)
  12067. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  12068. ToastUtil.showToast('清空播放记录成功')
  12069. } else {
  12070. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  12071. }
  12072. });
  12073. }
  12074. public async setAvSessionListener() {
  12075. if (!this.avSessionController) {
  12076. return;
  12077. }
  12078. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  12079. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  12080. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  12081. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  12082. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  12083. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  12084. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  12085. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  12086. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  12087. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  12088. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  12089. }
  12090. setLoopMode() {
  12091. let itype = this.playType + 1
  12092. if (itype >= 4) {
  12093. this.playType = 0
  12094. ToastUtil.showToast('连续播放')
  12095. } else if (itype === 1) {
  12096. this.playType = 1
  12097. ToastUtil.showToast('单曲循环')
  12098. } else if (itype === 2) {
  12099. this.playType = 2
  12100. ToastUtil.showToast('单曲播完')
  12101. } else if (itype === 3) {
  12102. this.playType = 3
  12103. ToastUtil.showToast('随机播放')
  12104. } else if (itype === 0) {
  12105. this.playType = 0
  12106. ToastUtil.showToast('连续播放')
  12107. }
  12108. PreferencesUtil.putSync('musicPlayType', this.playType)
  12109. this.setCurrentPlayMode()
  12110. }
  12111. private sessionSetLoopModeCallback = (mode: number) => {
  12112. if (this.mIjkMediaPlayer != null) {
  12113. ToastUtil.showToast('当前播放模式:' + mode)
  12114. Logger.info('onecold 当前播放模式= ' + mode)
  12115. let hmPlayMode = mode + 1
  12116. if (hmPlayMode >= 4) {
  12117. hmPlayMode = 0
  12118. }
  12119. if (hmPlayMode === 1) {
  12120. this.playType = 1
  12121. ToastUtil.showToast('单曲循环')
  12122. } else if (hmPlayMode === 0) {
  12123. this.playType = 2
  12124. ToastUtil.showToast('单曲播完')
  12125. } else if (hmPlayMode === 3) {
  12126. this.playType = 3
  12127. ToastUtil.showToast('随机播放')
  12128. } else if (hmPlayMode === 2) {
  12129. this.playType = 0
  12130. ToastUtil.showToast('连续播放')
  12131. }
  12132. PreferencesUtil.putSync('musicPlayType', this.playType)
  12133. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  12134. let playBackState: avSession.AVPlaybackState = {
  12135. loopMode: hmPlayMode,
  12136. };
  12137. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  12138. console.info(`set setLoopMode AVPlaybackState successfully`);
  12139. }).catch((err: BusinessError) => {
  12140. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  12141. });
  12142. }
  12143. }
  12144. setCurrentPlayMode() {
  12145. if (!this.avSessionController) {
  12146. return;
  12147. }
  12148. let mLoopMode = 0
  12149. switch (this.playType) {
  12150. case 0:
  12151. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  12152. break;
  12153. case 1:
  12154. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  12155. break;
  12156. case 2:
  12157. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  12158. break;
  12159. case 3:
  12160. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  12161. break;
  12162. }
  12163. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  12164. let playBState: avSession.AVPlaybackState = {
  12165. loopMode: mLoopMode,
  12166. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  12167. };
  12168. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  12169. console.info(`set setLoopMode AVPlaybackState successfully`);
  12170. }).catch((err: BusinessError) => {
  12171. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  12172. });
  12173. }
  12174. private sessionToggleFavoriteCallback = (assetId: string) => {
  12175. if (this.mIjkMediaPlayer != null && this.currentSong) {
  12176. console.info(`on toggleFavorite `);
  12177. // 应用收到收藏命令,进行收藏处理。
  12178. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  12179. this.doFav(this.currentSong)
  12180. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  12181. let playbackState: avSession.AVPlaybackState = {
  12182. isFavorite: !this.isFac,
  12183. };
  12184. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  12185. console.info(`SetAVPlaybackState successfully`);
  12186. }).catch((err: BusinessError) => {
  12187. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  12188. });
  12189. }
  12190. }
  12191. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  12192. device: avSession.OutputDeviceInfo) => {
  12193. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  12194. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  12195. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  12196. await this.startCasting();
  12197. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  12198. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  12199. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  12200. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  12201. if (device) {
  12202. this.endCasting();
  12203. }
  12204. }
  12205. };
  12206. private async startCasting() {
  12207. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  12208. this.setPlaybackStateChangeListener();
  12209. this.pause();
  12210. this.initQueueItem();
  12211. this.prepare();
  12212. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  12213. refToIsCasting?.set(true);
  12214. this.castSeek = true;
  12215. this.isCastPlaying = true;
  12216. }
  12217. async changeCasting() {
  12218. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  12219. this.initQueueItem();
  12220. this.prepare();
  12221. this.setPlaybackStateChangeListener();
  12222. this.isCastPlaying = true;
  12223. this.castSeek = true;
  12224. }
  12225. public endCasting() {
  12226. this.avSessionController.getAvSession()?.stopCasting();
  12227. this.stopCast();
  12228. this.isCastPlaying = false;
  12229. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  12230. refToIsCasting?.set(false);
  12231. this.pause();
  12232. this.setIsPlaying(false);
  12233. // if (this.curIndex === this.curSource.index) {
  12234. // this.play
  12235. // this.seek(this.currentTime * 1000);
  12236. // this.setIsPlaying(true);
  12237. // } else {
  12238. // this.pauseVideo();
  12239. // this.setIsPlaying(false);
  12240. // }
  12241. }
  12242. public setIsPlaying(isPlayer: boolean) {
  12243. this.isPlaying = isPlayer;
  12244. // 发送播放状态变化事件给歌单详情页面
  12245. try {
  12246. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  12247. const currentFilePath = this.currentSong?.filePath || ''
  12248. const eventData: emitter.EventData = {
  12249. data: {
  12250. isPlaying: this.isPlaying,
  12251. curIndex: this.curIndex,
  12252. currentFilePath: currentFilePath
  12253. }
  12254. };
  12255. emitter.emit(eventPlaybackStatus, eventData)
  12256. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  12257. } catch (error) {
  12258. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  12259. }
  12260. }
  12261. private setPlaybackStateChangeListener(): void {
  12262. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  12263. this.castController?.on('endOfStream', this.reloadCasting);
  12264. this.castController?.on('playNext', this.playNextCallback);
  12265. this.castController?.on('playPrevious', this.playPreviousCallback);
  12266. }
  12267. private updateSessionPlayState(isPlay: boolean): void {
  12268. // if(!this.isBgPlayOpen)
  12269. // return
  12270. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  12271. this.setAVSessionPlayState({
  12272. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  12273. position: {
  12274. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  12275. updateTime: new Date().getTime()
  12276. }
  12277. });
  12278. }
  12279. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  12280. this.avSessionController.setAvSessionPlayState(playbackState)
  12281. }
  12282. private positionChange(position: number) {
  12283. this.currentTime2 = position / 1000;
  12284. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  12285. }
  12286. private playDurationChange(duration: number) {
  12287. this.duration = duration;
  12288. this.durationTime = Math.floor(this.duration / 1000);
  12289. this.durationStringTime = secondToTime((this.durationTime));
  12290. }
  12291. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  12292. const duration = playbackState?.extras?.duration;
  12293. if (typeof duration === 'number') {
  12294. this.playDurationChange(duration as number);
  12295. }
  12296. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  12297. this.positionChange(playbackState?.position?.elapsedTime);
  12298. }
  12299. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  12300. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  12301. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  12302. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  12303. this.isCastPlaying = false;
  12304. }
  12305. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  12306. this.isCastPlaying = true;
  12307. }
  12308. };
  12309. private reloadCasting = async () => {
  12310. let item = this.songList[this.curIndex];
  12311. let uri = fileUri.getUriFromPath(item.filePath);
  12312. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  12313. // description.startPosition = 0;
  12314. this.castItem = {
  12315. itemId: this.curIndex,
  12316. description: {
  12317. assetId: item.filePath,
  12318. title: item.name,
  12319. artist: '',
  12320. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  12321. // mediaUri: item.filePath,
  12322. fdSrc: {
  12323. fd: file.fd
  12324. },
  12325. // 该字段大写,音频'AUDIO',视频'VIDEO'
  12326. mediaType: 'VIDEO',
  12327. mediaSize: item.videoSize,
  12328. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  12329. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  12330. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  12331. duration: this.duration,
  12332. // albumCoverUri: 'https://www.example.jpeg',
  12333. // albumTitle: '《ExampleAlbum》',
  12334. appName: this.appName,
  12335. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  12336. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  12337. }
  12338. };
  12339. this.prepare();
  12340. this.isCastPlaying = true;
  12341. };
  12342. public playNextCallback = (): void => {
  12343. this.playNext().catch(() => {
  12344. Logger.error('heanup playNextCallback', `播放下一首失败`);
  12345. });
  12346. };
  12347. public playPreviousCallback = (): void => {
  12348. this.playPrevious().catch(() => {
  12349. Logger.error('heanup playNextCallback', `播放上一首失败`);
  12350. });
  12351. };
  12352. async prepare() {
  12353. await this.castController?.prepare(this.castItem);
  12354. await this.castController?.start(this.castItem);
  12355. }
  12356. public initQueueItem() {
  12357. let item = this.songList[this.curIndex];
  12358. let time = this.currentTime;
  12359. let uri = fileUri.getUriFromPath(item.filePath);
  12360. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  12361. this.castItem = {
  12362. itemId: this.curIndex,
  12363. description: {
  12364. assetId: item.filePath,
  12365. title: item.name,
  12366. artist: '',
  12367. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  12368. fdSrc: {
  12369. fd: file.fd
  12370. },
  12371. // 该字段大写,音频'AUDIO',视频'VIDEO'
  12372. mediaType: 'AUDIO',
  12373. mediaSize: item.videoSize,
  12374. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  12375. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  12376. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  12377. duration: this.duration,
  12378. // albumCoverUri: 'https://www.example.jpeg',
  12379. // albumTitle: '《ExampleAlbum》',
  12380. appName: this.appName,
  12381. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  12382. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  12383. }
  12384. };
  12385. }
  12386. async stopCast() {
  12387. try {
  12388. this.castController?.off('playbackStateChange');
  12389. this.castController?.off('endOfStream');
  12390. this.castController?.off('playNext');
  12391. this.castController?.off('playPrevious');
  12392. this.castController?.off('error');
  12393. } catch (error) {
  12394. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  12395. }
  12396. }
  12397. private sessionPlayCallback = (): void => {
  12398. this.playOrPause()
  12399. };
  12400. private sessionPauseCallback = (): void => {
  12401. this.pause()
  12402. };
  12403. private playOrPause() {
  12404. if (!this.debounce()) {
  12405. return;
  12406. }
  12407. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  12408. this.pause();
  12409. } else {
  12410. console.info('onecold startPlayOrResumePlay 11064')
  12411. this.startPlayOrResumePlay();
  12412. this.playChange()
  12413. }
  12414. }
  12415. private sessionPlayNextCallback = (): void => {
  12416. this.playNext().catch(() => {
  12417. Logger.error('heanup sessionPlayPreviousCallback', `播放下 一首失败`);
  12418. });
  12419. };
  12420. private sessionPlayPreviousCallback = (): void => {
  12421. this.playPrevious().catch(() => {
  12422. Logger.error('heanup sessionPlayPreviousCallback', `播放上一首失败`);
  12423. });
  12424. };
  12425. private sessionStopCallback = (): void => {
  12426. this.stop()
  12427. };
  12428. private sessionFastForwardCallback = (time?: number) => {
  12429. if (!time) {
  12430. return;
  12431. }
  12432. if (this.mIjkMediaPlayer != null) {
  12433. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12434. let seeTime = curPosition + time * 1000;
  12435. // 限制 seekValue 在合法范围内
  12436. if (seeTime < 0) {
  12437. seeTime = 0;
  12438. } else if (seeTime > this.duration) {
  12439. seeTime = this.duration;
  12440. }
  12441. Logger.info('onecold seeTime= ' + seeTime)
  12442. this.setSeekToActionProgress(seeTime)
  12443. this.seekTo(seeTime + "")
  12444. }
  12445. };
  12446. /**
  12447. * Gesture method onActionUpdate.
  12448. *
  12449. * @param event Gesture event.手势拖动设置快进和后退
  12450. */
  12451. private setSeekToActionProgress(position: number) {
  12452. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  12453. let duration = this.mIjkMediaPlayer.getDuration();
  12454. let pos = 0;
  12455. if (duration > 0) {
  12456. this.slideEnable = true;
  12457. let curPercent = position / duration;
  12458. pos = curPercent * 100;
  12459. if (pos > this.PROGRESS_MAX_VALUE) {
  12460. this.progressValue = this.PROGRESS_MAX_VALUE
  12461. } else {
  12462. this.progressValue = pos;
  12463. }
  12464. }
  12465. // LogUtils.getInstance()
  12466. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  12467. this.totalTime = this.stringForTime(duration);
  12468. if (position > duration) {
  12469. position = duration;
  12470. }
  12471. this.isCurrentTime = true;
  12472. this.currentTime = this.stringForTime(position);
  12473. this.isCurrentTime = false
  12474. }
  12475. private sessionRewindCallback = (time?: number) => {
  12476. if (!time) {
  12477. return;
  12478. }
  12479. if (this.mIjkMediaPlayer != null) {
  12480. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12481. let seeTime = curPosition - time * 1000;
  12482. // 限制 seekValue 在合法范围内
  12483. if (seeTime < 0) {
  12484. seeTime = 0;
  12485. } else if (seeTime > this.duration) {
  12486. seeTime = this.duration;
  12487. }
  12488. Logger.info('onecold seeTime= ' + seeTime)
  12489. this.setSeekToActionProgress(seeTime)
  12490. this.seekTo(seeTime + "")
  12491. }
  12492. };
  12493. private sessionSeekCallback = (seekTime: number) => {
  12494. if (this.mIjkMediaPlayer != null) {
  12495. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12496. this.seekTo(seekTime + "")
  12497. }
  12498. };
  12499. private async getFileSize(filePath: string): Promise<number> {
  12500. try {
  12501. const stat = await fs.stat(filePath);
  12502. return stat.size;
  12503. } catch (err) {
  12504. console.error('Failed to get file size: ' + err.message);
  12505. return 0;
  12506. }
  12507. }
  12508. private pause() {
  12509. if (this.mIjkMediaPlayer.isPlaying()) {
  12510. this.savePlaybackPosition();
  12511. this.mIjkMediaPlayer.pause();
  12512. this.setProgress();
  12513. this.mDestroyPage = true;
  12514. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  12515. this.updateSessionPlayState(false)
  12516. this.playChange()
  12517. if (this.pipController) {
  12518. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  12519. PiPWindow.PiPControlStatus.PAUSE);
  12520. }
  12521. }
  12522. }
  12523. private stop() {
  12524. this.savePlaybackPosition();
  12525. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12526. this.mIjkMediaPlayer.stop();
  12527. this.mIjkMediaPlayer.release();
  12528. this.stopProgressTask();
  12529. this.updateSessionPlayState(false)
  12530. this.playChange()
  12531. this.watchStatus();
  12532. }
  12533. //保持记忆播放功能
  12534. private savePlaybackPosition() {
  12535. if (this.mIjkMediaPlayer != null) {
  12536. const position = this.mIjkMediaPlayer.getCurrentPosition();
  12537. // ToastUtil.showToast('保存记忆播放 = ' + position)
  12538. const duration = this.mIjkMediaPlayer.getDuration();
  12539. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  12540. // 如果播放位置接近视频末尾,则保存 position 为 0
  12541. const playbackPosition = (duration - position < threshold) ? 0 : position;
  12542. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  12543. }
  12544. }
  12545. //获取记忆播放功能
  12546. private restorePlaybackPosition() {
  12547. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  12548. // ToastUtil.showToast('position = ' + position)
  12549. if (this.mIjkMediaPlayer != null && position > 0) {
  12550. // ToastUtil.showToast('seekTo = ' + position)
  12551. this.seekTo(position + "");
  12552. }
  12553. }
  12554. private seekTo(value: string) {
  12555. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  12556. ToastUtil.showToast('wma格式不支持拖动快进。')
  12557. return
  12558. }
  12559. this.isSeekTo = true
  12560. this.mIjkMediaPlayer.seekTo(value);
  12561. console.info('onecold startPlayOrResumePlay 11227')
  12562. // this.startPlayOrResumePlay()
  12563. // 在这里恢复计时器状态
  12564. this.setProgress()
  12565. this.isSeekTo = false
  12566. }
  12567. // 添加到下一首播放
  12568. private addToNextPlay(song: VideoItem) {
  12569. if (!this.debounce()) {
  12570. return;
  12571. }
  12572. if (this.currentSong) {
  12573. if (this.currentSong === song) {
  12574. ToastUtil.showToast('当前已经在播放这首歌了!')
  12575. return
  12576. }
  12577. }
  12578. // 如果未开始播放或队列为空
  12579. if (this.curIndex === -1 || this.songList.length === 0) {
  12580. this.songList = [song];
  12581. this.curIndex = 0;
  12582. this.doPlay(song)
  12583. return;
  12584. }
  12585. // 插入到当前索引+1的位置
  12586. const insertPos = this.curIndex + 1;
  12587. this.songList.splice(insertPos, 0, song);
  12588. this.songList = [...this.songList]; // 触发状态更新
  12589. this.sonDataSource.pushArrayData(this.songList)
  12590. ToastUtil.showToast('已添加至下一首播放')
  12591. }
  12592. //后退10s,可再设置设置默认几秒
  12593. backForward() {
  12594. if(this.mIjkMediaPlayer){
  12595. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  12596. let value = pos - Number(this.fastForwardSeconds) * 1000;
  12597. this.seekTo(value+"");
  12598. }
  12599. }
  12600. //快进10s,可再设置设置默认几秒
  12601. fastForward() {
  12602. if(this.mIjkMediaPlayer){
  12603. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  12604. let value = pos + Number(this.fastForwardSeconds) * 1000;
  12605. this.seekTo(value+"");
  12606. }
  12607. }
  12608. //下一个
  12609. private async playNext() {
  12610. if (!this.debounce()) {
  12611. return;
  12612. }
  12613. if (this.playType == 3) { //3:随机播放
  12614. await this.randomPlay()
  12615. return;
  12616. }
  12617. if (ArrayUtil.isNotEmpty(this.songList)) {
  12618. if (this.curIndex == this.songList.length - 1) {
  12619. this.curIndex = 0;
  12620. } else {
  12621. this.curIndex++;
  12622. }
  12623. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12624. this.stop();
  12625. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  12626. this.currentSong = this.songList[this.curIndex];
  12627. Logger.info('heanup playNext', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  12628. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12629. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  12630. context: this.context,
  12631. autoParseMusicName: this.autoParseMusicName
  12632. });
  12633. this.artist = this.songList[this.curIndex].artist
  12634. this.name = this.songList[this.curIndex].name
  12635. //this.cover = this.songList[this.curIndex].pixelMapPath
  12636. this.changeImageAnimation()
  12637. }
  12638. }
  12639. changeImageAnimation() {
  12640. if(this.openSkipSongAnimate){
  12641. // 第一步:淡出动画
  12642. this.getUIContext()?.animateTo({
  12643. duration: 500,
  12644. curve: Curve.EaseOut,
  12645. }, () => {
  12646. this.opacityValueImage = 0.1;
  12647. if(this.isCoverRectangle){
  12648. this.scaleValueImage = 0.88
  12649. }
  12650. });
  12651. // 第二步:切换图片后淡入
  12652. setTimeout(() => {
  12653. this.cover = this.songList[this.curIndex].pixelMapPath
  12654. this.getUIContext()?.animateTo({
  12655. duration: 500,
  12656. curve: Curve.EaseIn,
  12657. }, () => {
  12658. this.opacityValueImage = 1;
  12659. this.scaleValueImage = 1 // 图标恢复到原始大小
  12660. this.startPlayOrResumePlay()
  12661. });
  12662. }, 500);
  12663. }else{
  12664. this.cover = this.songList[this.curIndex].pixelMapPath
  12665. this.startPlayOrResumePlay()
  12666. }
  12667. }
  12668. // 存储已播放的歌曲索引
  12669. private playedIndices: Set<number> = new Set();
  12670. //随机播放
  12671. private async randomPlay() {
  12672. // if (!this.debounce()) {
  12673. // return;
  12674. // }
  12675. if (ArrayUtil.isNotEmpty(this.songList)) {
  12676. if (this.songList.length > 3) {
  12677. // 如果所有歌曲都播放过一次,清空已播放索引集合
  12678. if (this.playedIndices.size === this.songList.length) {
  12679. this.playedIndices.clear();
  12680. }
  12681. // 随机选择一个未播放的歌曲索引
  12682. let newIndex: number;
  12683. // 添加超时机制防止无限循环
  12684. let attempt = 0;
  12685. const maxAttempts = 100; // 根据需求调整
  12686. do {
  12687. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  12688. attempt++;
  12689. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  12690. if (attempt >= maxAttempts) {
  12691. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  12692. newIndex = Math.floor(Math.random() * this.songList.length);
  12693. }
  12694. this.curIndex = newIndex;
  12695. this.playedIndices.add(newIndex);
  12696. } else {
  12697. // 当歌曲数量小于或等于3时,直接播放下一首
  12698. if (this.curIndex == this.songList.length - 1) {
  12699. this.curIndex = 0;
  12700. } else {
  12701. this.curIndex++;
  12702. }
  12703. }
  12704. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12705. this.stop();
  12706. this.currentSong = this.songList[this.curIndex];
  12707. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12708. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  12709. context: this.context,
  12710. autoParseMusicName: this.autoParseMusicName
  12711. });
  12712. this.name = this.songList[this.curIndex].name;
  12713. this.artist = this.songList[this.curIndex].artist
  12714. // this.cover = this.songList[this.curIndex].pixelMapPath
  12715. this.changeImageAnimation()
  12716. }
  12717. }
  12718. private async playIndex(index: number) {
  12719. if (!this.debounce()) {
  12720. return;
  12721. }
  12722. if (ArrayUtil.isNotEmpty(this.songList)) {
  12723. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12724. this.stop();
  12725. this.curIndex = index;
  12726. this.currentSong = this.songList[index];
  12727. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12728. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  12729. context: this.context,
  12730. autoParseMusicName: this.autoParseMusicName
  12731. });
  12732. this.name = this.currentSong.name
  12733. this.artist = this.currentSong.artist
  12734. this.changeImageAnimation()
  12735. }
  12736. }
  12737. //上一个
  12738. private async playPrevious() {
  12739. if (!this.debounce()) {
  12740. return;
  12741. }
  12742. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  12743. this.randomModePlayFromHistory()
  12744. return;
  12745. }
  12746. if (this.curIndex == 0) {
  12747. this.curIndex = this.songList.length - 1;
  12748. } else {
  12749. this.curIndex--;
  12750. }
  12751. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12752. this.stop();
  12753. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  12754. this.currentSong = this.songList[this.curIndex];
  12755. Logger.info('heanup playPrevious', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  12756. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12757. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  12758. context: this.context,
  12759. autoParseMusicName: this.autoParseMusicName
  12760. });
  12761. this.name = this.songList[this.curIndex].name
  12762. this.artist = this.songList[this.curIndex].artist
  12763. this.changeImageAnimation()
  12764. }
  12765. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  12766. private async randomModePlayFromHistory() {
  12767. if (this.historyList.length >= 2) {
  12768. // 播放历史记录的第二首
  12769. const prevSong = this.historyList[1];
  12770. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  12771. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12772. this.stop();
  12773. // 直接使用历史记录中的歌曲信息,历史记录中的数据应该是完整的
  12774. this.currentSong = prevSong;
  12775. Logger.info('heanup randomModePlayFromHistory', `直接使用历史歌曲信息: ${prevSong.name}, type: ${prevSong.type}`);
  12776. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12777. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  12778. context: this.context,
  12779. autoParseMusicName: this.autoParseMusicName
  12780. });
  12781. this.cover = prevSong.pixelMapPath
  12782. this.artist = prevSong.artist
  12783. this.name = prevSong.name;
  12784. console.info('onecold startPlayOrResumePlay 11434')
  12785. this.startPlayOrResumePlay();
  12786. } else {
  12787. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  12788. if (this.curIndex === 0) {
  12789. this.curIndex = this.songList.length - 1;
  12790. } else {
  12791. this.curIndex--;
  12792. }
  12793. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12794. this.stop();
  12795. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  12796. this.currentSong = this.songList[this.curIndex];
  12797. Logger.info('heanup randomModePlayFromHistory', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  12798. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12799. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  12800. context: this.context,
  12801. autoParseMusicName: this.autoParseMusicName
  12802. });
  12803. this.artist = this.songList[this.curIndex].artist
  12804. this.name = this.songList[this.curIndex].name;
  12805. this.changeImageAnimation()
  12806. }
  12807. }
  12808. debounce() {
  12809. const delay = 600;
  12810. let cur = new Date().getTime();
  12811. if (cur - this.last > delay) {
  12812. this.last = cur;
  12813. return true;
  12814. }
  12815. return false;
  12816. }
  12817. /**
  12818. * Sets whether the screen is a constant based on the playback status.
  12819. */
  12820. watchStatus() {
  12821. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  12822. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  12823. this.windowClass.setWindowKeepScreenOn(true);
  12824. } else {
  12825. this.windowClass.setWindowKeepScreenOn(false);
  12826. }
  12827. }
  12828. /**
  12829. * Volume gesture method onActionStart.
  12830. *
  12831. * @param event Gesture event.
  12832. */
  12833. private customDialogComponentIdMM: number = 0
  12834. @Builder
  12835. customDialogComponentMM() {
  12836. Column() {
  12837. Row() {
  12838. Blank()
  12839. Text('验证密码')
  12840. .fontSize(22)
  12841. .fontColor($r('app.color.pri_bg'))
  12842. .margin({ top: 18 })
  12843. Blank()
  12844. Image($r('app.media.close'))
  12845. .fillColor(Color.White)
  12846. .margin({ top: 18, right: 18 })
  12847. .width(20)
  12848. .onClick(() => {
  12849. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  12850. })
  12851. }
  12852. .width('100%') // 使Row占据整个宽度
  12853. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  12854. Verify({
  12855. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  12856. });
  12857. }.height('60%')
  12858. .backgroundColor($r('app.color.index_background'))
  12859. .justifyContent(FlexAlign.SpaceBetween)
  12860. }
  12861. private handleVerifyCompleted(isSuccess: boolean) {
  12862. if (isSuccess) {
  12863. console.log('验证成功');
  12864. // 在这里处理验证成功后的逻辑
  12865. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  12866. this.currentPath = this.lockPath
  12867. this.getSortedFiles(this.currentPath)
  12868. } else {
  12869. // console.log('验证失败');
  12870. ToastUtil.showToast('验证失败')
  12871. }
  12872. }
  12873. private showVerifyDialog() {
  12874. promptAction.openCustomDialog({
  12875. transition: TransitionEffect.asymmetric(
  12876. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  12877. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  12878. ,
  12879. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  12880. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  12881. ),
  12882. builder: () => {
  12883. this.customDialogComponentMM()
  12884. },
  12885. isModal: true,
  12886. autoCancel: true,
  12887. maskColor: Color.Transparent,
  12888. alignment: DialogAlignment.Bottom,
  12889. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  12890. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  12891. console.log("dialog onWillDismiss")
  12892. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  12893. dismissDialogAction.dismiss()
  12894. }
  12895. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  12896. dismissDialogAction.dismiss()
  12897. }
  12898. }
  12899. }).then((dialogId: number) => {
  12900. this.customDialogComponentIdMM = dialogId
  12901. })
  12902. }
  12903. //左滑操作 移动文件 重命名 删除等操作
  12904. @Builder
  12905. DeleteButton(item: VideoItem, index: number, filePath: string) {
  12906. Row() {
  12907. //加入收藏
  12908. Button() {
  12909. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  12910. .fillColor(Color.White)
  12911. .width(20)
  12912. }
  12913. .width(40)
  12914. .height(40)
  12915. .type(ButtonType.Circle)
  12916. .backgroundColor(this.themeColor)
  12917. .margin(5)
  12918. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  12919. .onClick(() => {
  12920. if (item) {
  12921. this.doFav(item)
  12922. }
  12923. })
  12924. //加入下一首播放
  12925. Button() {
  12926. Image($r('app.media.next_to_play'))
  12927. .fillColor(Color.White)
  12928. .width(20)
  12929. }
  12930. .width(40)
  12931. .height(40)
  12932. .type(ButtonType.Circle)
  12933. .backgroundColor(this.themeColor)
  12934. .margin(5)
  12935. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  12936. .onClick(() => {
  12937. this.addToNextPlay(item);
  12938. })
  12939. //复制文件
  12940. Button() {
  12941. Image($r('app.media.copy'))
  12942. .fillColor(Color.White)
  12943. .width(20)
  12944. }
  12945. .width(40)
  12946. .height(40)
  12947. .type(ButtonType.Circle)
  12948. .backgroundColor(this.themeColor)
  12949. .margin(5)
  12950. .id(filePath + 'copy')
  12951. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  12952. .onClick(() => {
  12953. this.showCopyDialog(false, item, index, filePath + 'copy');
  12954. })
  12955. //移动文件
  12956. Button() {
  12957. Image($r('app.media.cut'))
  12958. .fillColor(Color.White)
  12959. .width(20)
  12960. }
  12961. .width(40)
  12962. .height(40)
  12963. .type(ButtonType.Circle)
  12964. .backgroundColor(this.themeColor)
  12965. .margin(5)
  12966. .id(filePath)
  12967. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  12968. .onClick(() => {
  12969. this.showCutDialog(false, item, index, filePath);
  12970. })
  12971. Button() {
  12972. Image($r('app.media.cut_current'))
  12973. .fillColor(Color.White)
  12974. .width(20)
  12975. }
  12976. .width(40)
  12977. .height(40)
  12978. .type(ButtonType.Circle)
  12979. .backgroundColor(this.themeColor)
  12980. .margin(5)
  12981. .id(filePath + 'current')
  12982. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  12983. (this.isHasDir ? Visibility.Visible : Visibility.None))
  12984. .onClick(() => {
  12985. this.showCutDialog(true, item, index, filePath + 'current');
  12986. })
  12987. //重命名
  12988. Button() {
  12989. Image($r('app.media.rename2'))
  12990. .fillColor(Color.White)
  12991. .width(20)
  12992. }
  12993. .width(40)
  12994. .height(40)
  12995. .type(ButtonType.Circle)
  12996. .backgroundColor(this.themeColor)
  12997. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  12998. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  12999. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  13000. .margin(5)
  13001. .onClick(() => {
  13002. this.showReNameDialog(item, index + '', filePath)
  13003. })
  13004. Button() {
  13005. Image($r('app.media.delete2'))
  13006. .fillColor(Color.White)
  13007. .width(20)
  13008. }
  13009. .width(40)
  13010. .height(40)
  13011. .type(ButtonType.Circle)
  13012. .backgroundColor(this.themeColor)
  13013. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  13014. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  13015. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  13016. .margin(5)
  13017. .onClick(() => {
  13018. this.selectedFiles.push(item)
  13019. this.showWarnIsDelete()
  13020. // this.showWarnIsDeleteFile(item, index + '', filePath)
  13021. })
  13022. Button() {
  13023. Image($r('app.media.share2'))
  13024. .fillColor(Color.White)
  13025. .width(20)
  13026. }
  13027. .width(40)
  13028. .height(40)
  13029. .type(ButtonType.Circle)
  13030. .backgroundColor(this.themeColor)
  13031. .margin(5)
  13032. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13033. .onClick(() => {
  13034. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  13035. })
  13036. }
  13037. }
  13038. /**
  13039. * 穿山甲banner广告
  13040. */
  13041. // private declare bannerAd: CSJNativeExpressAd;
  13042. // @State private status: string = "未加载"
  13043. // @State private isShowAd: boolean = false
  13044. // private declare mAdSlot: AdSlot;
  13045. // private mBiddingAdm = '' //服务端bidding才需要设置
  13046. // private expressLoadAdListener: NativeExpressAdListener = {
  13047. // /**
  13048. // * 加载失败的回调
  13049. // *
  13050. // * @param code
  13051. // * @param message
  13052. // */
  13053. // onError: (code: number, message: string) => {
  13054. // console.error("加载广告失败,code=" + code + ",message=" + message);
  13055. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  13056. // },
  13057. //
  13058. // /**
  13059. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  13060. // *
  13061. // * @param ads 返回的广告列表
  13062. // */
  13063. //
  13064. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  13065. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  13066. // if (ads && ads.length > 0) {
  13067. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  13068. // ad.setExpressInteractionListener({
  13069. // /**
  13070. // *广告的点击回调
  13071. // * @param type 广告的交互类型
  13072. // */
  13073. // onAdClicked: (type: number) => {
  13074. // console.log("BannerExpressAdPage==onAdClicked......");
  13075. // },
  13076. //
  13077. // /**
  13078. // * 广告的展示回调 每个广告仅回调一次
  13079. // * @param type 广告的交互类型
  13080. // */
  13081. // onAdShow: (type: number) => {
  13082. // console.log("BannerExpressAdPage==onAdShow......");
  13083. // },
  13084. //
  13085. // /**
  13086. // * 模板渲染失败
  13087. // */
  13088. // onRenderFail: (code: number, msg: string) => {
  13089. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  13090. // },
  13091. //
  13092. // /**
  13093. // * 模板渲染成功
  13094. // * @param width 返回view的宽 单位 vp
  13095. // * @param height 返回view的高 单位 vp
  13096. // */
  13097. // onRenderSuccess: (width: number, height: number) => {
  13098. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  13099. // this.bannerAd = ad;
  13100. // this.status = "广告加载完成待展示";
  13101. //
  13102. // this.showBannerAd()
  13103. // }
  13104. // })
  13105. // //渲染广告
  13106. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  13107. // this.setDislikeCallback(ad); //设置dislike
  13108. // ad.render(this.getUIContext())
  13109. // this.status = "广告加载中...";
  13110. // });
  13111. // }
  13112. // }
  13113. // }
  13114. //
  13115. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  13116. // ad.setDislikeCallback({
  13117. // /**
  13118. // * dislike show
  13119. // */
  13120. // onShow: () => {
  13121. // console.log("BannerExpressAdPage==dislike......show");
  13122. // },
  13123. //
  13124. // /**
  13125. // * @param position 选择的位置
  13126. // * @param value 选择的内容
  13127. // * @param enforceRemove 是否强制关闭广告
  13128. // */
  13129. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  13130. // this.isShowAd = false;
  13131. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  13132. // ",enforce=" + enforceRemove);
  13133. // },
  13134. //
  13135. // /**
  13136. // * 点击取消
  13137. // */
  13138. // onCancel: () => {
  13139. // console.log("BannerExpressAdPage==dislike......onCancel");
  13140. // }
  13141. //
  13142. // })
  13143. // }
  13144. /**
  13145. * 加载Banner广告
  13146. */
  13147. loadBannerAd(rit: string) {
  13148. // if (Utility.isNoble()) {
  13149. // return
  13150. // }
  13151. // if (!Utility.isPassInstallTime(2)) {
  13152. // return
  13153. // }
  13154. // this.isShowAd = false;
  13155. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  13156. // this.mAdSlot = new AdSlotBuilder()
  13157. // .setCodeId(rit)
  13158. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  13159. // .setAdCount(1)
  13160. // .setBidAdm(this.mBiddingAdm)
  13161. // .build()
  13162. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  13163. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  13164. // this.status = "广告加载中..."
  13165. }
  13166. /**
  13167. * 展示Banner广告
  13168. */
  13169. // showBannerAd() {
  13170. // if (!this.bannerAd) {
  13171. // return
  13172. // }
  13173. // this.isShowAd = true
  13174. // this.status = "已展示"
  13175. // }
  13176. /**
  13177. * 穿山甲广告代码结束
  13178. */
  13179. /**
  13180. * 处理歌单播放请求
  13181. */
  13182. private async handlePlaylistPlayRequest(playlistId: string, playlistName:
  13183. string, songFilePaths: string[], startIndex: number) {
  13184. try {
  13185. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 歌曲数量: ${songFilePaths.length}, 开始索引: ${startIndex}`)
  13186. // 检查是否为WebDAV播放请求
  13187. if (playlistId === 'webdav-playlist') {
  13188. Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
  13189. // 从全局内存读取videoItems数据
  13190. const videoItems = getWebdavVideoItems();
  13191. const currentPlayIndex = getWebdavCurrentPlayIndex();
  13192. Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
  13193. if (videoItems && videoItems.length > 0) {
  13194. // 验证webdav_account_id设置情况
  13195. const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
  13196. Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
  13197. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName)
  13198. return
  13199. } else {
  13200. return
  13201. }
  13202. }
  13203. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  13204. const songMap: Map<number, VideoItem> = new Map()
  13205. let completedQueries = 0
  13206. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  13207. // 遍历所有文件路径,使用索引记录位置
  13208. for (let i = 0; i < songFilePaths.length; i++) {
  13209. const filePath = songFilePaths[i]
  13210. const index = i
  13211. // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  13212. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  13213. const queryPromise = this.table.queryVideoByFilePath(filePath)
  13214. // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  13215. queryPromise.then((videoItem) => {
  13216. completedQueries++
  13217. // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  13218. if (videoItem) {
  13219. // 使用索引作为key保存到Map中,保持原始顺序
  13220. songMap.set(index, videoItem)
  13221. // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  13222. } else {
  13223. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  13224. }
  13225. // 检查是否所有歌曲都已加载完成
  13226. if (completedQueries === songFilePaths.length) {
  13227. // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  13228. // 按照索引顺序重建歌曲数组
  13229. const songs: VideoItem[] = []
  13230. for (let j = 0; j < songFilePaths.length; j++) {
  13231. const song = songMap.get(j)
  13232. if (song) {
  13233. songs.push(song)
  13234. // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  13235. }
  13236. }
  13237. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  13238. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  13239. }
  13240. }).catch((error: Error) => {
  13241. completedQueries++
  13242. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  13243. // 即使出错也要检查是否完成所有查询
  13244. if (completedQueries === songFilePaths.length) {
  13245. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  13246. // 按照索引顺序重建歌曲数组
  13247. const songs: VideoItem[] = []
  13248. for (let j = 0; j < songFilePaths.length; j++) {
  13249. const song = songMap.get(j)
  13250. if (song) {
  13251. songs.push(song)
  13252. }
  13253. }
  13254. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  13255. }
  13256. })
  13257. }
  13258. } catch (error) {
  13259. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  13260. ToastUtil.showToast('播放失败')
  13261. }
  13262. }
  13263. /**
  13264. * 完成歌单加载并开始播放
  13265. */
  13266. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string) {
  13267. if (songs.length === 0) {
  13268. Logger.error('heanup 没有找到任何可播放的歌曲')
  13269. ToastUtil.showToast('没有找到可播放的歌曲')
  13270. return
  13271. }
  13272. this.songList = songs
  13273. this.sonDataSource.pushArrayData(songs)
  13274. this.sonDataSource.notifyDataReload()
  13275. this.curIndex = startIndex
  13276. if (songs[startIndex]) {
  13277. // 确保当前播放的歌曲也更新到存储
  13278. AppStorage.setOrCreate('currentSong', songs[startIndex])
  13279. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  13280. this.doPlay(songs[startIndex], startIndex, true)
  13281. }
  13282. PreferencesUtil.putSync('LastMusicList', this.songList)
  13283. ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  13284. }
  13285. }
  13286. //视频气泡窗口的布局
  13287. @Builder
  13288. function customPopupBuilder(dataBu: BubbleBean) {
  13289. List() {
  13290. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  13291. ListItem() {
  13292. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13293. Row() {
  13294. Column() {
  13295. Image(dataBu.imageRes[index])
  13296. .height(28)
  13297. .fillColor(dataBu.color)
  13298. .alignSelf(ItemAlign.Center)
  13299. }
  13300. .width(32)
  13301. Text(item)
  13302. .padding({
  13303. top: 10,
  13304. bottom: 10,
  13305. right: 10,
  13306. left: 10
  13307. })
  13308. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  13309. .textAlign(TextAlign.Start)
  13310. .width("100%")
  13311. }
  13312. }
  13313. .backgroundColor($r('app.color.settings_background_main'))
  13314. .margin({ top: 6, bottom: 6 })
  13315. }
  13316. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  13317. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  13318. TransitionEffect.scale({ x: 0, y: 0 })))
  13319. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  13320. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  13321. .onClick(() => {
  13322. dataBu.onItemClick?.(index)
  13323. })
  13324. })
  13325. }
  13326. .scrollBar(BarState.Off)
  13327. .width(120)
  13328. .divider({
  13329. strokeWidth: 1,
  13330. color: "#22FFFFFF"
  13331. })
  13332. }
  13333. // Function to calculate a hash for the file list
  13334. function simpleHash(fileList: string[]): string {
  13335. let hash = 0;
  13336. const str = fileList.join(',');
  13337. for (let i = 0; i < str.length; i++) {
  13338. const char = str.charCodeAt(i);
  13339. hash = (hash << 5) - hash + char;
  13340. hash |= 0; // Convert to 32bit integer
  13341. }
  13342. return hash.toString();
  13343. }
  13344. interface MoreItem {
  13345. id: number;
  13346. image: Resource;
  13347. title: string;
  13348. }
  13349. //视频气泡窗口的布局
  13350. @Builder
  13351. function cutPopupBuilder(dataBu: BubbleBean) {
  13352. Column() {
  13353. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  13354. .padding({
  13355. top: 10,
  13356. bottom: 10,
  13357. right: 10,
  13358. left: 10
  13359. })
  13360. .textAlign(TextAlign.Start)
  13361. .width(160)
  13362. .fontWeight(666)
  13363. .fontSize(16)
  13364. List() {
  13365. ForEach(dataBu.data, (item: string, index: number) => {
  13366. ListItem() {
  13367. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13368. Row() {
  13369. Column() {
  13370. Image($r('app.media.music_group'))
  13371. .height(28)
  13372. .fillColor(dataBu.color)
  13373. .alignSelf(ItemAlign.Center)
  13374. }
  13375. .width(32)
  13376. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  13377. .padding({
  13378. top: 10,
  13379. bottom: 10,
  13380. right: 10,
  13381. left: 10
  13382. })
  13383. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  13384. .fontSize(15)
  13385. }
  13386. }
  13387. .backgroundColor(Color.Transparent)
  13388. .margin({ top: 7, bottom: 7 })
  13389. }
  13390. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  13391. .animation({ duration: 500 }),
  13392. TransitionEffect.scale({ x: 0, y: 0 })))
  13393. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  13394. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  13395. .onClick(() => {
  13396. dataBu.onItemClick?.(index)
  13397. })
  13398. })
  13399. }
  13400. .scrollBar(BarState.Off)
  13401. .width(150)
  13402. .divider({
  13403. strokeWidth: 1,
  13404. color: "#22FFFFFF"
  13405. })
  13406. }
  13407. .height(300)
  13408. .padding({
  13409. bottom: 30
  13410. })
  13411. }
  13412. function getFileDirName(filePath: string,rootPath:string): string{
  13413. if(filePath===rootPath){
  13414. return '首页'
  13415. }
  13416. let result = FileUtil.getFileName(filePath)
  13417. if(StrUtil.isEmpty(result))
  13418. return ''
  13419. if(result.startsWith('.'))
  13420. result = result.replace(/\./g, '')
  13421. return result
  13422. }
  13423. //只扫描当前目录下文件(不扫描子文件夹)的方法
  13424. @Concurrent
  13425. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  13426. const table: MediaTable = new MediaTable(context);
  13427. try {
  13428. // 直接获取当前目录下的文件列表
  13429. const files = FileUtil.listFileSync(dirPath);
  13430. await Promise.all(files.map(async (file) => {
  13431. const fPath = `${dirPath}/${file}`;
  13432. // 跳过目录,只处理文件
  13433. if (FileUtil.isDirectory(fPath)) {
  13434. return;
  13435. }
  13436. // 跳过特定格式文件
  13437. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  13438. return;
  13439. }
  13440. // 检查是否为媒体文件
  13441. if (Utility.isMeidaByExtension(fPath)) {
  13442. let mType = CommonConstants.TYPE_LOCAL;
  13443. if (fPath.includes(lockPath)) {
  13444. mType = CommonConstants.TYPE_LOCK;
  13445. }
  13446. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  13447. context, fPath, mType, true
  13448. );
  13449. table.insert(mediaItem, (id: number) => {
  13450. // 插入回调函数
  13451. }, cover_api);
  13452. }
  13453. }));
  13454. } catch (error) {
  13455. console.error(' 扫描当前目录失败:', error);
  13456. }
  13457. }
  13458. //内嵌标签后更新库
  13459. @Concurrent
  13460. async function updateInfoDb(
  13461. context: Context,
  13462. filePath: string,
  13463. titleStr: string,
  13464. artistStr: string,
  13465. albumStr: string,
  13466. lyricConStr: string,
  13467. yearStr: string,
  13468. genreStr: string,
  13469. trackStr: string,
  13470. albumArtistStr: string,
  13471. composerStr: string,
  13472. lyricistStr: string,
  13473. commentStr: string,
  13474. discStr: string,
  13475. ): Promise<boolean> {
  13476. const table: MediaTable = new MediaTable(context);
  13477. await new Promise<void>((resolve, reject) => {
  13478. table.getRdbStore(context, (err:Error) => {
  13479. err ? reject(err) : resolve();
  13480. });
  13481. });
  13482. return await new Promise<boolean>((resolve) => {
  13483. table.updateMediaInfo(filePath, titleStr, artistStr, albumStr, lyricConStr,
  13484. yearStr, genreStr, trackStr, albumArtistStr, composerStr, lyricistStr, commentStr, discStr,
  13485. (success: boolean, error?: string) => {
  13486. if (success) {
  13487. console.log("onecold 编辑信息成功,数据库已同步");
  13488. } else {
  13489. console.error("onecold 编辑信息数据库失败原因: " + error);
  13490. }
  13491. resolve(success);
  13492. });
  13493. });
  13494. }