LocalMusic.ets 538 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501
  1. import TitleBar from './TitleBar'
  2. import { curves, display, MenuModifier,PiPWindow, promptAction, router, SymbolGlyphModifier, window } from '@kit.ArkUI';
  3. import { VideoItem } from '../viewmodel/VideoItem';
  4. import { LengthMetrics, SegmentButton,SegmentButtonOptions } from '@kit.ArkUI';
  5. import { getWebdavVideoItems, getWebdavCurrentPlayIndex } from '../pages/WebDavMainPage';
  6. import { getNavidromeVideoItems, getNavidromeCurrentPlayIndex } from '../common/util/NavidromePlaylistStore';
  7. import {
  8. ButtonFancyModifier,
  9. ImageFancyModifier,
  10. ShadowModifier,
  11. SymbolGlyphFancyModifier } from '../common/util/AttributeModifierUtil'
  12. import {
  13. AppUtil,
  14. ArrayUtil,
  15. Base64Util,
  16. DateUtil,
  17. DeviceUtil,
  18. FileUtil,
  19. GlobalContext,
  20. LogUtil,
  21. MD5,
  22. PreferencesUtil,
  23. RandomUtil,
  24. StrUtil,
  25. ToastUtil
  26. } from '@pura/harmony-utils';
  27. import { imagePathToPixelMap } from '../common/util/CommUtils';
  28. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  29. import { CommonConstants } from '../common/constants/CommonConstants';
  30. import { BaiduConstants } from '../common/constants/BaiduConstants';
  31. import { EventConstants } from '../common/constants/EventConstants';
  32. import Logger from '../common/util/Logger';
  33. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  34. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  35. import { BubbleBean } from '../viewmodel/BubbleBean';
  36. import { PopupPosition, XPopup } from '@chinalike/popup';
  37. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  38. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  39. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  40. import { MessageEvents, util, worker, ErrorEvent, JSON } from '@kit.ArkTS';
  41. import { Verify } from './Verify';
  42. import { taskpool } from '@kit.ArkTS';
  43. import { RotatingCover } from './RotatingCover';
  44. import { PlayConstants } from '../common/constants/PlayConstants';
  45. import { effectKit } from '@kit.ArkGraphics2D';
  46. import { ColorConversion } from '../common/util/ColorConversion';
  47. import { LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  48. import { AvSessionController } from '../controller/AvSessionController';
  49. import { repairAudioMetadata, convertDsfToWav, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  50. import { extractHwMediaMetadata, FFMpegTags,Utility } from '../common/util/Utility';
  51. import { TagsContentCover } from '../view/TagsContentCover';
  52. import {
  53. DeviceChangeReason,
  54. IjkMediaPlayer,
  55. InterruptEvent,
  56. InterruptHintType,
  57. LogUtils,
  58. OnBufferingUpdateListener,
  59. OnCompletionListener,
  60. OnErrorListener,
  61. OnInfoListener,
  62. OnPreparedListener,
  63. OnSeekCompleteListener,
  64. OnTimedTextListener,
  65. OnVideoSizeChangedListener
  66. } from '@ohos/ijkplayer';
  67. import { PlayStatus } from '../common/PlayStatus';
  68. import fs from '@ohos.file.fs';
  69. import { image } from '@kit.ImageKit';
  70. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  71. import { UniversalDetector } from '@ohos/juniversalchardet';
  72. import { SettingPage } from '../pages/SettingPage';
  73. import { secondToTime,getTransverterText } from '../common/util/CommUtils';
  74. import { CommonConstants2 } from '../common/util/CommonConstants2';
  75. import { hilog } from '@kit.PerformanceAnalysisKit';
  76. import { LazyDataSource } from '../common/util/LazyDataSource';
  77. import MediaTable from '../common/util/MediaTable';
  78. import FileDeletionWatcher from '../common/util/FileDeletionWatcher';
  79. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  80. import ImageUtils from '../common/util/ImageUtils';
  81. import { ringtone } from '@kit.RingtoneKit';
  82. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  83. import { resourceManager } from '@kit.LocalizationKit';
  84. import { deviceInfo } from '@kit.BasicServicesKit';
  85. import { RemoteCacheManager } from '../common/network/RemoteCacheManager';
  86. import '../common/network/RemoteCacheRegistry';
  87. import { RemoteCacheType, resolveCacheFilePath } from '../common/network/RemoteSongCache';
  88. import { findWebDavCacheIfExists, triggerWebDavCacheDownload } from '../common/network/WebDavFileCache';
  89. import { navidromeApi } from '../common/network/NavidromeApi';
  90. import { ServerLogUtil } from '../common/util/ServerLogUtil';
  91. import { ensureSmbFileStreaming, SmbStreamingMeta } from '../common/network/SmbFileCache';
  92. import { ensureBaiduFileCached } from '../common/network/BaiduFileCache';
  93. import FileManager from '../common/util/FileManager';
  94. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  95. import app from '@system.app';
  96. import { TextNodeController } from './PipLyricTextBuilder';
  97. import { IndexerView } from './IndexerView';
  98. import { KeyCode } from '@kit.InputKit';
  99. import { KnockController } from '../controller/KnockController';
  100. import { DeleteComptent } from '../view/DeleteComptent';
  101. import { ABLoopComptent } from '../view/ABLoopComptent';
  102. import { FixMessyView } from '../view/FixMessyView';
  103. import { parseCueFile,CueTrack,CueInfo } from '../common/util/CueUtils';
  104. import { CueComptent } from '../view/CueComptent';
  105. import PlaylistTable from '../common/util/PlaylistTable';
  106. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  107. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  108. import { convertPlaylistSongsToVideoItems, emptyView,updateAllSongsSortOrder } from '../pages/PlaylistDetailPage';
  109. import { Playlist, PlaylistSong } from '../viewmodel/Playlist';
  110. import { Song } from '../viewmodel/Song';
  111. import { SongType } from '../common/enums/SongType';
  112. import { RemoteDriveManager, WebDavAuthInfo as WebDavManagerAuthInfo,
  113. buildHttpHeadersWithWebDav,
  114. WebDavAuthItem} from '../common/util/RemoteDriveManager';
  115. import PermissionUtil from '../common/util/PermissionUtil'
  116. import { EditAudio, setRingTone } from './EditAudio';
  117. import { ExtractAccompaniment } from './ExtractAccompaniment';
  118. import { ExtractAudioFromVideo } from './ExtractAudioFromVideo';
  119. import { AudioFormatConverter } from './AudioFormatConverter';
  120. import { MergeAudio } from './MergeAudio';
  121. import { AIVoiceSeparation } from './AIVoiceSeparation';
  122. import { WebDavUrlUtil } from '../common/util/WebDavUrlUtil';
  123. import { ChangeTone } from './ChangeTone';
  124. import {
  125. hdsEffect,
  126. HdsVisualComponent,
  127. HdsSceneController,
  128. HdsSceneType,
  129. HdsVisualComponentAttribute,
  130. } from '@kit.UIDesignKit';
  131. import { GlobalAlphabetIndexerModifier } from '../Styels/GlobalStyles'
  132. import { getFirstLetter } from '../Constants';
  133. import { audio } from '@kit.AudioKit';
  134. const TAG = 'LocalMusic';
  135. const HICAR_LOG_TAG = 'HiCarWindow';
  136. function logHiCarWindow(message: string): void {
  137. void ServerLogUtil.info(HICAR_LOG_TAG, message);
  138. }
  139. /**
  140. * 歌单播放事件数据
  141. */
  142. interface PlaylistEventData {
  143. playlistId: string;
  144. playlistName: string;
  145. songCount: number;
  146. startIndex: number;
  147. songFilePaths: string[];
  148. isJump: boolean;
  149. webDavAuthInfo?: WebDavAuthItem; // 新增WebDAV认证信息
  150. }
  151. const DEFAULT_INDEX =
  152. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  153. 'X', 'Y', 'Z']
  154. //排序类型
  155. function getTypeOrder(type: number) {
  156. switch (type) {
  157. case CommonConstants.TYPE_IS_DIR:
  158. return 1; // First
  159. case CommonConstants.TYPE_IS_CSJAD:
  160. return 2; // Middle
  161. case CommonConstants.TYPE_LOCAL:
  162. return 3; // Last
  163. case CommonConstants.TYPE_WEBDAV:
  164. case CommonConstants.TYPE_SMB:
  165. case CommonConstants.TYPE_NAVIDROME:
  166. case CommonConstants.TYPE_FTP:
  167. case CommonConstants.TYPE_BAIDU:
  168. return 3;
  169. default:
  170. return 4; // Unknown types, if any, go last
  171. }
  172. }
  173. function isWebDavType(type: number): boolean {
  174. return type === CommonConstants.TYPE_WEBDAV;
  175. }
  176. function isSmbType(type: number): boolean {
  177. return type === CommonConstants.TYPE_SMB;
  178. }
  179. function isNavidromeType(type: number): boolean {
  180. return type === CommonConstants.TYPE_NAVIDROME;
  181. }
  182. function isFtpType(type: number): boolean {
  183. return type === CommonConstants.TYPE_FTP;
  184. }
  185. function isBaiduType(type: number): boolean {
  186. return type === CommonConstants.TYPE_BAIDU;
  187. }
  188. function isRemoteCloudType(type: number): boolean {
  189. return isWebDavType(type) || isSmbType(type) || isNavidromeType(type) || isFtpType(type) || isBaiduType(type);
  190. }
  191. function getShareNameFromFilePath(filePath?: string): string | undefined {
  192. if (!filePath) {
  193. return undefined;
  194. }
  195. const match = filePath.match(/^smb:\/\/[^/]+\/([^/]+)/i);
  196. return match && match[1] ? match[1] : undefined;
  197. }
  198. function removeSharePrefixFromPath(path: string, primaryShare?: string, secondaryShare?: string): string {
  199. const uniqueShares: string[] = [];
  200. [primaryShare, secondaryShare].forEach((name?: string) => {
  201. const cleaned = name ? name.replace(/^\/+|\/+$/g, '') : '';
  202. if (cleaned.length > 0 && !uniqueShares.some(item => item.toLowerCase() === cleaned.toLowerCase())) {
  203. uniqueShares.push(cleaned);
  204. }
  205. });
  206. if (uniqueShares.length === 0) {
  207. return path;
  208. }
  209. let result = path;
  210. for (let i = 0; i < uniqueShares.length; i++) {
  211. const share = uniqueShares[i];
  212. const lowerPath = result.toLowerCase();
  213. const lowerShare = share.toLowerCase();
  214. if (lowerPath === lowerShare) {
  215. result = '';
  216. break;
  217. }
  218. const prefix = `${lowerShare}/`;
  219. if (lowerPath.startsWith(prefix)) {
  220. result = result.substring(share.length + 1);
  221. break;
  222. }
  223. }
  224. return result;
  225. }
  226. function extractSmbRelativePath(song: VideoItem, shareNameOverride?: string): string {
  227. const shareFromFilePath = getShareNameFromFilePath(song.filePath);
  228. const shareName = shareNameOverride ?? shareFromFilePath;
  229. if (song.remote_rel_path && song.remote_rel_path.length > 0) {
  230. const cleaned = song.remote_rel_path.replace(/^\/+/, '');
  231. return removeSharePrefixFromPath(cleaned, shareName, shareFromFilePath);
  232. }
  233. if (!song.filePath) {
  234. return '';
  235. }
  236. const match = song.filePath.match(/^smb:\/\/[^/]+\/([^/]+)(\/.*)?$/i);
  237. if (!match) {
  238. return song.filePath.replace(/^\/+/, '');
  239. }
  240. const remainder = match[2] ? match[2].replace(/^\/+/, '') : '';
  241. if (remainder.length === 0) {
  242. return '';
  243. }
  244. return remainder;
  245. }
  246. function extractFtpRelativePath(song: VideoItem): string {
  247. if (song.remote_rel_path && song.remote_rel_path.length > 0) {
  248. return song.remote_rel_path.replace(/^\/+/, '');
  249. }
  250. if (!song.filePath) {
  251. return '';
  252. }
  253. const match = song.filePath.match(/^ftp:\/\/[^/]+(?::\d+)?(\/.*)$/i);
  254. if (match && match[1]) {
  255. return match[1].replace(/^\/+/, '');
  256. }
  257. return song.filePath.replace(/^\/+/, '');
  258. }
  259. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  260. interface MetadataExtractionOptions {
  261. context?: common.Context;
  262. autoParseMusicName?: boolean;
  263. }
  264. interface WorkerEditMusicResult {
  265. success: boolean;
  266. error?: string;
  267. coverResult?: boolean;
  268. needRefreshList?: boolean;
  269. metadataResult?: boolean;
  270. }
  271. interface LocalEditMusicPayload {
  272. context: Context;
  273. item: VideoItem;
  274. titleStr: string;
  275. artistStr: string;
  276. ablumStr: string;
  277. yearStr: string;
  278. genreStr: string;
  279. trackStr: string;
  280. albumArtistStr: string;
  281. composerStr: string;
  282. lyricistStr: string;
  283. commentStr: string;
  284. discStr: string;
  285. lyricConStr: string;
  286. imagePathStr: string;
  287. currentPath: string;
  288. packName: string;
  289. modeType: number;
  290. autoParseMusicName: boolean;
  291. }
  292. interface WorkerMetadataPayload {
  293. originFilePath: string;
  294. originId?: string;
  295. bit_rate?: string;
  296. duration?: string;
  297. sampleRate?: string;
  298. mimeType?: string;
  299. md5Str?: string;
  300. videoSize?: number;
  301. size?: string;
  302. pixelMapPath?: string;
  303. artist?: string;
  304. album?: string;
  305. name?: string;
  306. lyricContent?: string;
  307. bits_per_raw_sample?: string;
  308. channels?: string;
  309. channel_layout?: string;
  310. start_time?: string;
  311. genre?: string;
  312. year?: string;
  313. probe_score?: number;
  314. track?: string;
  315. disc?: string;
  316. ALBUMARTIST?: string;
  317. COMPOSER?: string;
  318. COMMENT?: string;
  319. LYRICIST?: string;
  320. nb_streams?: number;
  321. nb_programs?: number;
  322. error?: string;
  323. }
  324. interface WebDavMetadataUpdatePayload {
  325. filePath: string;
  326. pixelMapPath?: string;
  327. name?: string;
  328. artist?: string;
  329. }
  330. const metadataExtractionInFlight: Set<string> = new Set();
  331. const METADATA_RETRY_DELAY_MS = 1500;
  332. const METADATA_MAX_RETRY = 120;
  333. async function scheduleMetadataExtractionFromCache(
  334. song: VideoItem,
  335. cachePath: string,
  336. options?: MetadataExtractionOptions,
  337. expectedSize?: number,
  338. retryCount: number = 0
  339. ): Promise<void> {
  340. if (!song || !cachePath || !song.filePath || !options || !options.context) {
  341. return;
  342. }
  343. if (!isRemoteCloudType(song.type ?? -1)) {
  344. return;
  345. }
  346. if (metadataExtractionInFlight.has(song.filePath)) {
  347. return;
  348. }
  349. if (song.bit_rate && song.sampleRate && song.duration) {
  350. return;
  351. }
  352. const requiredSize = expectedSize && expectedSize > 0 ? expectedSize : undefined;
  353. try {
  354. const stat = await fileIo.stat(cachePath);
  355. const ready = requiredSize !== undefined ? stat.size >= requiredSize : stat.size > 0;
  356. if (!ready) {
  357. if (retryCount >= METADATA_MAX_RETRY) {
  358. Logger.warn(TAG, `缓存尚未完成,放弃解析: ${cachePath}`);
  359. return;
  360. }
  361. setTimeout(() => {
  362. void scheduleMetadataExtractionFromCache(song, cachePath, options, expectedSize, retryCount + 1);
  363. }, METADATA_RETRY_DELAY_MS);
  364. return;
  365. }
  366. } catch (error) {
  367. if (retryCount >= METADATA_MAX_RETRY) {
  368. Logger.warn(TAG, `无法读取缓存文件,放弃解析: ${(error as Error).message}`);
  369. return;
  370. }
  371. setTimeout(() => {
  372. void scheduleMetadataExtractionFromCache(song, cachePath, options, expectedSize, retryCount + 1);
  373. }, METADATA_RETRY_DELAY_MS);
  374. return;
  375. }
  376. metadataExtractionInFlight.add(song.filePath);
  377. workerInstance.postMessage({
  378. code: 5,
  379. data: options.context,
  380. data2: cachePath,
  381. data3: song.type,
  382. data4: {
  383. name: song.name,
  384. originFilePath: song.filePath,
  385. originId: song.id,
  386. autoParseMusicName: options.autoParseMusicName ?? false
  387. }
  388. });
  389. }
  390. function sanitizePlaybackUrl(rawUrl: string | null | undefined): string {
  391. if (!rawUrl) {
  392. return '';
  393. }
  394. try {
  395. const decoded = decodeURI(rawUrl);
  396. const encoded = encodeURI(decoded);
  397. // encodeURI 不会处理 #,手动转义避免播放器把剩余内容当作片段
  398. return encoded.replace(/#/g, '%23');
  399. } catch (error) {
  400. const err = error as Error;
  401. Logger.warn(TAG, `URL 编码失败,使用降级方案: ${err?.message}`);
  402. return rawUrl.replace(/ /g, '%20').replace(/#/g, '%23');
  403. }
  404. }
  405. function cloneVideoItem(item: VideoItem): VideoItem {
  406. const copy = new VideoItem(
  407. item.name,
  408. item.id,
  409. item.filePath,
  410. item.type,
  411. item.videoSize,
  412. item.cTime,
  413. item.size,
  414. item.pixelMapPath,
  415. item.artist,
  416. item.album,
  417. item.fileName,
  418. item.lastPlayed
  419. );
  420. copy.parentPath = item.parentPath;
  421. copy.isFav = item.isFav;
  422. copy.size = item.size;
  423. copy.pixelMapPath = item.pixelMapPath;
  424. copy.artist = item.artist;
  425. copy.album = item.album;
  426. copy.duration = item.duration;
  427. copy.mimeType = item.mimeType;
  428. copy.sampleRate = item.sampleRate;
  429. copy.trackCount = item.trackCount;
  430. copy.lastPlayedStr = item.lastPlayedStr;
  431. copy.playCount = item.playCount;
  432. copy.lyricContent = item.lyricContent;
  433. copy.md5Str = item.md5Str;
  434. copy.extra_json = item.extra_json;
  435. copy.pyStr = item.pyStr;
  436. copy.bit_rate = item.bit_rate;
  437. copy.probe_score = item.probe_score;
  438. copy.year = item.year;
  439. copy.nb_streams = item.nb_streams;
  440. copy.nb_programs = item.nb_programs;
  441. copy.genre = item.genre;
  442. copy.track = item.track;
  443. copy.bits_per_raw_sample = item.bits_per_raw_sample;
  444. copy.channels = item.channels;
  445. copy.channel_layout = item.channel_layout;
  446. copy.start_time = item.start_time;
  447. copy.ALBUMARTIST = item.ALBUMARTIST;
  448. copy.COMPOSER = item.COMPOSER;
  449. copy.LYRICIST = item.LYRICIST;
  450. copy.COMMENT = item.COMMENT;
  451. copy.disc = item.disc;
  452. copy.webdav_account_id = item.webdav_account_id;
  453. copy.remote_rel_path = item.remote_rel_path;
  454. return copy;
  455. }
  456. /**
  457. * 异步设置videoUrl的辅助方法,处理WebDAV URL的构建
  458. * @param song 歌曲对象
  459. * @returns Promise<string> 完整的URL
  460. */
  461. /**
  462. * 设置videoUrl,通过webdav_account_id设置完整的 URL
  463. * @param song 歌曲对象
  464. * @returns Promise<string> 完整的URL
  465. */
  466. async function setVideoUrlForSong(song: VideoItem, options?: MetadataExtractionOptions): Promise<string> {
  467. const metadataOptions = options ?? {};
  468. Logger.info(TAG, `setVideoUrlForSong start -> name=${song.name}, type=${song.type}, path=${song.filePath}, fsId=${song.baiduFsId || song.id}`);
  469. if (isWebDavType(song.type) && song.webdav_account_id) {
  470. try {
  471. Logger.info(TAG, `WebDAV 路径信息 remote_rel_path: ${song.remote_rel_path}`);
  472. Logger.info(TAG, `WebDAV 路径信息 filePath: ${song.filePath}`);
  473. const relativePath = song.remote_rel_path || song.filePath;
  474. const manager = RemoteDriveManager.getInstance();
  475. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  476. if (account) {
  477. const cachePath = await findWebDavCacheIfExists(account, relativePath);
  478. if (cachePath) {
  479. Logger.info(TAG, `WebDAV 缓存命中,直接播放: ${cachePath}`);
  480. void scheduleMetadataExtractionFromCache(song, cachePath, metadataOptions, song.videoSize);
  481. return cachePath;
  482. }
  483. const fullUrlFromAccount = WebDavUrlUtil.buildFullUrl(account, relativePath);
  484. if (fullUrlFromAccount) {
  485. const sanitizedUrl = sanitizePlaybackUrl(fullUrlFromAccount);
  486. const downloadPromise = triggerWebDavCacheDownload(account, relativePath, sanitizedUrl);
  487. if (downloadPromise) {
  488. downloadPromise.then((completedPath?: string | null) => {
  489. if (completedPath) {
  490. void scheduleMetadataExtractionFromCache(song, completedPath, metadataOptions, song.videoSize);
  491. }
  492. }).catch((error: Error) => {
  493. Logger.error(TAG, `WebDAV 缓存后台下载失败: ${error.message}`);
  494. });
  495. }
  496. Logger.info(TAG, `WebDAV 启动异步缓存: ${relativePath}`);
  497. return sanitizedUrl;
  498. }
  499. }
  500. const fallbackUrl = await WebDavUrlUtil.buildFullUrlByAccountId(song.webdav_account_id, relativePath);
  501. if (fallbackUrl) {
  502. Logger.warn(TAG, `WebDAV 使用全局查询到的URL: ${fallbackUrl}`);
  503. return sanitizePlaybackUrl(fallbackUrl);
  504. }
  505. Logger.error(TAG, `WebDAV URL构建失败,使用原始路径: ${relativePath}`);
  506. return sanitizePlaybackUrl(relativePath);
  507. } catch (error) {
  508. Logger.error(TAG, `WebDAV URL构建出错: ${(error as Error).message}`);
  509. const fallbackPath = song.remote_rel_path || song.filePath;
  510. return sanitizePlaybackUrl(fallbackPath);
  511. }
  512. }
  513. if (isNavidromeType(song.type) && song.webdav_account_id) {
  514. try {
  515. const manager = RemoteDriveManager.getInstance();
  516. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  517. if (!account) {
  518. throw new Error('Navidrome账号不可用');
  519. }
  520. const navSongId = song.remote_rel_path || song.id || song.filePath;
  521. const streamUrl = await navidromeApi.buildStreamUrl(account, navSongId);
  522. void ServerLogUtil.info(TAG, `流地址构建成功: ${streamUrl}`);
  523. void ServerLogUtil.debug(TAG, `播放songId=${navSongId}, account=${ServerLogUtil.sanitizeAccount(account)}`);
  524. return sanitizePlaybackUrl(streamUrl);
  525. } catch (error) {
  526. const err = error as Error;
  527. void ServerLogUtil.error(TAG, `URL构建失败: ${err.message}`);
  528. throw new Error(err.message);
  529. }
  530. }
  531. if (isSmbType(song.type) && song.webdav_account_id) {
  532. try {
  533. const manager = RemoteDriveManager.getInstance();
  534. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  535. if (!account) {
  536. throw new Error('SMB账号不可用');
  537. }
  538. const relativePath = extractSmbRelativePath(song, account.smbShare);
  539. const pathInfo = await resolveCacheFilePath(
  540. RemoteCacheType.SMB,
  541. account.id?.toString(),
  542. relativePath
  543. );
  544. const streamMeta: SmbStreamingMeta = {
  545. fileSize: song.videoSize,
  546. mimeType: song.mimeType,
  547. fileName: song.fileName || song.name
  548. };
  549. const streamingUrl = await ensureSmbFileStreaming(account, pathInfo.normalizedRelative, streamMeta);
  550. Logger.info(TAG, `SMB 流地址: ${streamingUrl}`);
  551. void scheduleMetadataExtractionFromCache(song, pathInfo.cachePath, metadataOptions, song.videoSize);
  552. const shouldBypassSanitize = streamingUrl.startsWith('http://127.0.0.1:');
  553. return shouldBypassSanitize ? streamingUrl : sanitizePlaybackUrl(streamingUrl);
  554. } catch (error) {
  555. const err = error as Error;
  556. Logger.error(TAG, `SMB 流式播放失败: ${err.message}`);
  557. throw new Error(err.message);
  558. }
  559. }
  560. if (isFtpType(song.type) && song.webdav_account_id) {
  561. try {
  562. const manager = RemoteDriveManager.getInstance();
  563. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  564. if (!account) {
  565. throw new Error('FTP账号不可用');
  566. }
  567. const relativePath = extractFtpRelativePath(song);
  568. const cachedPath = await RemoteCacheManager.ensureCached(RemoteCacheType.FTP, {
  569. account,
  570. remotePath: relativePath
  571. });
  572. Logger.info(TAG, `FTP 缓存路径: ${cachedPath}`);
  573. void scheduleMetadataExtractionFromCache(song, cachedPath, metadataOptions, song.videoSize);
  574. return cachedPath;
  575. } catch (error) {
  576. const err = error as Error;
  577. Logger.error(TAG, `FTP 缓存失败: ${err.message}`);
  578. throw new Error(err.message);
  579. }
  580. }
  581. if (isBaiduType(song.type) && song.webdav_account_id) {
  582. try {
  583. const manager = RemoteDriveManager.getInstance();
  584. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  585. if (!account) {
  586. throw new Error('百度网盘账户不可用');
  587. }
  588. Logger.info(TAG, `百度网盘播放准备 - accountId: ${account.id}, fsId: ${song.baiduFsId || song.id}`);
  589. const fsId = song.baiduFsId || song.id;
  590. if (!fsId) {
  591. throw new Error('缺少百度网盘文件fs_id');
  592. }
  593. // 优先使用remote_rel_path,回退到文件名
  594. const relativePath = song.remote_rel_path || song.name || song.fileName || song.filePath;
  595. const cachedPath = await resolveCacheFilePath(
  596. RemoteCacheType.BAIDU,
  597. account.id?.toString(),
  598. relativePath
  599. );
  600. const fileExists = await FileManager.isExist(cachedPath.cachePath);
  601. if (fileExists) {
  602. const fileSize = await FileManager.getFileSize(cachedPath.cachePath);
  603. if (fileSize > 0) {
  604. Logger.info(TAG, `百度网盘文件已缓存: ${cachedPath.cachePath}`);
  605. void scheduleMetadataExtractionFromCache(song, cachedPath.cachePath, metadataOptions, song.videoSize);
  606. return cachedPath.cachePath;
  607. }
  608. }
  609. // 缓存不存在或无效,获取文件信息(包含大小和下载链接)
  610. Logger.info(TAG, `百度网盘文件未缓存,准备获取文件信息: ${relativePath}`);
  611. const fileInfo = await manager.getBaiduFileInfo(account, fsId);
  612. Logger.info(TAG, `百度网盘文件信息获取成功: 大小=${fileInfo.size}字节,链接已获取`);
  613. // 立即返回下载链接,开始播放
  614. Logger.info(TAG, `返回下载链接进行播放,同时后台缓存: ${fileInfo.dlink}`);
  615. // 异步进行缓存,不阻塞播放
  616. void (async () => {
  617. try {
  618. Logger.info(TAG, `后台开始缓存百度网盘文件: ${relativePath},大小: ${fileInfo.size}字节`);
  619. const cachedFilePath = await ensureBaiduFileCached(
  620. account,
  621. fsId,
  622. relativePath,
  623. fileInfo.dlink,
  624. fileInfo.size
  625. );
  626. Logger.info(TAG, `后台缓存完成: ${cachedFilePath}`);
  627. void scheduleMetadataExtractionFromCache(song, cachedFilePath, metadataOptions, song.videoSize);
  628. } catch (cacheError) {
  629. const cacheErr = cacheError as Error;
  630. Logger.warn(TAG, `后台缓存失败: ${cacheErr.message}`);
  631. }
  632. })();
  633. return fileInfo.dlink;
  634. } catch (error) {
  635. const err = error as Error;
  636. Logger.error(TAG, `百度网盘播放链接获取失败: ${err.message}`);
  637. throw err;
  638. }
  639. }
  640. if (isWebDavType(song.type)) {
  641. Logger.warn(TAG, `WebDAV歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
  642. return sanitizePlaybackUrl(song.filePath);
  643. }
  644. if (isSmbType(song.type)) {
  645. Logger.warn(TAG, `SMB歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
  646. return song.filePath;
  647. }
  648. if (isFtpType(song.type)) {
  649. Logger.warn(TAG, `FTP歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
  650. return song.filePath;
  651. }
  652. if (isBaiduType(song.type)) {
  653. throw new Error('百度网盘歌曲缺少webdav_account_id,无法构建播放链接');
  654. }
  655. if (isNavidromeType(song.type)) {
  656. throw new Error('Navidrome歌曲缺少webdav_account_id,无法构建播放链接');
  657. }
  658. Logger.info(TAG, `setVideoUrlForSong fallback直接返回原始路径: ${song.filePath}`);
  659. return song.filePath;
  660. }
  661. // 定义接口
  662. interface HiCarAspectRatio {
  663. ratio: number;
  664. name: string;
  665. }
  666. interface GeneratedObjectLiteralInterface_1 {
  667. assetId: string;
  668. title: string;
  669. artist: string;
  670. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  671. mediaUri: string;
  672. // 该字段大写,音频'AUDIO',视频'VIDEO'
  673. mediaType: string;
  674. mediaSize: number;
  675. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  676. startPosition: number;
  677. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  678. duration: number;
  679. albumCoverUri: string;
  680. albumTitle: string;
  681. appName: string;
  682. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  683. drmScheme: string;
  684. }
  685. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  686. const ITEM_HEIGHT: number = 65; // 列表项中高度
  687. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  688. //功能强大的音乐播放器
  689. @Preview
  690. @Component
  691. export struct LocalMusic {
  692. private prevOffsetY: number = 0; // 记录上一次的Y轴偏移量
  693. @State autoHideTitle: boolean = true //滚动自动隐藏标题栏
  694. // 字母表
  695. @State alphaBet: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
  696. 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  697. @State alphaBetStyle: GlobalAlphabetIndexerModifier = new GlobalAlphabetIndexerModifier()
  698. @State selectAlphaBetIndex: number = 0
  699. @State isShowAlphaBet: boolean = false
  700. @State isScrolling: boolean = false
  701. @State isTouchingAlphaBet: boolean = false
  702. @State alphabetHeight: number = 0
  703. public enableShowAlphabet: boolean = true // 是否显示字母表
  704. @State isShowPrecious: boolean = false //播控条显示上一首按钮
  705. //背景两侧流光控制器
  706. @State sceneBgController: HdsSceneController|undefined = deviceInfo.sdkApiVersion>=20
  707. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  708. new HdsSceneController()
  709. .setSceneParams({
  710. backgroundMaskColors: [Color.Green, Color.Red],
  711. firstEdgeFlowLight: {
  712. startPos: 0,
  713. endPos: 0.5,
  714. color: Color.Red
  715. },
  716. secondEdgeFlowLight: {
  717. startPos: 0,
  718. endPos: -0.5,
  719. color: Color.Green
  720. }
  721. }) : undefined;
  722. //背景流光控制器
  723. @State bgController: hdsEffect.ShaderEffectController|undefined = deviceInfo.sdkApiVersion>=20
  724. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  725. new hdsEffect.ShaderEffectController():undefined;
  726. @State showAddSheet:boolean = false
  727. searchController: SearchController = new SearchController()
  728. @State rightTopImage:Resource = $r('sys.symbol.sort')
  729. @State isEditAudio:boolean = false
  730. @State isExtractAcc:boolean = false
  731. @State isConverter:boolean = false
  732. @State isAIVoiceSeparation:boolean = false
  733. @State isExtractAudio:boolean = false
  734. @State isMergeAudio:boolean = false
  735. @State isCopyFileToDownLoad: boolean = false
  736. @State isChangeTone:boolean = false
  737. @State offHeight: number = 75
  738. @State currentSongList: Array<VideoItem> = []//当前歌单
  739. @Consume currentSongListName:string //当前歌单名称
  740. @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
  741. @State isRefreshing: boolean = false;
  742. @State maxRefreshingHeight: number = 100.0;
  743. private contentNode?: ComponentContent<Object> = undefined;
  744. // WebDAV相关实例变量(现在改为从内存读取,不再需要存储)
  745. @State ratioL: number = 1;
  746. @State mediaKuCount: number = 0;
  747. @State albumCount: number = 0;
  748. @State artistCount: number = 0;
  749. @State fastForwardSeconds: string = '10'
  750. @State isShowBackFast: boolean = true//快进快退按钮
  751. @State isCanAuto:boolean = true
  752. @State opacityValueImage: number = 1;
  753. @State tipPopup:boolean = false
  754. @Consume mType: number;
  755. @StorageProp('themeColor') themeColor: string =
  756. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  757. themeMode: number = 0;
  758. @State titleName: string = '首页'
  759. @State textStr: string = ''
  760. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  761. // private download_path: string = '';
  762. @Consume rootPath: string //音频根目录
  763. @Consume currentPath: string
  764. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  765. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  766. @State lockPath: string = ''
  767. @State favPath: string = ''
  768. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  769. @State historyPath: string = ''
  770. @State historyList: Array<VideoItem> = []
  771. @Consume isHistory: boolean
  772. static readonly HISTORY_MUSIC: string = 'music_historyList';
  773. private table: MediaTable = new MediaTable(getContext(this))
  774. private playlistTable: PlaylistTable | null = null
  775. private deletionWatcher: FileDeletionWatcher | null = null
  776. @State allPlaylists: Playlist[] = []
  777. @State isZero: boolean = false
  778. @State fileList: Array<string> = []
  779. @State dirList: Array<VideoItem> = []
  780. @Consume videoLocalList:VideoItem[]
  781. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  782. @State listRefreshKey: number = 0
  783. // @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  784. @StorageProp('mediaKuList') mediaKuList: Array<VideoItem> = []; //媒体库文件
  785. @State artistList: Array<VideoItem> = []; //艺术家文件
  786. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  787. @State albumList: Array<VideoItem> = []; //专辑文件
  788. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  789. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  790. @State imageOpacities: number[] = [];
  791. @Consume isCanBack: boolean
  792. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  793. @State showSingleLyric: boolean = false
  794. @State sortType: number = 4 //默认排序方式
  795. @State isShowSimi: boolean = false //是否显示私密音频
  796. @State isShowFAV: boolean = true //是否显示我的收藏
  797. @State isShowTitleBar: boolean = true //是否显示分类导航条
  798. @State isShowAllBar: boolean = true //是否显示播放全部条
  799. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  800. @State isShowHistory: boolean = true //是否显示最近播放
  801. @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
  802. @State isGridMusic: boolean = false //是否网格布局
  803. @State isCircleBtn: boolean = false //是否圆形播放按钮
  804. @State twoFingerType: number = 3 //双支放大缩小的类型
  805. @State isScrollHide: boolean = false //是否滚动隐藏
  806. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  807. @State isStartAutoPlay: boolean = false //启动后自动播放
  808. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  809. @State isShowHeader: boolean = true
  810. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  811. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  812. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  813. @State isSwipe: boolean = false //listItem的左滑开关
  814. @State openSkipSongAnimate: boolean = true//切歌动画效果
  815. @State customizeBgPath: string | undefined = '';
  816. @State isDarkMode: boolean = false
  817. @State lyricTextWeight: number = 400
  818. @State lyricTextWeightPip: number = 400
  819. @State currentSwiperIndex: number = 0
  820. @State blurValue: number = 0 //背景模糊
  821. @State bgBrightness: number = 0 //背景亮度
  822. private listScroller: ListScroller = new ListScroller()
  823. private playListScroller: Scroller = new Scroller()
  824. @State isOneKeyTags:boolean = false
  825. @State isFixMessy:boolean = false
  826. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  827. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  828. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  829. @StorageProp('windowWidth') windowWidth: number = 0;
  830. @StorageProp('windowHeight') windowHeight: number = 0;
  831. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  832. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  833. private UNKONWN:string = '';
  834. private listArea: Area = {
  835. width: 0,
  836. height: 0,
  837. position: {},
  838. globalPosition: {}
  839. }
  840. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  841. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  842. // WebDAV认证信息缓存(作为实例变量,比全局上下文更可靠)
  843. private currentWebDavAuthInfo: WebDavAuthItem | null = null;
  844. //瀑布流的列数横竖屏动态切换
  845. onIsLandscapeChange() {
  846. if(this.isLandscape){
  847. this.columns = 4
  848. }else{
  849. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  850. }
  851. }
  852. onColorModeChange() {
  853. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  854. }
  855. //点击某个歌单id发生变化的时候回调
  856. onIDChange(){
  857. console.log('onecold 歌单id发生变化this.currentSongListID='+this.currentSongListID)
  858. console.log('onecold 歌单id发生变化this.currentSongListName='+this.currentSongListName)
  859. if(this.modeType==4){
  860. this.titleName = this.currentSongListName
  861. this.rightTopImage = $r('sys.symbol.sort')
  862. //获取缓存
  863. const cacheSongs:string =PreferencesUtil.getStringSync(this.currentSongListID+'currentSongList', '')
  864. console.log('onecold 歌单id发生变化获取缓存2 cacheSongs = '+cacheSongs)
  865. if(StrUtil.isNotEmpty(cacheSongs)){
  866. this.currentSongList = JSON.parse(cacheSongs) as VideoItem[]
  867. this.updateListData(this.currentSongList, true)
  868. }
  869. this.doSongListTask()//获取歌单信息
  870. }
  871. }
  872. async doSongListTask() {
  873. // 初始化歌单数据库
  874. const playlistTable = new PlaylistTable(this.context);
  875. // 查询歌单中的所有歌曲
  876. const playlistSongs: PlaylistSong[] = await playlistTable.queryPlaylistSongs(this.currentSongListID);
  877. console.log('onecold 歌单id发生变化获取缓存7 playlistSongs='+playlistSongs.length)
  878. if (ArrayUtil.isEmpty(playlistSongs)) {
  879. this.updateListData([], true)
  880. } else {
  881. this.currentSongList = await convertPlaylistSongsToVideoItems(this.context, playlistSongs);
  882. console.log('onecold 从数据库读取的歌曲为 playlistSongs='+this.currentSongList.length)
  883. this.updateListData(this.currentSongList, true)
  884. if (ArrayUtil.isNotEmpty(this.currentSongList)&&this.currentSongList.length > 100) {
  885. // 只保存前100条记录到缓存中
  886. let canceList = this.currentSongList.slice(0, 100);
  887. PreferencesUtil.putSync(this.currentSongListID+'currentSongList',
  888. JSON.stringify(canceList))
  889. } else {
  890. PreferencesUtil.putSync(this.currentSongListID+'currentSongList', JSON.stringify(this.currentSongList));
  891. }
  892. }
  893. this.isRefreshing = false
  894. }
  895. onModeChange() {
  896. this.isFavMusic = false
  897. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  898. switch (this.modeType) {
  899. case 0:
  900. this.getSortedFiles(this.currentPath)
  901. break
  902. case 1:
  903. this.rightTopImage = $r('sys.symbol.sort')
  904. this.updateListData(this.mediaKuList)
  905. this.titleName = Utility.resourceToString(this.context,$r('app.string.media_ku'))
  906. break
  907. case 2:
  908. this.rightTopImage = $r('sys.symbol.sort')
  909. this.updateListData(this.artistList)
  910. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  911. break
  912. case 3:
  913. this.rightTopImage = $r('sys.symbol.sort')
  914. this.updateListData(this.albumList)
  915. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  916. break
  917. }
  918. }
  919. // @Consume currentSong: VideoItem | undefined;
  920. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  921. // @StorageLink('isPlay') isPlay: boolean = false;
  922. @Consume isShowPlay: boolean ;
  923. @StorageLink('songList') songList: Array<VideoItem> = [];
  924. @State translateY: number = 0;
  925. @State isShowSheet: boolean = false;
  926. @State isShowSheetView: boolean = false;
  927. @State isShowTimeCloseView: boolean = false;
  928. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  929. @StorageLink('currIndex') curIndex: number = 0;
  930. @Consume isShowDrawer: boolean;
  931. @Consume offsetX: number;
  932. @State isFac: boolean = false;
  933. @State favList: Array<VideoItem> = []
  934. @Consume isFavMusic: boolean
  935. @State isClickedPLayAll: boolean = false;
  936. private scrollerForlist: ListScroller = new ListScroller();
  937. private knockController: KnockController | undefined = undefined;
  938. // 修改为:
  939. imagesF: ImageFrameInfo[] = CommonConstants.IMAGE_FRAME_INFO;
  940. @StorageProp('animationState') animationState: AnimationStatus = AnimationStatus.Initial
  941. // 缓存机制
  942. private cache: Map<string, Array<VideoItem>> = new Map();
  943. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  944. // 持久化缓存
  945. private async saveCacheToStorage() {
  946. const cacheArray = Array.from(this.cache.entries());
  947. const stringCacheArray = Array.from(this.stringCache.entries());
  948. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  949. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  950. }
  951. // 载入缓存
  952. private async loadCacheFromStorage() {
  953. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  954. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  955. if (cacheString) {
  956. const parsedCache: Object | null = JSON.parse(cacheString);
  957. if (parsedCache && Array.isArray(parsedCache)) {
  958. const cacheArray: [string, Array<VideoItem>][] = parsedCache;
  959. this.cache = new Map(cacheArray);
  960. }
  961. }
  962. if (stringCacheString) {
  963. const parsedStringCache: Object | null = JSON.parse(stringCacheString);
  964. if (parsedStringCache && Array.isArray(parsedStringCache)) {
  965. const stringCacheArray: [string, string][] = parsedStringCache;
  966. this.stringCache = new Map(stringCacheArray);
  967. }
  968. }
  969. }
  970. // 查找缓存
  971. private findCache(key: string): Array<VideoItem> | undefined {
  972. return this.cache.get(key);
  973. }
  974. // 查找字符串缓存
  975. private findStringCache(key: string): string | undefined {
  976. return this.stringCache.get(key);
  977. }
  978. // 添加缓存
  979. private addCache(key: string, value: Array<VideoItem>) {
  980. this.cache.set(key, value);
  981. }
  982. // 添加字符串缓存
  983. private addStringCache(key: string, value: string) {
  984. this.stringCache.set(key, value);
  985. }
  986. // 删除缓存
  987. private deleteCache(key: string) {
  988. this.cache.delete(key);
  989. this.saveCacheToStorage()
  990. }
  991. // 删除字符串缓存
  992. private deleteStringCache(key: string) {
  993. this.stringCache.delete(key);
  994. }
  995. // 多选机制
  996. @State selectedFiles: Array<VideoItem> = [];
  997. @Consume isMultiSelect: boolean;
  998. @State isAllSelected: boolean = false;
  999. @State appName: string = ''
  1000. @State isHasDir: boolean = false
  1001. @State packName: string = ''
  1002. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  1003. doSwipBack() {
  1004. if(this.isSearchMode){
  1005. console.info('onecold doSwipBack = ' +this.isSearchMode)
  1006. this.isSearchMode = false
  1007. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  1008. this.searchText = ''
  1009. this.getSortedFiles(this.currentPath)
  1010. return
  1011. }
  1012. this.onSearchInput('')
  1013. return
  1014. }
  1015. this.isZero = false
  1016. if (this.modeType !== 0 && this.isCanBack) {
  1017. this.onModeChange()
  1018. this.isCanBack = false
  1019. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  1020. setTimeout(() => {
  1021. if (this.modeType == 2) {
  1022. if (this.isGridMusic||this.twoFingerType==4) {
  1023. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  1024. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  1025. if(this.twoFingerType==4){
  1026. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  1027. }else{
  1028. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1029. }
  1030. } else {
  1031. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  1032. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1033. }
  1034. } else if (this.modeType == 3) {
  1035. if (this.isGridMusic||this.twoFingerType==4) {
  1036. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  1037. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 0
  1038. if(this.twoFingerType==4){
  1039. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  1040. }else{
  1041. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1042. }
  1043. } else {
  1044. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  1045. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1046. }
  1047. }
  1048. }, 200)
  1049. return
  1050. }
  1051. if (this.isHistory || this.isFavMusic) {
  1052. this.isHistory = false
  1053. this.getSortedFiles(this.currentPath)
  1054. return
  1055. }
  1056. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  1057. animateTo({ duration: 555 }, () => {
  1058. // 动画闭包内控制Image组件的出现和消失
  1059. this.isShowDrawer = !this.isShowDrawer
  1060. this.offsetX = 0
  1061. })
  1062. return
  1063. }
  1064. //返回上一级歌单的滚动位置
  1065. setTimeout(() => {
  1066. if (this.modeType == 0) {
  1067. if (this.isGridMusic||this.twoFingerType==4) {
  1068. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  1069. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
  1070. if(this.twoFingerType==4){
  1071. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  1072. }else{
  1073. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1074. }
  1075. } else {
  1076. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  1077. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1078. }
  1079. }
  1080. }, 300)
  1081. this.currentPath = Utility.getParentDirectory(this.currentPath)
  1082. Logger.info('this.currentPath2 = ' + this.currentPath)
  1083. this.getSortedFiles(this.currentPath)
  1084. }
  1085. // 组件生命周期
  1086. aboutToAppear() {
  1087. console.info('onecold aboutToAppear sdkApiVersion = '+deviceInfo.sdkApiVersion)
  1088. if(ArrayUtil.isNotEmpty(this.videoLocalList)&&this.modeType==0){
  1089. this.updateListData(this.videoLocalList)
  1090. }
  1091. // 初始化 PlaylistTable
  1092. this.playlistTable = new PlaylistTable(getContext(this))
  1093. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  1094. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  1095. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  1096. this.tipPopup = !this.tipPopup
  1097. PreferencesUtil.putSync('isFirstTiped',false)
  1098. }
  1099. this.initSetting()
  1100. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  1101. Utility.getAppName(getContext(this)).then((appName: string) => {
  1102. this.appName = appName
  1103. })
  1104. this.packName = AppUtil.getBundleName()
  1105. this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
  1106. this.loadCacheFromStorage(); // 加载文件夹缓存
  1107. // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
  1108. this.initLoadCache()
  1109. this.mkDownLoadDir()
  1110. let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
  1111. // 监听广播事件(打开其他应用处理)
  1112. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  1113. this.saveVideoDatas([eventData.data?.message], true)
  1114. });
  1115. //侧滑广播接收时间
  1116. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
  1117. // 监听广播事件(打开其他应用处理)
  1118. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  1119. animateTo({ duration: 555 }, () => {
  1120. this.doSwipBack()
  1121. })
  1122. });
  1123. //ScanFilePage广播接收时间
  1124. let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
  1125. // 监听ScanFilePage广播事件(更新数据库)
  1126. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  1127. this.doUpdateData()
  1128. });
  1129. // 监听歌单播放请求事件
  1130. let eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY }
  1131. emitter.on(eventPlaylistPlay, async (eventData: emitter.EventData) => {
  1132. const data = eventData.data as Record<string, Object>
  1133. if (!data) {
  1134. Logger.error('heanup eventPlaylistPlay: eventData.data is undefined or null')
  1135. return
  1136. }
  1137. // 检查歌单播放数据结构
  1138. if (data.playlistId && data.songFilePaths && data.startIndex !== undefined) {
  1139. const playlistData: PlaylistEventData = {
  1140. playlistId: data.playlistId as string,
  1141. playlistName: data.playlistName as string,
  1142. songCount: data.songCount as number,
  1143. startIndex: data.startIndex as number,
  1144. isJump: data.isJump as boolean,
  1145. songFilePaths: data.songFilePaths as string[]
  1146. }
  1147. await this.handlePlaylistPlayRequest(
  1148. playlistData.playlistId,
  1149. playlistData.playlistName,
  1150. playlistData.songFilePaths,
  1151. playlistData.startIndex,
  1152. playlistData.isJump,
  1153. )
  1154. return
  1155. }
  1156. Logger.error('heanup eventPlaylistPlay: 接收到无效的数据结构')
  1157. });
  1158. let eventRefreshSort: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_REFRESH_SORT }
  1159. // 监听广播事件(通用设置配置更新)
  1160. emitter.on(eventRefreshSort, (eventData: emitter.EventData) => {
  1161. if(this.modeType ==4){
  1162. this.doSongListTask()//获取歌单信息
  1163. }
  1164. });
  1165. let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
  1166. // 监听广播事件(通用设置配置更新)
  1167. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  1168. this.doChangeSetting()
  1169. });
  1170. let event: Callback<InterruptEvent> = (event) => {
  1171. // LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  1172. console.info(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  1173. this.savePlaybackPosition()
  1174. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  1175. this.pause();
  1176. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  1177. console.info(`onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  1178. console.info('onecold startPlayOrResumePlay 514')
  1179. this.startPlayOrResumePlay();
  1180. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  1181. console.info(`onecold 与其他应用音频冲突 被截断点 INTERRUPT_HINT_STOP`)
  1182. if(!this.isSameTimePlay){
  1183. this.stop();
  1184. }
  1185. }
  1186. }
  1187. this.mIjkMediaPlayer.on('audioInterrupt', event);
  1188. // 音频设备断连回调处理比如蓝牙耳机断开
  1189. let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  1190. LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  1191. if (event.reason === DeviceChangeReason.REASON_NEW_DEVICE_AVAILABLE) { // 音频设备连接
  1192. } else if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  1193. console.info('onecold 音频设备断开连接, 暂停播放')
  1194. this.pause();
  1195. }
  1196. }
  1197. // 订阅音频设备断开和连接事件
  1198. this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  1199. const eventPause: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_PAUSE }
  1200. // 监听广播事件(hicar断开暂停播放)
  1201. emitter.on(eventPause, (eventData: emitter.EventData) => {
  1202. this.pause();
  1203. });
  1204. // 有线耳机断开和连接的监听。监听音频设备状态变化。
  1205. let audioManager = audio.getAudioManager(); // 需要先创建AudioManager实例。
  1206. let audioRoutingManager = audioManager.getRoutingManager(); // 再调用AudioManager的方法创建AudioRoutingManager实例。
  1207. audioRoutingManager.on('deviceChange', audio.DeviceFlag.INPUT_DEVICES_FLAG, (deviceChanged: audio.DeviceChangeAction) => {
  1208. console.info('device change type : ' + deviceChanged.type); // 设备连接状态变化,0为连接,1为断开连接。
  1209. if(deviceChanged.type==1){
  1210. this.pause();
  1211. }
  1212. });
  1213. this.makeWorker()
  1214. //折叠屏的屏幕显示模式变化
  1215. display.on('foldDisplayModeChange', (data) => {
  1216. this.doChangeBarHeight()
  1217. });
  1218. display.on('foldStatusChange', (data) => {
  1219. Logger.info('onecold foldStatusChange ')
  1220. });
  1221. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  1222. // 读取 themeMode 并同步 currentColorMode
  1223. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  1224. this.applyThemeMode(this.themeMode)
  1225. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  1226. AppStorage.setOrCreate('themeColor', themeColor);
  1227. this.themeColor = themeColor;
  1228. this.doChangeSetting()
  1229. this.windowClass.on('windowSizeChange', (size) => {
  1230. LogUtil.info('onecold windowSizeChange')
  1231. this.doChangeBarHeight()
  1232. let viewWidth = px2vp(size.width);
  1233. let viewHeight = px2vp(size.height);
  1234. if(this.isPhoneLan()){
  1235. this.is_auto_hide_progress = false
  1236. if(this.isHiCar()){
  1237. return
  1238. }
  1239. setTimeout(() => {
  1240. this.is_auto_hide_progress = true
  1241. }, 6000)
  1242. }else{
  1243. this.startAutoHide()
  1244. }
  1245. });
  1246. this.eventHub.on('onStateChange', (fg: boolean) => {
  1247. if (fg && this.curState === 'STARTED') {
  1248. this.stopPip();
  1249. }
  1250. });
  1251. //NewIndex的博空调收到eventHub消息控制播放
  1252. this.getUIContext().getHostContext()!.eventHub.on('playOrPause', () => {
  1253. if (ArrayUtil.isNotEmpty(this.songList)) {
  1254. this.playOrPause();
  1255. } else {
  1256. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1257. }
  1258. });
  1259. this.getUIContext().getHostContext()!.eventHub.on('playPrevious', () => {
  1260. if (ArrayUtil.isNotEmpty(this.songList)) {
  1261. this.playPrevious();
  1262. } else {
  1263. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1264. }
  1265. });
  1266. this.getUIContext().getHostContext()!.eventHub.on('playNext', () => {
  1267. if (ArrayUtil.isNotEmpty(this.songList)) {
  1268. this.playNext();
  1269. } else {
  1270. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1271. }
  1272. });
  1273. this.getUIContext().getHostContext()!.eventHub.on('showPlayerView', () => {
  1274. this.showPlayerView();
  1275. });
  1276. this.getUIContext().getHostContext()!.eventHub.on('openPlayList', () => {
  1277. this.openPlayList();
  1278. });
  1279. }
  1280. //载入媒体库,艺术家,专辑等缓存
  1281. initLoadCache(){
  1282. this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
  1283. this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
  1284. this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
  1285. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  1286. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  1287. if(ArrayUtil.isNotEmpty(cachedList)){
  1288. this.mediaKuList = cachedList
  1289. if(this.modeType==1){
  1290. this.updateListData(this.mediaKuList)
  1291. }
  1292. }
  1293. let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
  1294. let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
  1295. if(ArrayUtil.isNotEmpty(artistCachedList)){
  1296. this.artistList = artistCachedList
  1297. let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
  1298. const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
  1299. this.artistMap = new Map(parsedArray);
  1300. // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
  1301. if(this.modeType==2){
  1302. this.updateListData(this.artistList)
  1303. }
  1304. }
  1305. let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
  1306. let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
  1307. if(ArrayUtil.isNotEmpty(albumCachedList)){
  1308. this.albumList = albumCachedList
  1309. let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
  1310. const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
  1311. this.albumMap = new Map(parsedArray);
  1312. if(this.modeType==3){
  1313. this.updateListData(this.albumList)
  1314. }
  1315. }
  1316. }
  1317. startAutoHide() {
  1318. if(this.isHiCar()){
  1319. return
  1320. }
  1321. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  1322. console.info('onecold startAutoHide')
  1323. this.is_auto_hide_progress = false
  1324. setTimeout(() => {
  1325. this.is_auto_hide_progress = true
  1326. }, 6000)
  1327. }
  1328. }
  1329. applyThemeMode(mode: number) {
  1330. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  1331. if (mode === 1) {
  1332. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  1333. } else if (mode === 2) {
  1334. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1335. }
  1336. AppStorage.setOrCreate('currentColorMode', colorMode)
  1337. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  1338. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  1339. AppStorage.setOrCreate('themeMode', mode)
  1340. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1341. // 只有强制浅色/深色时才主动设置
  1342. const context = getContext(this) as common.UIAbilityContext
  1343. context.getApplicationContext().setColorMode(colorMode)
  1344. }
  1345. initSetting() {
  1346. this.autoHideTitle = PreferencesUtil.getBooleanSync('autoHideTitle', true)
  1347. this.isShowPrecious = PreferencesUtil.getBooleanSync('isShowPrecious', false)
  1348. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1349. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  1350. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  1351. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, false)
  1352. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  1353. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  1354. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  1355. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  1356. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  1357. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  1358. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  1359. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  1360. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  1361. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 2)
  1362. this.isCoverTop = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP, true)
  1363. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  1364. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  1365. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  1366. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  1367. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  1368. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  1369. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  1370. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  1371. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  1372. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  1373. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  1374. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  1375. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  1376. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  1377. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  1378. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  1379. this.isCopyFileToDownLoad = PreferencesUtil.getBooleanSync(SettingPage.IS_COPYFILE_TO_DOWNLOAD, false)
  1380. let audioManager = audio.getAudioManager();
  1381. let audioSessionManager: audio.AudioSessionManager = audioManager.getSessionManager();
  1382. if(this.isSameTimePlay){
  1383. //与其他应用同时播放,关键代码
  1384. let strategy: audio.AudioSessionStrategy = {
  1385. concurrencyMode: audio.AudioConcurrencyMode.CONCURRENCY_MIX_WITH_OTHERS
  1386. };
  1387. audioSessionManager.activateAudioSession(strategy).then(() => {
  1388. console.info('onecold Succeeded in doing activateAudioSession.');
  1389. }).catch((err: BusinessError) => {
  1390. console.error(`Failed to activateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1391. });
  1392. }else{
  1393. let isActivated = audioSessionManager.isAudioSessionActivated();
  1394. if(isActivated){
  1395. audioSessionManager.deactivateAudioSession().then(() => {
  1396. console.info('Succeeded in doing deactivateAudioSession.');
  1397. }).catch((err: BusinessError) => {
  1398. console.error(`Failed to deactivateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1399. });
  1400. }
  1401. }
  1402. if(this.volumeSmall){
  1403. this.volume = 0.5
  1404. }else{
  1405. this.volume = 1
  1406. }
  1407. //如果是hicar连接状态,这些都是false
  1408. if(this.isHiCar()){
  1409. this.autoHideTitle = false
  1410. this.isCoverRectangle= true
  1411. this.columns=4
  1412. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  1413. {
  1414. this.isGridMusic= false//用list不用网格
  1415. this.isCoverTopBig = false
  1416. }
  1417. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  1418. }
  1419. if (this.isSavePlayMode) {
  1420. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  1421. }
  1422. }
  1423. doChangeSetting() {
  1424. this.initSetting()
  1425. this.deleteCache(this.currentPath)
  1426. if (this.modeType === 0) {
  1427. this.getSortedFiles(this.currentPath)
  1428. }
  1429. }
  1430. doChangeBarHeight() {
  1431. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  1432. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  1433. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  1434. this.setBarHeightNormal()
  1435. }
  1436. }
  1437. onPageShow() {
  1438. this.knockController?.immersiveListening();
  1439. app.setImageCacheCount(100);
  1440. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  1441. app.setImageRawDataCacheSize(104857600);
  1442. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  1443. }
  1444. //开启线程查看各个数据库
  1445. makeWorker() {
  1446. setTimeout(() => {
  1447. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  1448. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  1449. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  1450. // workerInstance.postMessage({
  1451. // code: 1,
  1452. // data1: this.context,
  1453. // data2: this.rootPath,
  1454. // data3: this.lockPath,
  1455. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1456. // data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  1457. // });
  1458. PreferencesUtil.putSync('isFirstApp', false)
  1459. } else {
  1460. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1461. workerInstance.postMessage({ code: 3, data: this.context });
  1462. workerInstance.postMessage({ code: 4, data: this.context });
  1463. this.getHistoryList(false)
  1464. }
  1465. }, 1000)
  1466. workerInstance.onmessage = (e: MessageEvents): void => {
  1467. switch (e.data.code) {
  1468. case 101: //第一次扫描文件夹入库
  1469. ToastUtil.showToast('刷新同步数据库成功!')
  1470. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  1471. this.doAllUpdateData()
  1472. break;
  1473. case 102: //查询媒体库列表
  1474. this.isRefreshing = false
  1475. this.mediaKuList = e.data.data
  1476. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  1477. Utility.doSortListAscending(this.mediaKuList)
  1478. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  1479. if (this.modeType === 1) {
  1480. this.updateListData(this.mediaKuList)
  1481. }
  1482. PreferencesUtil.putSync('mediaKuCount', this.mediaKuList.length)
  1483. // 处理媒体库前100条记录,列表长度并存储到PreferencesUtil
  1484. if (ArrayUtil.isNotEmpty(this.mediaKuList)&&this.mediaKuList.length > 100) {
  1485. // 只保存前100条记录到缓存中
  1486. let truncatedList = this.mediaKuList.slice(0, 100);
  1487. PreferencesUtil.putSync('mediaKuList', JSON.stringify(truncatedList));
  1488. } else {
  1489. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  1490. }
  1491. break;
  1492. case 103: //收到查询艺术家列表
  1493. this.isRefreshing = false
  1494. this.artistMap = e.data.data1;
  1495. this.artistList = e.data.data2;
  1496. PreferencesUtil.putSync('artistCount', this.artistList.length)
  1497. // 处理艺术家前100条记录,列表长度并存储到PreferencesUtil
  1498. if (ArrayUtil.isNotEmpty(this.artistList)&&this.artistList.length > 100) {
  1499. // 只保存前100条记录到缓存中
  1500. let truncatedList = this.artistList.slice(0, 100);
  1501. PreferencesUtil.putSync('artistList', JSON.stringify(truncatedList));
  1502. } else {
  1503. PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
  1504. }
  1505. // 处理并缓存前60条艺术家数据
  1506. const sortedEntries = Array.from(this.artistMap.entries())
  1507. .sort((a, b) => b[1].length - a[1].length)
  1508. .slice(0, 60);
  1509. PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
  1510. break;
  1511. case 104: //收到查询专辑列表
  1512. this.isRefreshing = false
  1513. this.albumMap = e.data.data1;
  1514. this.albumList = e.data.data2
  1515. //查询完毕在启动是否自动播放
  1516. if (this.isStartAutoPlay&&this.isCanAuto) {
  1517. this.isCanAuto = false
  1518. console.info('onecold startPlayOrResumePlay 757')
  1519. this.startPlayOrResumePlay()
  1520. }
  1521. PreferencesUtil.putSync('albumCount', this.albumList.length)
  1522. // 处理专辑前100条记录,列表长度并存储到PreferencesUtil
  1523. if (ArrayUtil.isNotEmpty(this.albumList)&&this.albumList.length > 100) {
  1524. // 只保存前100条记录到缓存中
  1525. let truncatedList = this.albumList.slice(0, 100);
  1526. PreferencesUtil.putSync('albumList', JSON.stringify(truncatedList));
  1527. } else {
  1528. PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
  1529. }
  1530. const mapArrayAlbum = Array.from(this.albumMap.entries())
  1531. .sort((a, b) => b[1].length - a[1].length)
  1532. .slice(0, 60);
  1533. PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
  1534. break;
  1535. case 105: // 缓存完成后返回的元数据
  1536. this.handleWorkerMetadataPayload(e.data.data as WorkerMetadataPayload);
  1537. break;
  1538. case 106: // 编辑音乐元数据和封面完成
  1539. this.handleEditMusicResult(e.data);
  1540. break;
  1541. }
  1542. };
  1543. // 在调用terminate后,执行onexit
  1544. workerInstance.onexit = (code) => {
  1545. metadataExtractionInFlight.clear();
  1546. Logger.info(TAG, 'workerInstance 线程已退出,code: ' + code);
  1547. }
  1548. workerInstance.onerror = (err: ErrorEvent) => {
  1549. metadataExtractionInFlight.clear();
  1550. console.error('workerInstance 线程执行发生异常: ' + err.message)
  1551. }
  1552. }
  1553. private handleWorkerMetadataPayload(payload: WorkerMetadataPayload | undefined): void {
  1554. if (!payload || !payload.originFilePath) {
  1555. return;
  1556. }
  1557. metadataExtractionInFlight.delete(payload.originFilePath);
  1558. if (payload.error) {
  1559. Logger.warn(TAG, `缓存文件元数据解析失败: ${payload.error}`);
  1560. return;
  1561. }
  1562. this.applyMetadataToCollections(payload.originFilePath, payload);
  1563. }
  1564. private applyMetadataToCollections(filePath: string, payload: WorkerMetadataPayload): void {
  1565. const targets: Array<VideoItem> = [];
  1566. let mainListUpdated = false;
  1567. let playlistUpdated = false;
  1568. if (this.currentSong && this.currentSong.filePath === filePath) {
  1569. targets.push(this.currentSong);
  1570. }
  1571. const collectFromList = (list?: Array<VideoItem>, markUpdated?: () => void) => {
  1572. if (!list || list.length === 0) {
  1573. return;
  1574. }
  1575. const found = Utility.getItemByFilePath(list, filePath);
  1576. if (found) {
  1577. markUpdated?.();
  1578. targets.push(found);
  1579. }
  1580. };
  1581. collectFromList(this.videoLocalList, () => {
  1582. mainListUpdated = true;
  1583. });
  1584. collectFromList(this.songList, () => {
  1585. playlistUpdated = true;
  1586. });
  1587. collectFromList(this.historyList);
  1588. collectFromList(this.favList);
  1589. const remoteManager = RemoteDriveManager.getInstance();
  1590. collectFromList(remoteManager.webDavSongs);
  1591. const updated = new Set<VideoItem>();
  1592. const remoteMetadataUpdates: Map<string, WebDavMetadataUpdatePayload> = new Map();
  1593. for (let i = 0; i < targets.length; i++) {
  1594. const target = targets[i];
  1595. if (!target || updated.has(target)) {
  1596. continue;
  1597. }
  1598. updated.add(target);
  1599. this.mergeVideoItemWithPayload(target, payload);
  1600. if (isRemoteCloudType(target.type) && StrUtil.isNotEmpty(target.filePath)) {
  1601. remoteMetadataUpdates.set(target.filePath, {
  1602. filePath: target.filePath,
  1603. pixelMapPath: target.pixelMapPath,
  1604. name: target.name,
  1605. artist: target.artist
  1606. });
  1607. }
  1608. }
  1609. if (this.currentSong && this.currentSong.filePath === filePath) {
  1610. this.mergeVideoItemWithPayload(this.currentSong, payload);
  1611. if (payload.name) {
  1612. this.name = payload.name;
  1613. }
  1614. if (payload.artist) {
  1615. this.artist = payload.artist;
  1616. }
  1617. if (payload.pixelMapPath) {
  1618. this.cover = payload.pixelMapPath;
  1619. }
  1620. if (payload.lyricContent) {
  1621. this.applyInlineLyricContent(payload.lyricContent);
  1622. }
  1623. let avSessionDurationMs = this.duration;
  1624. if (payload.duration) {
  1625. const durationSeconds = Number(payload.duration);
  1626. if (!Number.isNaN(durationSeconds) && durationSeconds > 0) {
  1627. avSessionDurationMs = durationSeconds * 1000;
  1628. this.duration = avSessionDurationMs;
  1629. this.durationTime = Math.floor(avSessionDurationMs / 1000);
  1630. this.durationStringTime = secondToTime(this.durationTime);
  1631. }
  1632. }
  1633. if (avSessionDurationMs > 0) {
  1634. this.avSessionController.setAVMetadataMusic(this.currentSong, avSessionDurationMs, this.lyricContent);
  1635. }
  1636. this.currentSong = cloneVideoItem(this.currentSong);
  1637. AppStorage.setOrCreate('currentSong', this.currentSong);
  1638. }
  1639. const primaryTarget = targets.length > 0 ? targets[0] : undefined;
  1640. if (primaryTarget) {
  1641. this.persistRemoteMetadataToDb(primaryTarget).catch((error: Error) => {
  1642. Logger.error(TAG, `缓存元数据持久化失败: ${error.message}`);
  1643. });
  1644. }
  1645. if (remoteMetadataUpdates.size > 0) {
  1646. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  1647. emitter.emit(eventUpdate, { data: Array.from(remoteMetadataUpdates.values()) });
  1648. }
  1649. this.refreshLazyListViews(mainListUpdated, playlistUpdated);
  1650. }
  1651. private handleEditMusicResult(result: WorkerEditMusicResult): void {
  1652. // 关闭进度条
  1653. DialogHelper.closeLoading();
  1654. if (result.success) {
  1655. console.log("heanup 编辑信息成功,数据库已同步");
  1656. if (result.coverResult) {
  1657. ToastUtil.showToast('内嵌封面成功');
  1658. }
  1659. ToastUtil.showToast('内嵌音乐标签成功');
  1660. this.isShowMoreView = false;
  1661. this.name = this.titleStr;
  1662. // 同步当前播放的歌曲信息
  1663. if (this.editingItem && this.editingItem.filePath == this.currentSong?.filePath) {
  1664. this.currentSong.name = this.titleStr;
  1665. this.artist = this.artistStr;
  1666. this.currentSong.artist = this.artistStr;
  1667. this.currentSong.album = this.ablumStr;
  1668. this.currentSong.year = this.yearStr;
  1669. this.currentSong.genre = this.genreStr;
  1670. this.currentSong.track = this.trackStr;
  1671. this.currentSong.lyricContent = this.lyricConStr;
  1672. this.currentSong.ALBUMARTIST = this.albumArtistStr;
  1673. this.currentSong.COMPOSER = this.composerStr;
  1674. this.currentSong.LYRICIST = this.lyricistStr;
  1675. this.currentSong.COMMENT = this.commentStr;
  1676. }
  1677. // if (result.needRefreshList && this.modeType == 0) {
  1678. // this.deleteCache(this.currentPath);
  1679. // this.getSortedFiles(this.currentPath);
  1680. // }
  1681. // 同步编辑字段到本地列表
  1682. if (this.editingItem) {
  1683. this.syncEditedFields(this.editingItem);
  1684. this.syncListsAfterEdit(this.editingItem.filePath);
  1685. this.doUpateEditedFields(this.editingItem);
  1686. }
  1687. // 清理临时变量
  1688. this.longItemFilePath = '';
  1689. this.tempLyricContent = '';
  1690. this.isShowEdit = false;
  1691. this.imagePathStr = '';
  1692. } else {
  1693. console.error("heanup 编辑信息失败: " + result.error);
  1694. ToastUtil.showToast('编辑失败: ' + (result.error || '未知错误'));
  1695. // 清理临时变量
  1696. this.longItemFilePath = '';
  1697. this.tempLyricContent = '';
  1698. this.isShowEdit = false;
  1699. this.imagePathStr = '';
  1700. }
  1701. }
  1702. private assignStringMetadata(target: VideoItem, key: keyof VideoItem, value?: string | null, allowEmpty = false): void {
  1703. if (value === undefined || value === null) {
  1704. return;
  1705. }
  1706. const text = value.toString();
  1707. if (!allowEmpty && text.trim().length === 0) {
  1708. return;
  1709. }
  1710. Reflect.set(target, key as string, value);
  1711. }
  1712. private assignNumberMetadata(target: VideoItem, key: keyof VideoItem, value?: number | null): void {
  1713. if (value === undefined || value === null || Number.isNaN(value)) {
  1714. return;
  1715. }
  1716. Reflect.set(target, key as string, value);
  1717. }
  1718. private mergeVideoItemWithPayload(target: VideoItem, payload: WorkerMetadataPayload): void {
  1719. if (!target || !payload) {
  1720. return;
  1721. }
  1722. this.assignStringMetadata(target, 'name', payload.name);
  1723. this.assignStringMetadata(target, 'artist', payload.artist);
  1724. this.assignStringMetadata(target, 'album', payload.album);
  1725. this.assignStringMetadata(target, 'bit_rate', payload.bit_rate);
  1726. this.assignStringMetadata(target, 'duration', payload.duration);
  1727. this.assignStringMetadata(target, 'sampleRate', payload.sampleRate);
  1728. this.assignStringMetadata(target, 'mimeType', payload.mimeType);
  1729. this.assignStringMetadata(target, 'size', payload.size);
  1730. this.assignStringMetadata(target, 'pixelMapPath', payload.pixelMapPath);
  1731. this.assignStringMetadata(target, 'lyricContent', payload.lyricContent, true);
  1732. this.assignStringMetadata(target, 'genre', payload.genre);
  1733. this.assignStringMetadata(target, 'track', payload.track);
  1734. this.assignStringMetadata(target, 'bits_per_raw_sample', payload.bits_per_raw_sample);
  1735. this.assignStringMetadata(target, 'channels', payload.channels);
  1736. this.assignStringMetadata(target, 'channel_layout', payload.channel_layout);
  1737. this.assignStringMetadata(target, 'start_time', payload.start_time);
  1738. this.assignStringMetadata(target, 'year', payload.year);
  1739. this.assignStringMetadata(target, 'disc', payload.disc);
  1740. this.assignStringMetadata(target, 'ALBUMARTIST', payload.ALBUMARTIST);
  1741. this.assignStringMetadata(target, 'COMPOSER', payload.COMPOSER);
  1742. this.assignStringMetadata(target, 'LYRICIST', payload.LYRICIST);
  1743. this.assignStringMetadata(target, 'COMMENT', payload.COMMENT, true);
  1744. this.assignNumberMetadata(target, 'videoSize', payload.videoSize);
  1745. this.assignNumberMetadata(target, 'probe_score', payload.probe_score);
  1746. this.assignNumberMetadata(target, 'nb_streams', payload.nb_streams);
  1747. this.assignNumberMetadata(target, 'nb_programs', payload.nb_programs);
  1748. }
  1749. private mergeVideoItemFromSource(target: VideoItem, source: VideoItem): void {
  1750. if (!target || !source) {
  1751. return;
  1752. }
  1753. this.assignStringMetadata(target, 'name', source.name);
  1754. this.assignStringMetadata(target, 'artist', source.artist);
  1755. this.assignStringMetadata(target, 'album', source.album);
  1756. this.assignStringMetadata(target, 'bit_rate', source.bit_rate);
  1757. this.assignStringMetadata(target, 'duration', source.duration);
  1758. this.assignStringMetadata(target, 'sampleRate', source.sampleRate);
  1759. this.assignStringMetadata(target, 'trackCount', source.trackCount);
  1760. this.assignStringMetadata(target, 'mimeType', source.mimeType);
  1761. this.assignStringMetadata(target, 'size', source.size);
  1762. this.assignStringMetadata(target, 'pixelMapPath', source.pixelMapPath);
  1763. this.assignStringMetadata(target, 'lyricContent', source.lyricContent, true);
  1764. this.assignStringMetadata(target, 'genre', source.genre);
  1765. this.assignStringMetadata(target, 'track', source.track);
  1766. this.assignStringMetadata(target, 'bits_per_raw_sample', source.bits_per_raw_sample);
  1767. this.assignStringMetadata(target, 'channels', source.channels);
  1768. this.assignStringMetadata(target, 'channel_layout', source.channel_layout);
  1769. this.assignStringMetadata(target, 'start_time', source.start_time);
  1770. this.assignStringMetadata(target, 'year', source.year);
  1771. this.assignStringMetadata(target, 'disc', source.disc);
  1772. this.assignStringMetadata(target, 'ALBUMARTIST', source.ALBUMARTIST);
  1773. this.assignStringMetadata(target, 'COMPOSER', source.COMPOSER);
  1774. this.assignStringMetadata(target, 'LYRICIST', source.LYRICIST);
  1775. this.assignStringMetadata(target, 'COMMENT', source.COMMENT, true);
  1776. this.assignNumberMetadata(target, 'videoSize', source.videoSize);
  1777. this.assignNumberMetadata(target, 'probe_score', source.probe_score);
  1778. this.assignNumberMetadata(target, 'nb_streams', source.nb_streams);
  1779. this.assignNumberMetadata(target, 'nb_programs', source.nb_programs);
  1780. if (source.remote_rel_path && StrUtil.isEmpty(target.remote_rel_path)) {
  1781. target.remote_rel_path = source.remote_rel_path;
  1782. }
  1783. }
  1784. private async hydrateRemoteSongFromDb(item: VideoItem | undefined): Promise<void> {
  1785. if (!item || !isRemoteCloudType(item.type)) {
  1786. return;
  1787. }
  1788. const storagePath = item.remote_rel_path || WebDavUrlUtil.toStoragePath(item.filePath);
  1789. if (!storagePath) {
  1790. return;
  1791. }
  1792. try {
  1793. const cached = await this.table.queryVideoByFilePath(storagePath);
  1794. if (!cached) {
  1795. return;
  1796. }
  1797. this.mergeVideoItemFromSource(item, cached);
  1798. if (StrUtil.isEmpty(item.remote_rel_path)) {
  1799. item.remote_rel_path = storagePath;
  1800. }
  1801. if (item === this.currentSong) {
  1802. if (StrUtil.isNotEmpty(item.name)) {
  1803. this.name = item.name;
  1804. }
  1805. if (StrUtil.isNotEmpty(item.artist)) {
  1806. this.artist = item.artist!;
  1807. }
  1808. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  1809. this.cover = item.pixelMapPath!;
  1810. }
  1811. if (StrUtil.isNotEmpty(item.lyricContent) && StrUtil.isEmpty(this.lyricContent)) {
  1812. this.applyInlineLyricContent(item.lyricContent as string);
  1813. }
  1814. }
  1815. } catch (error) {
  1816. Logger.error(TAG, `hydrateRemoteSongFromDb 失败: ${(error as Error).message}`);
  1817. }
  1818. }
  1819. private applyInlineLyricContent(content: string): void {
  1820. if (StrUtil.isEmpty(content)) {
  1821. return;
  1822. }
  1823. this.lyricContent = content;
  1824. const lines = content.split('\n').map(line => line.trim());
  1825. const lyric = this.parser.parse(lines);
  1826. this.lyricController.setLyric(lyric);
  1827. this.lyricControllerXF.setLyric(lyric);
  1828. this.lyricControllerSingle.setLyric(lyric);
  1829. }
  1830. private extractParentPathFromStoragePath(path: string): string {
  1831. if (!path) {
  1832. return '';
  1833. }
  1834. const lastSlash = path.lastIndexOf('/');
  1835. if (lastSlash <= 0) {
  1836. return '';
  1837. }
  1838. return path.substring(0, lastSlash);
  1839. }
  1840. private resolveRemoteStoragePath(target: VideoItem): string | null {
  1841. if (!target || !isRemoteCloudType(target.type)) {
  1842. return null;
  1843. }
  1844. if (isWebDavType(target.type)) {
  1845. const storagePath = target.remote_rel_path || WebDavUrlUtil.toStoragePath(target.filePath);
  1846. if (storagePath) {
  1847. target.remote_rel_path = storagePath;
  1848. return storagePath;
  1849. }
  1850. return null;
  1851. }
  1852. if (target.remote_rel_path && target.remote_rel_path.length > 0) {
  1853. return target.remote_rel_path;
  1854. }
  1855. return null;
  1856. }
  1857. private async persistRemoteMetadataToDb(target: VideoItem): Promise<void> {
  1858. if (!this.context || !target || !isRemoteCloudType(target.type)) {
  1859. return;
  1860. }
  1861. const storagePath = this.resolveRemoteStoragePath(target);
  1862. if (!storagePath) {
  1863. return;
  1864. }
  1865. const table = new MediaTable(this.context);
  1866. await new Promise<void>((resolve) => {
  1867. table.getRdbStore(this.context as Context, () => resolve());
  1868. });
  1869. const cloneItem = cloneVideoItem(target);
  1870. cloneItem.filePath = storagePath;
  1871. cloneItem.remote_rel_path = storagePath;
  1872. cloneItem.parentPath = this.extractParentPathFromStoragePath(storagePath);
  1873. await table.saveOrUpdateWebDavItem(cloneItem);
  1874. }
  1875. onPageHide(): void {
  1876. this.knockController?.immersiveDisableListening();
  1877. }
  1878. @State isFirstStartPlay: boolean = false
  1879. private async startFileDeletionWatcher(): Promise<void> {
  1880. if (!this.rootPath) {
  1881. return;
  1882. }
  1883. if (!this.deletionWatcher) {
  1884. this.deletionWatcher = new FileDeletionWatcher(this.context, this.table);
  1885. }
  1886. try {
  1887. await this.deletionWatcher.watchDirectories([
  1888. this.rootPath,
  1889. this.lockPath,
  1890. this.favPath,
  1891. this.historyPath
  1892. ]);
  1893. } catch (error) {
  1894. Logger.error(TAG, `初始化文件删除监听失败: ${(error as Error).message}`);
  1895. }
  1896. }
  1897. //获取download_path
  1898. async mkDownLoadDir() {
  1899. const documentViewPicker = new picker.DocumentViewPicker()
  1900. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  1901. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  1902. PreferencesUtil.putSync('download_path', this.rootPath+'/')
  1903. this.currentPath = this.rootPath
  1904. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  1905. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  1906. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  1907. Logger.info('onecold rootPath = ' + this.rootPath)
  1908. Logger.info('onecold lockPath = ' + this.lockPath)
  1909. if (!FileUtil.accessSync(this.lockPath)) {
  1910. FileUtil.mkdirSync(this.lockPath)
  1911. }
  1912. if (!FileUtil.accessSync(this.favPath)) {
  1913. FileUtil.mkdirSync(this.favPath)
  1914. }
  1915. if (!FileUtil.accessSync(this.historyPath)) {
  1916. FileUtil.mkdirSync(this.historyPath)
  1917. }
  1918. // await this.startFileDeletionWatcher();
  1919. this.getSortedFiles(this.rootPath).then(async () => {
  1920. this.isFavMusic = false
  1921. //穿山甲
  1922. // this.loadBannerAd(CSJUtil.getBannerID())
  1923. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  1924. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  1925. if (ArrayUtil.isEmpty(this.songList)) {
  1926. this.songList = this.getCurFileList()
  1927. } else {
  1928. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  1929. }
  1930. if (ArrayUtil.isNotEmpty(this.songList)) {
  1931. this.isFirstStartPlay = true
  1932. this.sonDataSource.pushArrayData(this.songList)
  1933. if (this.currentSong === undefined) {
  1934. this.isFirstStartPlay = false
  1935. this.currentSong = this.songList[0]
  1936. }
  1937. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  1938. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  1939. context: this.context,
  1940. autoParseMusicName: this.autoParseMusicName
  1941. });
  1942. Logger.info(TAG, `WebDAV URL同步构建完成: ${this.videoUrl}`);
  1943. this.name = this.currentSong.name
  1944. this.cover = this.currentSong.pixelMapPath
  1945. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  1946. } else {
  1947. this.name = '空空如也'
  1948. }
  1949. })
  1950. this.getFavList(false)
  1951. }
  1952. getFavList(isFavRefresh: boolean) {
  1953. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  1954. this.favList = result
  1955. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  1956. this.videoLocalList = this.favList
  1957. this.updateListData(this.videoLocalList)
  1958. }
  1959. })
  1960. }
  1961. getHistoryList(isRefresh: boolean) {
  1962. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  1963. this.historyList = result
  1964. // for (let i = 0; i < this.historyList.length; i++) {
  1965. //
  1966. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  1967. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  1968. // }
  1969. if (isRefresh) {
  1970. this.videoLocalList = this.historyList
  1971. this.updateListData(this.videoLocalList, true)
  1972. }
  1973. })
  1974. }
  1975. // 组件消失生命周期
  1976. aboutToDisappear() {
  1977. console.info('LifeCycleComponent aboutToDisappear');
  1978. this.deletionWatcher?.stop();
  1979. this.knockController?.immersiveDisableListening();
  1980. this.curIndex = 0
  1981. emitter.off(EventConstants.EVENT_AUDIO_OPEN);
  1982. emitter.off(EventConstants.EVENT_SCAN_UPDATE);
  1983. emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
  1984. emitter.off(EventConstants.EVENT_SETTING_UPDATE);
  1985. this.mDestroyPage = true;
  1986. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  1987. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  1988. this.stop();
  1989. }
  1990. this.mIjkMediaPlayer.off('audioInterrupt');
  1991. this.mIjkMediaPlayer.off('deviceChange');
  1992. if (workerInstance) {
  1993. workerInstance.terminate();
  1994. }
  1995. this.stopPip();
  1996. this.destroyPipController()
  1997. this.getUIContext().getHostContext()!.eventHub.off('playOrPause');
  1998. this.getUIContext().getHostContext()!.eventHub.off('playPrevious');
  1999. this.getUIContext().getHostContext()!.eventHub.off('playNext');
  2000. this.getUIContext().getHostContext()!.eventHub.off('showPlayerView');
  2001. this.getUIContext().getHostContext()!.eventHub.off('openPlayList');
  2002. }
  2003. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean,openItem?:VideoItem) {
  2004. this.isFavMusic = false
  2005. console.info('onecold getSortedFiles 1 curPath '+curPath)
  2006. if (isWorkerPost) {
  2007. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  2008. }
  2009. if (this.modeType !== 0) {
  2010. return
  2011. }
  2012. console.info('onecold getSortedFiles 2')
  2013. this.isCanBack = false
  2014. this.currentPath = curPath
  2015. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  2016. this.titleName = getFileDirName(this.currentPath,this.rootPath)
  2017. if (curPath === this.rootPath) {
  2018. this.rightTopImage = $r('sys.symbol.sort')
  2019. } else {
  2020. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  2021. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  2022. this.rightTopImage = $r('sys.symbol.chevron_left')
  2023. }
  2024. }
  2025. // Get the current file list and calculate its hash
  2026. this.fileList = FileUtil.listFileSync(curPath);
  2027. const currentHash = simpleHash(this.fileList);
  2028. // Check cache
  2029. const cachedValue = this.findCache(curPath);
  2030. Logger.info('onecold cachedValue = ' + cachedValue)
  2031. const cachedHash = this.findStringCache(curPath + '_hash');
  2032. const cachedDirList = this.findCache(curPath + "_dirList");
  2033. if (cachedValue !== undefined&&!this.isRefreshing) {
  2034. // this.videoLocalList = cachedValue;
  2035. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  2036. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  2037. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  2038. }
  2039. this.isRefreshing = false
  2040. this.updateListData(cachedValue)
  2041. }
  2042. if (cachedDirList !== undefined) {
  2043. this.dirList = cachedDirList
  2044. }
  2045. //通过当前hash值和缓存hash判断list有没有变化
  2046. if (cachedValue && cachedHash === currentHash) {
  2047. return;
  2048. }
  2049. // this.fileList = FileUtil.listFileSync(curPath)
  2050. let directories: Array<VideoItem> = [];
  2051. let files: Array<VideoItem> = [];
  2052. for (let i = 0; i < this.fileList.length; i++) {
  2053. console.info(`The name of file: ${this.fileList[i]}`);
  2054. let path = curPath + '/' + this.fileList[i]
  2055. if (FileUtil.isDirectory(path)) {
  2056. let item: VideoItem =
  2057. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  2058. '')
  2059. if (this.isShowDir(item.name)) {
  2060. directories.push(item);
  2061. }
  2062. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2063. // Utility.doSortListAscending(directories)
  2064. } else {
  2065. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  2066. let item: VideoItem =
  2067. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  2068. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  2069. files.push(item);
  2070. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2071. // this.doSortListAscending(files)
  2072. }
  2073. }
  2074. }
  2075. }
  2076. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  2077. if (this.currentPath !== this.lockPath) {
  2078. files = result;
  2079. }
  2080. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2081. Utility.doSortListAscending(files)
  2082. if (this.currentPath === this.rootPath) {
  2083. this.dirList = directories
  2084. this.addCache(curPath + "_dirList", this.dirList);
  2085. }
  2086. //插入广告先注释掉
  2087. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  2088. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  2089. // directories.push(adItem)
  2090. // }
  2091. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  2092. this.videoLocalList = directories.concat(files);
  2093. this.updateListData(this.videoLocalList)
  2094. if (ArrayUtil.isNotEmpty(files)) {
  2095. if (this.currentPath != this.rootPath) {
  2096. if (files) {
  2097. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  2098. }
  2099. }
  2100. // 缓存结果
  2101. this.addCache(curPath, this.videoLocalList);
  2102. await this.saveCacheToStorage(); // 保存缓存至本地存储
  2103. this.addStringCache(curPath + '_hash', currentHash);
  2104. }
  2105. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  2106. for (let i = 0; i < this.videoLocalList.length; i++) {
  2107. console.info(`onecold gengxin 1: ${this.videoLocalList[i].name}`);
  2108. }
  2109. // this.setButtonStatus()
  2110. this.openMusic(isOpen, destPath,openItem)
  2111. this.isRefreshing = false
  2112. });
  2113. }
  2114. //第三方app打开天天静听导入音乐后播放
  2115. openMusic(isOpen?: boolean, destPath?: string,openItem?:VideoItem){
  2116. if (isOpen&&destPath) {
  2117. if (destPath === undefined) {
  2118. // 处理 destPath 为 undefined 的情况
  2119. return
  2120. }
  2121. if (destPath.endsWith('.lrc')) {
  2122. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  2123. if (StrUtil.isNotEmpty(this.videoUrl)) {
  2124. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  2125. this.initLyric(lyricPath);
  2126. }
  2127. return
  2128. }
  2129. if(openItem){
  2130. this.doPlay(openItem,0,false,true)
  2131. // this.isShowPlay = true
  2132. this.setShowPlayTrue()
  2133. }
  2134. }
  2135. }
  2136. //扫描文件夹入库
  2137. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  2138. const files = FileUtil.listFileSync(curPath);
  2139. let mediaItems: VideoItem[] = [];
  2140. Logger.info('onecold scanDirectory start ')
  2141. for (const file of files) {
  2142. const fPath = `${curPath}/${file}`;
  2143. if (fPath === this.lockPath) {
  2144. Logger.info(`Skipping locked path: ${fPath}`);
  2145. continue;
  2146. }
  2147. if (FileUtil.isDirectory(fPath)) {
  2148. // Recursively scan subdirectories
  2149. const subDirItems = await this.scanDirectory(fPath);
  2150. mediaItems = mediaItems.concat(subDirItems);
  2151. } else {
  2152. Logger.info('onecold scanDirectory filePath = ' + fPath)
  2153. // Process media files
  2154. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  2155. let mediaItem: VideoItem =
  2156. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2157. mediaItems.push(mediaItem);
  2158. this.table.insert(mediaItem, (id: number) => {
  2159. });
  2160. }
  2161. }
  2162. }
  2163. return mediaItems;
  2164. }
  2165. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  2166. animateTo({ duration: 666 }, () => {
  2167. this.opacityItem = 0.5;
  2168. });
  2169. setTimeout(() => {
  2170. this.videoLocalList = mList;
  2171. if (!noSort) {
  2172. if (this.modeType === 0 || this.modeType === 1) {
  2173. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  2174. this.doSortType(this.sortType)
  2175. }
  2176. }
  2177. this.dataSource.pushArrayData(this.videoLocalList)
  2178. animateTo({ duration: 666 }, () => {
  2179. this.opacityItem = 1;
  2180. });
  2181. this.setButtonStatus()
  2182. //添加到字母索引表
  2183. this.setAlphaBet()
  2184. }, 200);
  2185. }
  2186. getCurFileList(): Array<VideoItem> {
  2187. if(this.isSearchMode){
  2188. return this.filteredList
  2189. }
  2190. let files: Array<VideoItem> = [];
  2191. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2192. for (let i = 0; i < this.videoLocalList.length; i++) {
  2193. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  2194. files.push(this.videoLocalList[i]);
  2195. }
  2196. }
  2197. }
  2198. return files
  2199. }
  2200. setButtonStatus() {
  2201. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2202. this.isZero = false
  2203. } else {
  2204. this.isZero = true
  2205. }
  2206. if (this.currentPath !== this.rootPath &&
  2207. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  2208. this.isHasDir = true //不为空,说明有子文件夹
  2209. } else {
  2210. this.isHasDir = false
  2211. }
  2212. }
  2213. @Builder
  2214. SortMenuBuilder() {
  2215. Menu() {
  2216. MenuItem({
  2217. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2218. content: "按艺术家升序"
  2219. })
  2220. .onClick(async () => {
  2221. this.doSortType(0)
  2222. PreferencesUtil.put(SettingPage.SORT_TYPE, 0)
  2223. this.updateListData(this.videoLocalList, true)
  2224. })
  2225. MenuItem({
  2226. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2227. content: "按艺术家降序"
  2228. })
  2229. .onClick(async () => {
  2230. this.doSortType(1)
  2231. PreferencesUtil.put(SettingPage.SORT_TYPE, 1)
  2232. this.updateListData(this.videoLocalList, true)
  2233. })
  2234. MenuItem({
  2235. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat_size_square')),
  2236. content: "按专辑升序"
  2237. })
  2238. .onClick(async () => {
  2239. this.doSortType(2)
  2240. PreferencesUtil.put(SettingPage.SORT_TYPE, 2)
  2241. this.updateListData(this.videoLocalList, true)
  2242. })
  2243. MenuItem({
  2244. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.character_arrow_clockwise')),
  2245. content: "按专辑降序"
  2246. })
  2247. .onClick(async () => {
  2248. this.doSortType(3)
  2249. PreferencesUtil.put(SettingPage.SORT_TYPE, 3)
  2250. this.updateListData(this.videoLocalList, true)
  2251. })
  2252. MenuItem({
  2253. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2254. content: $r('app.string.sort_by_name')
  2255. })
  2256. .onClick(async () => {
  2257. this.doSortType(4)
  2258. PreferencesUtil.put(SettingPage.SORT_TYPE, 4)
  2259. this.updateListData(this.videoLocalList, true)
  2260. })
  2261. MenuItem({
  2262. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2263. content: '按名称降序'
  2264. })
  2265. .onClick(async () => {
  2266. this.doSortType(5)
  2267. PreferencesUtil.put(SettingPage.SORT_TYPE, 5)
  2268. this.updateListData(this.videoLocalList, true)
  2269. })
  2270. MenuItem({
  2271. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2272. content: $r('app.string.sort_by_time')
  2273. })
  2274. .onClick(async () => {
  2275. this.doSortType(6)
  2276. PreferencesUtil.put(SettingPage.SORT_TYPE, 6)
  2277. this.updateListData(this.videoLocalList, true)
  2278. })
  2279. MenuItem({
  2280. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  2281. content: '按添加时间降序'
  2282. })
  2283. .onClick(async () => {
  2284. this.doSortType(7)
  2285. PreferencesUtil.put(SettingPage.SORT_TYPE, 7)
  2286. this.updateListData(this.videoLocalList, true)
  2287. })
  2288. }.attributeModifier(new MenuModifier())
  2289. }
  2290. @Builder
  2291. SortMenuForArtistAblumBuilder() {
  2292. Menu() {
  2293. MenuItem({
  2294. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2295. content: $r('app.string.sort_by_name')
  2296. })
  2297. .onClick(async () => {
  2298. this.doSortType(4)
  2299. // PreferencesUtil.put(SettingPage.SORT_TYPE, 2)
  2300. this.updateListData(this.videoLocalList, true)
  2301. })
  2302. MenuItem({
  2303. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2304. content: '按名称降序'
  2305. })
  2306. .onClick(async () => {
  2307. this.doSortType(5)
  2308. this.updateListData(this.videoLocalList, true)
  2309. })
  2310. MenuItem({
  2311. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2312. content: '按数量升序'
  2313. })
  2314. .onClick(async () => {
  2315. this.doSortType(8)
  2316. this.updateListData(this.videoLocalList, true)
  2317. })
  2318. MenuItem({
  2319. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  2320. content: '按数量降序'
  2321. })
  2322. .onClick(async () => {
  2323. this.doSortType(9)
  2324. this.updateListData(this.videoLocalList, true)
  2325. })
  2326. }.attributeModifier(new MenuModifier())
  2327. }
  2328. doSortType(index: number) {
  2329. switch (index) {
  2330. case 0:
  2331. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2332. // 类型排序优先级
  2333. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2334. if (typeOrder !== 0) {
  2335. return typeOrder;
  2336. }
  2337. // 处理艺术家可能为undefined的字符串比较
  2338. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  2339. const artistB = b.artist?.trim() || '';
  2340. return artistA.localeCompare(artistB);
  2341. });
  2342. break;
  2343. case 1:
  2344. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2345. // 类型排序优先级
  2346. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2347. if (typeOrder !== 0) {
  2348. return typeOrder;
  2349. }
  2350. // 处理艺术家可能为undefined的字符串比较
  2351. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  2352. const artistB = b.artist?.trim() || '';
  2353. return artistB.localeCompare(artistA);
  2354. });
  2355. break;
  2356. case 2:
  2357. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2358. // 类型排序优先级
  2359. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2360. if (typeOrder !== 0) {
  2361. return typeOrder;
  2362. }
  2363. // 处理专辑可能为undefined的字符串比较
  2364. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  2365. const albumB = b.album?.trim() || '';
  2366. return albumA.localeCompare(albumB);
  2367. });
  2368. break;
  2369. case 3:
  2370. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2371. // 类型排序优先级
  2372. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2373. if (typeOrder !== 0) {
  2374. return typeOrder;
  2375. }
  2376. // 处理专辑可能为undefined的字符串比较
  2377. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  2378. const albumB = b.album?.trim() || '';
  2379. return albumB.localeCompare(albumA);
  2380. });
  2381. break;
  2382. case 4:
  2383. Utility.doSortListAscending(this.videoLocalList,this.isShowFileName)
  2384. break;
  2385. case 5:
  2386. Utility.doSortListDescending(this.videoLocalList,this.isShowFileName)
  2387. break;
  2388. case 6:
  2389. this.videoLocalList.sort((a, b) => {
  2390. // First, sort by type
  2391. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2392. if (typeOrder !== 0) {
  2393. return typeOrder;
  2394. }
  2395. // If types are the same, sort by cTime in ascending order
  2396. return a.cTime.localeCompare(b.cTime);
  2397. });
  2398. break;
  2399. case 7:
  2400. this.videoLocalList.sort((a, b) => {
  2401. // First, sort by type
  2402. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2403. if (typeOrder !== 0) {
  2404. return typeOrder;
  2405. }
  2406. // If types are the same, sort by cTime in descending order
  2407. return b.cTime.localeCompare(a.cTime);
  2408. });
  2409. break;
  2410. case 8:
  2411. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  2412. // 1. Sort by type first
  2413. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  2414. if (typeOrder !== 0) {
  2415. return typeOrder;
  2416. }
  2417. // 2. Then sort by artist count (numeric comparison)
  2418. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  2419. if(this.modeType === 2){
  2420. sortMap = this.artistMap
  2421. }else{
  2422. sortMap = this.albumMap
  2423. }
  2424. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  2425. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  2426. return aArtistCount - bArtistCount;
  2427. });
  2428. break;
  2429. case 9:
  2430. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  2431. // 1. Sort by type first
  2432. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  2433. if (typeOrder !== 0) {
  2434. return typeOrder;
  2435. }
  2436. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  2437. if(this.modeType === 2){
  2438. sortMap = this.artistMap
  2439. }else{
  2440. sortMap = this.albumMap
  2441. }
  2442. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  2443. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  2444. return bArtistCount - aArtistCount;
  2445. });
  2446. break;
  2447. }
  2448. }
  2449. showSheelDialog() {
  2450. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  2451. // this.showTips()
  2452. // return
  2453. // }
  2454. this.showAddDialog()
  2455. }
  2456. showAddDialog() {
  2457. if (this.modeType === 2 || this.modeType === 3) {
  2458. return
  2459. }
  2460. DialogHelper.showActionSheetDialog({
  2461. title: "请选择添加方式(建议歌词文件一起导入)",
  2462. sheets: [
  2463. { value: "新建文件夹", fontColor: $r('app.color.text_color') },
  2464. { value: "手动导入", fontColor: $r('app.color.text_color') },
  2465. { value: "自动导入", fontColor: $r('app.color.text_color') },
  2466. { value: "全选导入", fontColor: $r('app.color.text_color') },
  2467. ],
  2468. maskColor: Color.Transparent,
  2469. backgroundColor: $r('app.color.bg_card'),
  2470. transition: AnimationHelper.transitionInDown(555),
  2471. onAction: (index) => {
  2472. switch (index) {
  2473. case 0:
  2474. if (this.modeType === 0) {
  2475. this.showMkDialog()
  2476. } else {
  2477. ToastUtil.showToast('请切换到首页才能新建文件夹!')
  2478. }
  2479. break;
  2480. case 1:
  2481. this.callFilePickerSelectFile()
  2482. break;
  2483. case 2:
  2484. this.showTips()
  2485. break;
  2486. case 3:
  2487. this.goSelectMusic()
  2488. break;
  2489. }
  2490. }
  2491. })
  2492. }
  2493. //拉起音频
  2494. goSelectMusic() {
  2495. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  2496. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  2497. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  2498. ) {
  2499. ToastUtil.showToast('暂时不支持该设备')
  2500. return
  2501. }
  2502. try {
  2503. let documentSelectOptions = new picker.DocumentSelectOptions();
  2504. documentSelectOptions.authMode = true
  2505. documentSelectOptions.multiAuthMode = true
  2506. if( deviceInfo.sdkApiVersion>=21){//如果api大于21 ,可以支持1w首歌以上
  2507. documentSelectOptions.maxSelectNumber = 20000
  2508. }
  2509. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  2510. let documentPicker = new picker.DocumentViewPicker(this.context);
  2511. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  2512. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  2513. this.saveVideoDatas(documentSelectResult)
  2514. }
  2515. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  2516. JSON.stringify(documentSelectResult));
  2517. }).catch((err: BusinessError) => {
  2518. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  2519. });
  2520. } catch (error) {
  2521. let err: BusinessError = error as BusinessError;
  2522. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2523. }
  2524. }
  2525. async showTips() {
  2526. try {
  2527. this.getUIContext().getPromptAction().showDialog({
  2528. title: '导入指南',
  2529. message:'用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2530. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2531. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2532. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后去文件扫描一下。\n',
  2533. buttons: [
  2534. {
  2535. text: '知道了',
  2536. color: '#000000'
  2537. },
  2538. ]
  2539. }, (err, data) => {
  2540. if (err) {
  2541. console.error('showDialog err: ' + err);
  2542. return;
  2543. }
  2544. console.info('showDialog success callback, click button: ' + data.index);
  2545. });
  2546. } catch (error) {
  2547. let message = (error as BusinessError).message;
  2548. let code = (error as BusinessError).code;
  2549. console.error(`showDialog args error code is ${code}, message is ${message}`);
  2550. };
  2551. // DialogHelper.showTipsDialog({
  2552. // title: '使用提示:自动导入教程',
  2553. //
  2554. // content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2555. // + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2556. // '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2557. // '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  2558. // onAction: (action) => {
  2559. // if (action == DialogAction.TWO) {
  2560. // PreferencesUtil.putSync('isFirstMusic', false)
  2561. // router.pushUrl({
  2562. // url: 'pages/ScanFilePage'
  2563. // });
  2564. // }
  2565. // }
  2566. // })
  2567. }
  2568. showMkDialog() {
  2569. DialogHelper.showTextInputDialog({
  2570. title: '新建歌单',
  2571. maskColor: Color.Transparent,
  2572. text: '',
  2573. transition: AnimationHelper.transitionInDown(666),
  2574. onChange: (text) => {
  2575. console.error("onChange: " + text);
  2576. },
  2577. onAction: (action, dialogId, content) => {
  2578. // ToastUtil.showToast('content = ' +content)
  2579. if (action == DialogAction.TWO) {
  2580. const newName = content
  2581. const newPath = this.currentPath + '/' + newName
  2582. FileUtil.mkdir(newPath, true).then(() => {
  2583. this.cache.delete(this.currentPath); // 删除目标路径缓存
  2584. this.getSortedFiles(this.currentPath)
  2585. }).catch((error: BusinessError) => {
  2586. console.error(error.message);
  2587. });
  2588. }
  2589. }
  2590. })
  2591. }
  2592. @State progress: number = 0;
  2593. async saveVideoDatas(uris:string[],isOpen?:boolean){
  2594. if (ArrayUtil.isEmpty(uris)) {
  2595. return;
  2596. }
  2597. console.info('onecold this.isCopyFileToDownLoad = ' + this.isCopyFileToDownLoad);
  2598. if(this.isCopyFileToDownLoad||this.currentPath==this.lockPath||isOpen){
  2599. this.saveVideoDatasToDownLoad(uris,isOpen)
  2600. return
  2601. }
  2602. // 初始化进度条
  2603. this.progress = 0;
  2604. DialogHelper.showLoadingProgress({
  2605. progress: this.progress,
  2606. backCancel: false,
  2607. autoCancel: false,
  2608. loadColor: $r('app.color.title_bar_bg'),
  2609. fontColor: $r('app.color.title_bar_bg')
  2610. });
  2611. // 计算处理总数用于进度计算
  2612. const totalItems = uris.length;
  2613. let processedItems = 0;
  2614. for (let i = 0; i < uris.length; i++) {
  2615. let filePath = uris[i];
  2616. try {
  2617. if (this.currentPath !== this.lockPath) { // 判断不是私密音乐,才入库
  2618. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2619. let mediaItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context,
  2620. filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2621. console.info('onecold saveVideoDatas filePath = ' + filePath)
  2622. if (!filePath.includes(this.rootPath)) {
  2623. console.info('onecold saveVideoDatas mediaItem.parentPath111 = ' + mediaItem.parentPath)
  2624. mediaItem.parentPath = this.currentPath;
  2625. }
  2626. console.info('onecold saveVideoDatas mediaItem.parentPath = ' + mediaItem.parentPath)
  2627. this.table.insert(mediaItem, (id: number) => {
  2628. // 插入完成回调
  2629. });
  2630. }
  2631. }
  2632. // 更新进度
  2633. processedItems++;
  2634. this.progress = Math.floor((processedItems / totalItems) * 100);
  2635. DialogHelper.updateLoading(' 正在处理', this.progress);
  2636. } catch (error) {
  2637. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2638. // 即使出错也更新进度
  2639. processedItems++;
  2640. this.progress = Math.floor((processedItems / totalItems) * 100);
  2641. DialogHelper.updateLoading(' 正在处理', this.progress);
  2642. }
  2643. }
  2644. // 关闭进度条
  2645. DialogHelper.closeLoading();
  2646. this.isZero = false
  2647. // 删除目标路径缓存
  2648. setTimeout(() => {
  2649. this.cache.delete(this.currentPath);
  2650. this.getSortedFiles(this.currentPath,false,uris[0],isOpen)
  2651. this.setButtonStatus()
  2652. }, 500);
  2653. }
  2654. async saveVideoDatasToDownLoad(uris: string[], isOpen?: boolean) {
  2655. if (ArrayUtil.isEmpty(uris)) {
  2656. return;
  2657. }
  2658. let newUris: string[] = [];
  2659. this.progress = 0
  2660. DialogHelper.showLoadingProgress({
  2661. progress: this.progress,
  2662. backCancel: false,
  2663. autoCancel: false,
  2664. loadColor: this.themeColor,
  2665. fontColor: this.themeColor
  2666. });
  2667. // 计算所有文件的总大小
  2668. let totalSize = 0;
  2669. for (let uri of uris) {
  2670. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  2671. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  2672. await fileIo.close(sourceFile.fd);
  2673. }
  2674. let totalRead = 0;
  2675. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  2676. Logger.info(TAG, 'destPath uri: ' + destPath);
  2677. for (let i = 0; i < uris.length; i++) {
  2678. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  2679. Logger.info(TAG, 'filePath uri: ' + filePath);
  2680. newUris.push(filePath);
  2681. try {
  2682. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  2683. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  2684. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  2685. const buffer = new ArrayBuffer(buffSize);
  2686. let len = await fileIo.read(sourceFile.fd, buffer);
  2687. while (len > 0) {
  2688. await fileIo.write(destFile.fd, buffer.slice(0, len));
  2689. totalRead += len;
  2690. // 计算总进度
  2691. this.progress = Math.floor((totalRead / totalSize) * 100);
  2692. DialogHelper.updateLoading('正在导入', this.progress);
  2693. len = await fileIo.read(sourceFile.fd, buffer);
  2694. }
  2695. await fileIo.close(sourceFile.fd);
  2696. await fileIo.close(destFile.fd);
  2697. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  2698. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2699. let mediaItem: VideoItem =
  2700. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2701. this.table.insert(mediaItem, (id: number) => {
  2702. // 删除目标路径缓存
  2703. this.cache.delete(this.currentPath);
  2704. this.getSortedFiles(this.currentPath, true, destPath, isOpen,mediaItem)
  2705. });
  2706. }
  2707. }
  2708. } catch (error) {
  2709. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2710. }
  2711. }
  2712. DialogHelper.closeLoading()
  2713. this.isZero = false
  2714. // setTimeout(() => {
  2715. // // 删除目标路径缓存
  2716. // this.cache.delete(this.currentPath);
  2717. // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
  2718. // }, 500);
  2719. Logger.info(TAG, 'scan select video result:' + newUris)
  2720. }
  2721. //拉起音频
  2722. // goSelectMusic(){
  2723. //
  2724. // try {
  2725. // let audioSelectOptions = new picker.AudioSelectOptions();
  2726. // let audioPicker = new picker.AudioViewPicker(this.context);
  2727. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  2728. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  2729. // this.saveVideoDatas(audioSelectResult)
  2730. // }
  2731. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  2732. // }).catch((err: BusinessError) => {
  2733. //
  2734. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  2735. // });
  2736. // } catch (error) {
  2737. // let err: BusinessError = error as BusinessError;
  2738. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2739. // }
  2740. //
  2741. //
  2742. //
  2743. // }
  2744. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  2745. if (!item) {
  2746. return undefined;
  2747. }
  2748. try {
  2749. let selectUris: Array<string> = [];
  2750. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  2751. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  2752. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  2753. photoSelectOptions.maxSelectNumber = 1;
  2754. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  2755. selectUris = photoSelectResult.photoUris;
  2756. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  2757. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  2758. console.info('file fd: ' + file.fd);
  2759. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  2760. let imagePath = this.context.filesDir + FileUtil.separator + name
  2761. imagePath = fileUri.getUriFromPath(imagePath)
  2762. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  2763. fileIo.copyFileSync(file.fd, file2.fd)
  2764. fileIo.closeSync(file);
  2765. fileIo.closeSync(file2);
  2766. if (item.filePath == this.currentSong?.filePath) {
  2767. this.cover = imagePath
  2768. }
  2769. if (item) {
  2770. item.pixelMapPath = imagePath
  2771. }
  2772. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  2773. if (success) {
  2774. this.doUpdateData()
  2775. console.log("onecold 更新音乐封面成功,数据库已同步");
  2776. } else {
  2777. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  2778. }
  2779. });
  2780. LogUtil.debug("onecold this.cover =" + this.cover)
  2781. return FileUtil.getFilePath(imagePath); // Return the image path here
  2782. } catch (err) {
  2783. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  2784. return undefined;
  2785. }
  2786. }
  2787. // 拉起picker选择文件管理器
  2788. async callFilePickerSelectFile(): Promise<void> {
  2789. try {
  2790. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  2791. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  2792. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  2793. } else {
  2794. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  2795. }
  2796. let documentPicker = new picker.DocumentViewPicker();
  2797. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  2798. Logger.info(TAG,
  2799. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  2800. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  2801. this.saveVideoDatas(DocumentSelectResult)
  2802. }
  2803. }).catch((err: BusinessError) => {
  2804. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  2805. });
  2806. } catch (err) {
  2807. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  2808. }
  2809. }
  2810. //重命名的对话框
  2811. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  2812. if(!item.filePath.includes(this.packName)){
  2813. ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限重命名')
  2814. return
  2815. }
  2816. DialogHelper.showTextInputDialog({
  2817. title: '重命名',
  2818. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  2819. maskColor: Color.Transparent,
  2820. backgroundColor: Color.Grey,
  2821. transition: AnimationHelper.transitionInDown(666),
  2822. onChange: (text) => {
  2823. console.error("onChange: " + text);
  2824. },
  2825. onAction: (action, dialogId, content) => {
  2826. // ToastUtil.showToast('content = ' +content)
  2827. if (action == DialogAction.TWO) {
  2828. const newName = content
  2829. const newPath = this.currentPath + '/' + newName
  2830. console.log("onecold item = " + item.type);
  2831. this.doReName(index, newName, filePath, newPath, item)
  2832. }
  2833. }
  2834. })
  2835. }
  2836. //剪切 移动到另个文件夹的对话框
  2837. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2838. Logger.info('onecold showCutDialog')
  2839. let mList: Array<string> = []
  2840. let rPath = this.rootPath
  2841. if (isCurrent) {
  2842. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2843. rPath = this.currentPath
  2844. } else {
  2845. mList = Utility.getNameList(this.dirList);
  2846. rPath = this.rootPath
  2847. }
  2848. let dataBean = new BubbleBean()
  2849. dataBean.data = mList
  2850. dataBean.color = this.themeColor
  2851. dataBean.onItemClick = (i) => {
  2852. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2853. Logger.info('newPath = ' + newPath)
  2854. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  2855. ToastUtil.showToast('移动成功')
  2856. this.table.deleteData(item, () => {
  2857. });
  2858. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2859. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2860. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2861. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2862. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2863. this.table.insert(newItem, (id: number) => {
  2864. //加入数据库
  2865. });
  2866. }
  2867. this.cache.delete(this.currentPath); // 删除原路径缓存
  2868. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2869. this.getSortedFiles(this.currentPath, true)
  2870. }).catch((error: BusinessError) => {
  2871. console.error(error.message);
  2872. });
  2873. XPopup.dismissTop()
  2874. }
  2875. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2876. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2877. popupPosition = PopupPosition.TOP
  2878. }
  2879. if (index <= 3) {
  2880. popupPosition = PopupPosition.BOTTOM
  2881. }
  2882. let pup: XPopup
  2883. if (this.isDarkMode) {
  2884. pup = XPopup.Builder()
  2885. .setPopupPosition(popupPosition)
  2886. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  2887. .setBackgroundColor(Color.Black)
  2888. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2889. .show()
  2890. } else {
  2891. pup = XPopup.Builder()
  2892. .setPopupPosition(popupPosition)
  2893. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  2894. .setBackgroundColor(Color.White)
  2895. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2896. .show()
  2897. }
  2898. }
  2899. //复制 到另个文件夹的对话框
  2900. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2901. Logger.info('onecoldv showCopyDialog')
  2902. let mList: Array<string> = []
  2903. let rPath = this.rootPath
  2904. if (isCurrent) {
  2905. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2906. rPath = this.currentPath
  2907. } else {
  2908. mList = Utility.getNameList(this.dirList);
  2909. rPath = this.rootPath
  2910. }
  2911. let dataBean = new BubbleBean()
  2912. dataBean.data = mList
  2913. dataBean.isCopy = true
  2914. dataBean.color = this.themeColor
  2915. dataBean.onItemClick = (i) => {
  2916. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2917. Logger.info('newPath = ' + newPath)
  2918. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2919. ToastUtil.showToast('复制成功')
  2920. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2921. this.getSortedFiles(this.currentPath)
  2922. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2923. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2924. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2925. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2926. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2927. this.table.insert(newItem, (id: number) => {
  2928. //加入数据库
  2929. });
  2930. }
  2931. }).catch((error: BusinessError) => {
  2932. console.error(error.message);
  2933. });
  2934. XPopup.dismissTop()
  2935. }
  2936. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2937. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2938. popupPosition = PopupPosition.TOP
  2939. }
  2940. if (index <= 3) {
  2941. popupPosition = PopupPosition.BOTTOM
  2942. }
  2943. let pup: XPopup
  2944. if (this.isDarkMode) {
  2945. pup = XPopup.Builder()
  2946. .setPopupPosition(popupPosition)
  2947. .atView(id)
  2948. .setMaxHeight('60%')
  2949. .setBackgroundColor(Color.Black)
  2950. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2951. .show();
  2952. } else {
  2953. pup = XPopup.Builder()
  2954. .setPopupPosition(popupPosition)
  2955. .atView(id)
  2956. .setMaxHeight('60%')
  2957. .setBackgroundColor(Color.White)
  2958. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2959. .show();
  2960. }
  2961. }
  2962. //重命名索引index的视频
  2963. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  2964. FileUtil.rename(oldPath, newPath).then(async () => {
  2965. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2966. if (info.type === CommonConstants.TYPE_IS_DIR) {
  2967. //如果是文件夹先删除源数据,再添加新数据
  2968. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  2969. if (success) {
  2970. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  2971. } else {
  2972. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  2973. }
  2974. });
  2975. this.scanDirectory(newPath)
  2976. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  2977. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  2978. if (success) {
  2979. console.log(" onecold 重命名成功,数据库已同步");
  2980. } else {
  2981. console.error(" onecold 重命名数据库失败原因: " + error);
  2982. }
  2983. });
  2984. }
  2985. let mediaItem: VideoItem =
  2986. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2987. this.videoLocalList[index] = mediaItem;
  2988. }
  2989. this.cache.delete(this.currentPath)
  2990. this.getSortedFiles(this.currentPath, true)
  2991. }).catch((error: BusinessError) => {
  2992. console.error(error.message);
  2993. });
  2994. }
  2995. build() {
  2996. Stack() {
  2997. this.ContentBuild()
  2998. Stack() {
  2999. Column()
  3000. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  3001. height: '95%',
  3002. dragBar: true,
  3003. showClose: true,
  3004. blurStyle: BlurStyle.Thin,
  3005. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3006. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  3007. title: {
  3008. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  3009. + `(${this.songList.length}首)`
  3010. }
  3011. })
  3012. }
  3013. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  3014. modalTransition: ModalTransition.DEFAULT,
  3015. onWillDisappear: () => {
  3016. this.setShowPlayFalse()
  3017. },
  3018. })
  3019. }
  3020. .alignContent(Alignment.Bottom)
  3021. .width('100%')
  3022. .height('100%')
  3023. }
  3024. @Builder
  3025. ContentBuild() {
  3026. Scroll() {
  3027. Column() {
  3028. Stack() {
  3029. //libraryname加上去后onKeyEvent监听不了,因为目前的解决方案是上面的XComponent,去掉libraryname
  3030. XComponent({ id: 'for_onKeyEvent',type: XComponentType.SURFACE,
  3031. controller: this.xcomponentController })
  3032. .onLoad(async (event?: object) => {
  3033. })
  3034. .focusable(true)
  3035. .height(0)
  3036. .focusOnTouch(true)
  3037. .defaultFocus(true) // 自动获取键盘焦点
  3038. .onKeyEvent((event?: KeyEvent) => {
  3039. console.info('onecold点击 onKeyEvent')
  3040. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  3041. if (!event || event.type !== KeyType.Down) {
  3042. return;
  3043. }
  3044. console.info('onecold点击 onKeyEvent event.keyCode: ' + event.keyCode)
  3045. //空格键 Space key controls pause/play
  3046. if (event.keyCode === KeyCode.KEYCODE_SPACE|| event.keyCode === KeyCode.KEYCODE_MEDIA_PLAY_PAUSE) {
  3047. this.playOrPause()
  3048. }
  3049. if (event.keyCode === KeyCode.KEYCODE_DPAD_UP) {
  3050. this.playPrevious()
  3051. }
  3052. if (event.keyCode === KeyCode.KEYCODE_DPAD_DOWN) {
  3053. this.playNext()
  3054. }
  3055. // Right-click to fast forward
  3056. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  3057. this.fastForward()
  3058. }
  3059. // Left-click to rewind
  3060. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  3061. this.backForward()
  3062. }
  3063. })
  3064. Column() {
  3065. XComponent({
  3066. id: 'xcomponentId',
  3067. type: 'surface',
  3068. libraryname: 'ijkplayer_napi',
  3069. controller: this.xcomponentController
  3070. })
  3071. .onLoad((event?: object) => {
  3072. if (!!event) {
  3073. this.initDelayPlay(event);
  3074. }
  3075. })
  3076. .onDestroy(() => {
  3077. })
  3078. .width('100%')// .width(this.videoWidth)
  3079. .aspectRatio(this.videoAspectRatio)
  3080. }
  3081. .aspectRatio(this.videoAspectRatio)
  3082. .justifyContent(FlexAlign.Center)
  3083. .backgroundColor(Color.Transparent)
  3084. .visibility(Visibility.Hidden)
  3085. .height(CommonConstants.FULL_PERCENT)
  3086. .width(CommonConstants.FULL_PERCENT)
  3087. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  3088. height:this.isLandscape?'80%': '43%',
  3089. dragBar: true,
  3090. showClose: true,
  3091. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3092. blurStyle:BlurStyle.Thin,
  3093. backgroundColor:Color.Transparent,
  3094. title: { title: 'AB循环' }
  3095. })
  3096. Stack() {
  3097. Column() {
  3098. if(this.twoFingerType==4){
  3099. this.getWaterView()
  3100. }else{
  3101. if(this.isGridMusic){
  3102. this.getGridView()
  3103. }else {
  3104. this.getList()
  3105. }
  3106. }
  3107. if (this.modeType ==0||this.modeType==4) {
  3108. Column() {
  3109. emptyView(this.themeColor)
  3110. }
  3111. .onClick(()=>{
  3112. this.asyncCurrentPathOnlyFile()
  3113. })
  3114. .position({ top: 200 })
  3115. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  3116. .animation({ duration: 500 }),
  3117. TransitionEffect.scale({ x: 0, y: 0 })))
  3118. .justifyContent(FlexAlign.Center)
  3119. .opacity(this.isZero ? 1 : 0)
  3120. .visibility(this.isZero && !this.isFavMusic && !this.isHistory
  3121. ? Visibility.Visible : Visibility.None)
  3122. .animation({
  3123. duration: 500,
  3124. curve: Curve.Friction // 可选动画曲线
  3125. })
  3126. .width('100%')
  3127. }
  3128. }
  3129. .layoutWeight(1)
  3130. .height('100%')
  3131. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  3132. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3133. .onDrop((event?: DragEvent) => {
  3134. try {
  3135. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3136. if (dragData !== undefined) {
  3137. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3138. if (records.length > 0) {
  3139. for (let i = 0; i < records.length; i++) {
  3140. let types = records[i].getTypes();
  3141. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3142. const fileUriUds =
  3143. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3144. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3145. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3146. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3147. this.targetFile = fileUriUds.oriUri;
  3148. this.saveVideoDatas([this.targetFile])
  3149. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3150. }
  3151. }
  3152. }
  3153. } else {
  3154. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3155. }
  3156. } else {
  3157. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3158. }
  3159. } catch (error) {
  3160. const err = error as BusinessError;
  3161. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3162. }
  3163. })
  3164. // 右侧居中的字母表索引
  3165. this.indexBuilder()
  3166. this.topTitleBar()
  3167. }
  3168. .alignContent(Alignment.Top)
  3169. .layoutWeight(1)
  3170. .height('100%')
  3171. Row() {
  3172. Button(this.isAllSelected ? '反选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  3173. .width(45)
  3174. .height(45)
  3175. .fontSize(10)
  3176. .margin({ top: 10, bottom: 10, right: 6 })
  3177. .backgroundColor(this.themeColor)
  3178. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3179. .onClick(() => {
  3180. if (this.isAllSelected) {
  3181. // 全不选
  3182. this.selectedFiles = [];
  3183. } else {
  3184. // 全选
  3185. this.selectedFiles = [...this.getCurFileList()];
  3186. }
  3187. this.isAllSelected = !this.isAllSelected;
  3188. })
  3189. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  3190. .width(72)
  3191. .height(45)
  3192. .fontSize(10)
  3193. .margin({ top: 10, bottom: 10, right: 6 })
  3194. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3195. .backgroundColor(this.themeColor)
  3196. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  3197. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3198. })
  3199. .onClick(() => {
  3200. // if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  3201. this.isOneKeyTags = !this.isOneKeyTags
  3202. // }else{
  3203. // ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限批量内嵌标签,导入的时候请勾选复制一份。')
  3204. // }
  3205. })
  3206. Button('合并', { type: ButtonType.Circle, stateEffect: true })
  3207. .width(45)
  3208. .height(45)
  3209. .fontSize(10)
  3210. .margin({ top: 10, bottom: 10, right: 6 })
  3211. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3212. .backgroundColor(this.themeColor)
  3213. .bindContentCover($$this.isMergeAudio, this.MergeAudioBuilder(), {
  3214. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3215. })
  3216. .onClick(() => {
  3217. if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  3218. this.isMergeAudio = !this.isMergeAudio
  3219. }else{
  3220. ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限合并')
  3221. }
  3222. })
  3223. Button('+歌单', { type: ButtonType.Circle, stateEffect: true })
  3224. .width(45)
  3225. .height(45)
  3226. .fontSize(10)
  3227. .margin({ top: 10, bottom: 10, right: 6 })
  3228. .backgroundColor(this.themeColor)
  3229. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3230. .onClick(async () => {
  3231. this.longItemFilePath = ''
  3232. await this.openAddToPlaylistDialog(this.selectedFiles)
  3233. })
  3234. // Button('乱码', { type: ButtonType.Circle, stateEffect: true })
  3235. // .width(45)
  3236. // .height(45)
  3237. // .fontSize(10)
  3238. // .margin({ top: 10, bottom: 10, right: 6 })
  3239. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3240. // .backgroundColor(this.themeColor)
  3241. // .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  3242. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3243. // })
  3244. // .onClick(() => {
  3245. // this.isFixMessy = !this.isFixMessy
  3246. // })
  3247. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  3248. // .width('35%')
  3249. // .height(60)
  3250. // .id('music_cut')
  3251. // .margin({ top: 10, bottom: 10, right: 6 })
  3252. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3253. // .backgroundColor(this.themeColor)
  3254. // .onClick(() => {
  3255. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  3256. // })
  3257. //
  3258. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  3259. // .width('35%')
  3260. // .height(60)
  3261. // .id('music_cut_current')
  3262. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  3263. // .margin({ top: 10, bottom: 10, right: 6 })
  3264. // .backgroundColor(this.themeColor)
  3265. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3266. // .onClick(() => {
  3267. //
  3268. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  3269. // })
  3270. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  3271. // .width('35%')
  3272. // .height(60)
  3273. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  3274. // .margin({ top: 10, bottom: 10, right: 6 })
  3275. // .backgroundColor(this.themeColor)
  3276. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3277. // .onClick(() => {
  3278. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  3279. // })
  3280. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  3281. .width(45)
  3282. .height(45)
  3283. .fontSize(10)
  3284. .margin({ top: 10, bottom: 10, right: 6 })
  3285. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  3286. .backgroundColor(this.themeColor)
  3287. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3288. .onClick(() => {
  3289. this.showWarnIsDelete()
  3290. })
  3291. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  3292. .width(45)
  3293. .height(45)
  3294. .fontSize(10)
  3295. .margin({ top: 10, bottom: 10, right: 6 })
  3296. .backgroundColor(this.themeColor)
  3297. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3298. .onClick(() => {
  3299. this.selectedFiles = [];
  3300. this.isAllSelected = false
  3301. this.isMultiSelect = false
  3302. })
  3303. }
  3304. .width('100%')
  3305. .justifyContent(FlexAlign.Center)
  3306. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  3307. .opacity(this.isMultiSelect ? 1 : 0)
  3308. .animation({
  3309. duration: 666,
  3310. curve: 'ease-in-out' // 可选动画曲线
  3311. })
  3312. .position({ bottom: 20 }) // 将 Row 固定在底部
  3313. }
  3314. .width('100%')
  3315. .height('100%')
  3316. .alignContent(Alignment.Top)
  3317. }
  3318. .width('100%')
  3319. .height('100%')
  3320. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  3321. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  3322. .backgroundImagePosition(Alignment.Center)
  3323. .backdropBlur(this.blurValue)
  3324. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  3325. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  3326. }
  3327. }
  3328. //字母表索引
  3329. @Builder
  3330. indexBuilder(){
  3331. if(this.enableShowAlphabet){
  3332. Column({space: 5}){
  3333. if(this.isShowAlphaBet&&!(this.modeType==2&&!this.isCanBack)
  3334. &&!(this.modeType==3&&!this.isCanBack)){
  3335. AlphabetIndexer({arrayValue: this.alphaBet,selected: this.selectAlphaBetIndex})
  3336. .attributeModifier(this.alphaBetStyle)
  3337. .usingPopup(this.isTouchingAlphaBet)
  3338. .onAreaChange((old_value,new_value)=>{
  3339. this.alphabetHeight = new_value.height as number
  3340. })
  3341. .popupPosition({
  3342. x: 40,
  3343. y: this.alphabetHeight / 2
  3344. })
  3345. .onSelect((index: number) => {
  3346. this.onSelectIndexItem(this.alphaBet[index])
  3347. })
  3348. .onTouch((event: TouchEvent) =>{
  3349. this.isShowAlphaBet = true
  3350. if(event.type === TouchType.Up || event.type === TouchType.Cancel){
  3351. this.isTouchingAlphaBet = false
  3352. }else{
  3353. this.isTouchingAlphaBet = true
  3354. }
  3355. })
  3356. .transition(
  3357. TransitionEffect.translate({x: 10})
  3358. .combine(TransitionEffect.opacity(0.1))
  3359. .animation({
  3360. duration: 150,
  3361. curve: Curve.EaseInOut,
  3362. })
  3363. )
  3364. }else{
  3365. Blank()
  3366. .layoutWeight(1)
  3367. }
  3368. // ListLocateButton()
  3369. // .onClick(() =>{
  3370. // this.locateSong()
  3371. // })
  3372. // .clickEffect({level:ClickEffectLevel.LIGHT,scale: 0.5})
  3373. // .margin({
  3374. // bottom: 10
  3375. // })
  3376. }
  3377. .padding({
  3378. bottom: 0
  3379. })
  3380. .position({x:'92%'})
  3381. .height('100%')
  3382. .justifyContent(FlexAlign.Center)
  3383. }
  3384. }
  3385. onSelectIndexItem(letter: string) {
  3386. let songs = this.videoLocalList
  3387. let targetIndex = -1;
  3388. for (let i = 0; i < songs.length; i++) {
  3389. let song = songs[i]
  3390. let text = this.isShowFileName?song.fileName:
  3391. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  3392. if(this.sortType === 0||this.sortType==1){
  3393. text = song.artist
  3394. }else if(this.sortType === 2||this.sortType==3){
  3395. text = song.album
  3396. }
  3397. if(text){
  3398. let firstPinyin = getFirstLetter(text)
  3399. if (firstPinyin&&firstPinyin === letter) {
  3400. targetIndex = i;
  3401. break;
  3402. }
  3403. }
  3404. }
  3405. if (targetIndex !== -1) {
  3406. this.listScroller.scrollToIndex(targetIndex);
  3407. }
  3408. }
  3409. // 找到对应字母表的索引
  3410. findAlphaBetIndex(song: VideoItem):number{
  3411. let text = this.isShowFileName?song.fileName:
  3412. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  3413. if(this.sortType === 0||this.sortType==1){
  3414. text = song.artist
  3415. }else if(this.sortType === 2||this.sortType==3){
  3416. text = song.album
  3417. }
  3418. if(text){
  3419. let firstLetter = getFirstLetter(text)
  3420. for(let i=0;i<this.alphaBet.length;i++){
  3421. if(this.alphaBet[i] === firstLetter){
  3422. return i
  3423. }
  3424. }
  3425. }
  3426. return 0
  3427. }
  3428. async setAlphaBet(){
  3429. return new Promise<void>((resolve,reject) => {
  3430. try {
  3431. let songs = this.videoLocalList
  3432. if(songs.length > 40000){
  3433. this.alphaBet = []
  3434. resolve()
  3435. return
  3436. }
  3437. let alphabetSet = new Set<string>();
  3438. for (let song of songs) {
  3439. let text = this.isShowFileName?song.fileName:
  3440. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  3441. if(this.sortType === 0||this.sortType==1){
  3442. text = song.artist
  3443. }else if(this.sortType === 2||this.sortType==3){
  3444. text = song.album
  3445. }
  3446. if(text){
  3447. let firstPinyin = getFirstLetter(text)
  3448. if(!alphabetSet.has(firstPinyin)){
  3449. alphabetSet.add(firstPinyin)
  3450. }
  3451. }
  3452. // const pyStr = song.pyStr
  3453. // if(pyStr){
  3454. // if(!alphabetSet.has(pyStr)){
  3455. // alphabetSet.add(pyStr)
  3456. // }
  3457. // }
  3458. }
  3459. this.alphaBet = Array.from(alphabetSet).sort((a,b)=>{
  3460. if(this.sortType ===4||this.sortType==0||this.sortType==2||this.sortType==6){
  3461. return a.localeCompare(b)
  3462. }else{
  3463. return b.localeCompare(a)
  3464. }
  3465. })
  3466. if(this.videoLocalList.length > 0){
  3467. this.listScroller.scrollToIndex(0)
  3468. this.selectAlphaBetIndex = 0
  3469. }
  3470. resolve()
  3471. }catch (e) {
  3472. console.error('testTag','排序字母表出错',JSON.stringify(e))
  3473. resolve()
  3474. }
  3475. })
  3476. }
  3477. @Builder
  3478. topTitleBar(){
  3479. Column() {
  3480. Row({ space: 15 }) {
  3481. if (!this.isSearchMode ) {
  3482. //左侧滑动按钮
  3483. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3484. SymbolGlyph(this.rightTopImage)
  3485. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3486. }
  3487. .attributeModifier(new ButtonFancyModifier(40, 40))
  3488. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3489. .animation({ duration: 300, curve: Curve.Ease })
  3490. .onClick(() => {
  3491. this.doSwipBack()
  3492. })
  3493. .attributeModifier(new ShadowModifier())
  3494. .zIndex(0)
  3495. }else{
  3496. //左侧搜索返回按钮
  3497. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3498. SymbolGlyph($r('sys.symbol.chevron_left'))
  3499. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3500. }
  3501. .attributeModifier(new ButtonFancyModifier(40, 40))
  3502. .margin({bottom:5})
  3503. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3504. .animation({ duration: 300, curve: Curve.Ease })
  3505. .onClick(() => {
  3506. this.isSearchMode = false
  3507. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  3508. this.searchText = ''
  3509. this.getSortedFiles(this.currentPath)
  3510. return
  3511. }
  3512. this.onSearchInput('')
  3513. })
  3514. .attributeModifier(new ShadowModifier())
  3515. .zIndex(0)
  3516. }
  3517. if (!this.isSearchMode) {
  3518. Text(this.titleName)
  3519. .margin({left:3,right:10})
  3520. .fontColor($r('app.color.text_color'))
  3521. .fontSize(this.twoFingerType==3?19:this.twoFingerType==2?17:15)
  3522. .maxLines(1)
  3523. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3524. .layoutWeight(1)
  3525. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3526. }
  3527. //搜索框
  3528. Search({ controller: this.searchController,value: this.searchText, placeholder: '搜索标题、艺术家...' })
  3529. .searchButton('搜索',{fontColor:this.themeColor})
  3530. .searchIcon({
  3531. src: $r('sys.media.ohos_ic_public_search_filled')
  3532. })
  3533. .cancelButton({
  3534. style: CancelButtonStyle.CONSTANT,
  3535. icon: {
  3536. src: $r('sys.media.ohos_ic_public_cancel_filled')
  3537. }
  3538. })
  3539. .layoutWeight(1)
  3540. .height(40)
  3541. .maxLength(20)
  3542. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  3543. .placeholderColor(Color.Grey)
  3544. .placeholderFont({ size: 14, weight: 400 })
  3545. .textFont({ size: 14, weight: 400 })
  3546. .onSubmit((value: string) => {
  3547. console.log('onecold onSubmit ='+value)
  3548. this.searchController.stopEditing()
  3549. this.onSearchInput(this.searchText);
  3550. })
  3551. .onChange((value: string) => {
  3552. console.log('onecold onChange ='+value)
  3553. this.onSearchInput(value);
  3554. })
  3555. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  3556. .animation({ duration: 300, curve: Curve.Ease })
  3557. //搜索按钮
  3558. if (!this.isSearchMode) {
  3559. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3560. SymbolGlyph($r('sys.symbol.magnifyingglass'))
  3561. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3562. }
  3563. .attributeModifier(new ButtonFancyModifier(40, 40))
  3564. .animation({ duration: 300, curve: Curve.Ease })
  3565. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3566. .attributeModifier(new ShadowModifier())
  3567. .zIndex(0)
  3568. .onClick(()=>{
  3569. this.isSearchMode = true
  3570. })
  3571. //排序按钮
  3572. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3573. SymbolGlyph($r('sys.symbol.list_number'))
  3574. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3575. }
  3576. .attributeModifier(new ButtonFancyModifier(40, 40))
  3577. .animation({ duration: 300, curve: Curve.Ease })
  3578. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3579. .bindMenu((this.modeType==2&&!this.isCanBack)||(this.modeType==3&&!this.isCanBack)
  3580. ?this.SortMenuForArtistAblumBuilder:this.SortMenuBuilder)
  3581. .attributeModifier(new ShadowModifier())
  3582. .zIndex(0)
  3583. //添加按钮
  3584. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3585. SymbolGlyph($r('sys.symbol.plus'))
  3586. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3587. }
  3588. .attributeModifier(new ButtonFancyModifier(40, 40))
  3589. .animation({ duration: 300, curve: Curve.Ease })
  3590. .visibility(this.modeType==0||this.modeType==1?Visibility.Visible:Visibility.None)
  3591. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3592. .bindSheet($$this.showAddSheet, this.addSheet(), {
  3593. height: SheetSize.FIT_CONTENT,
  3594. dragBar: true,
  3595. showClose: true,
  3596. preferType: SheetType.CENTER ,
  3597. title: {
  3598. title: '导入音乐'
  3599. }
  3600. })
  3601. .onClick(() => {
  3602. this.showAddSheet = !this.showAddSheet;
  3603. })
  3604. .attributeModifier(new ShadowModifier())
  3605. .zIndex(0)
  3606. }
  3607. }
  3608. }
  3609. .padding({ top: this.topSafeHeight+10, left: 10, right: 10 })
  3610. .width('100%')
  3611. .visibility(this.isShowTitleBar?Visibility.Visible:
  3612. this.autoHideTitle?Visibility.None:Visibility.Visible)
  3613. .animation({
  3614. duration: 500,
  3615. curve: Curve.Friction // 可选动画曲线
  3616. })
  3617. }
  3618. @Builder
  3619. addSheet() {
  3620. Scroll() {
  3621. Column() {
  3622. Column() {
  3623. Row() {
  3624. Text('导入音乐复制到DownLoad目录')
  3625. .margin({ left: 18 })
  3626. .fontSize(14)
  3627. .fontColor($r('app.color.text_color'))
  3628. .fontWeight(480)
  3629. .layoutWeight(1)
  3630. Toggle({ type: ToggleType.Switch, isOn: this.isCopyFileToDownLoad })
  3631. .selectedColor(this.themeColor)
  3632. .switchPointColor(Color.White)
  3633. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  3634. .margin({ right: 18 })
  3635. .onChange((checked: boolean) => {
  3636. this.isCopyFileToDownLoad = checked;
  3637. PreferencesUtil.put(SettingPage.IS_COPYFILE_TO_DOWNLOAD, this.isCopyFileToDownLoad)
  3638. })
  3639. .width(50)
  3640. .height(30);
  3641. }
  3642. .height(88)
  3643. }
  3644. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3645. .backgroundColor($r('app.color.start_window_background'))
  3646. .borderRadius(15)
  3647. .margin({
  3648. left: 30,
  3649. right: 30,
  3650. top: 10,
  3651. bottom: 10
  3652. })
  3653. .padding(0)
  3654. .border({
  3655. color: Color.White,
  3656. width: 1.8
  3657. })
  3658. Menu() {
  3659. MenuItem({
  3660. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder_badge_plus')),
  3661. content: "新建文件夹"
  3662. })
  3663. .backgroundColor($r('app.color.silvery'))
  3664. .border({
  3665. width: { bottom: 1 },
  3666. color: '#12ec5c87'
  3667. })
  3668. .margin(10)
  3669. .padding({left:15,right:15})
  3670. .onClick(async () => {
  3671. this.showMkDialog()
  3672. this.showAddSheet = !this.showAddSheet
  3673. })
  3674. MenuItem({
  3675. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder')),
  3676. content: $r('app.string.import_from_files')
  3677. })
  3678. .padding({left:15,right:15})
  3679. .backgroundColor($r('app.color.silvery'))
  3680. .border({
  3681. width: { bottom: 1 },
  3682. color: '#12ec5c87'
  3683. })
  3684. .margin(10)
  3685. .onClick(async () => {
  3686. this.callFilePickerSelectFile()
  3687. this.showAddSheet = !this.showAddSheet
  3688. })
  3689. MenuItem({
  3690. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square')),
  3691. content: '全选导入'
  3692. // content: '从下载文件夹导入(路径:Download/' +
  3693. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  3694. })
  3695. .padding({left:15,right:15})
  3696. .backgroundColor($r('app.color.silvery'))
  3697. .border({
  3698. width: { bottom: 1 },
  3699. color: '#12ec5c87'
  3700. })
  3701. .margin(10)
  3702. .onClick(async () => {
  3703. this.goSelectMusic()
  3704. this.showAddSheet = !this.showAddSheet
  3705. })
  3706. MenuItem({
  3707. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.save')),
  3708. content: '自动导入教程'
  3709. // content: '从下载文件夹导入(路径:Download/' +
  3710. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  3711. })
  3712. .padding({left:15,right:15})
  3713. .backgroundColor($r('app.color.silvery'))
  3714. .border({
  3715. width: { bottom: 1 },
  3716. color: '#12ec5c87'
  3717. })
  3718. .margin(10)
  3719. .onClick(async () => {
  3720. this.showTips()
  3721. this.showAddSheet = !this.showAddSheet
  3722. })
  3723. }.attributeModifier(new MenuModifier())
  3724. .margin({bottom:30})
  3725. }
  3726. .layoutWeight(1)
  3727. }
  3728. }
  3729. @Builder
  3730. TagsContentCoverBuilder() {
  3731. Scroll() {
  3732. Column() {
  3733. TagsContentCover(
  3734. {
  3735. selectedFiles:this.selectedFiles,
  3736. isOneKeyTags:this.isOneKeyTags,
  3737. onSeePath:(path:string)=>{
  3738. this.modeType = 0
  3739. this.deleteCache(path)
  3740. this.getSortedFiles(path)
  3741. },
  3742. onTagsResult:(result: boolean,deleteCache_path?:string)=>{
  3743. this.isMultiSelect = false
  3744. if(result){//如果嵌入成功,更新数据
  3745. this.listRefreshKey++
  3746. setTimeout(()=>{
  3747. this.doUpdateData()
  3748. },500)
  3749. }
  3750. console.info('onecold onTagsResult deleteCache_path =' +deleteCache_path)
  3751. if(deleteCache_path){
  3752. this.deleteCache(deleteCache_path)
  3753. }
  3754. }
  3755. }
  3756. )
  3757. }
  3758. }
  3759. .width('100%')
  3760. .height('100%')
  3761. }
  3762. @Builder
  3763. FixMessyViewBuilder() {
  3764. Scroll() {
  3765. Column() {
  3766. FixMessyView(
  3767. {
  3768. selectedFiles:this.selectedFiles,
  3769. isFixMessy:this.isFixMessy,
  3770. onFixResult:(result: boolean)=>{
  3771. this.isMultiSelect = false
  3772. if(result){//如果嵌入成功,更新数据
  3773. this.deleteCache(this.currentPath)
  3774. this.doUpdateData()
  3775. }
  3776. }
  3777. }
  3778. )
  3779. }
  3780. }
  3781. .width('100%')
  3782. .height('100%')
  3783. }
  3784. //剪辑音频
  3785. @Builder
  3786. EditAudioBuilder(item:VideoItem) {
  3787. Scroll() {
  3788. Column() {
  3789. EditAudio(
  3790. {
  3791. mVideoItem:item,
  3792. currentPath:this.currentPath,
  3793. videoUrl:this.videoUrl,
  3794. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3795. currentTime:this.currentTime,
  3796. progressValue:this.progressValue,
  3797. onBack:()=>{
  3798. this.isEditAudio = !this.isEditAudio
  3799. },
  3800. onSeeOutputPath:(outPutPath:string)=>{
  3801. this.isEditAudio = !this.isEditAudio
  3802. this.longItemFilePath = ''
  3803. this.modeType = 0
  3804. this.isShowFileName = true
  3805. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3806. },
  3807. onPlayOrPause:()=>{
  3808. if(this.videoUrl==item.filePath){
  3809. this.playOrPause()
  3810. }else{//如果不是当前播放的,则播放该文件
  3811. this.videoUrl==item.filePath
  3812. this.doPlay(item,0,false,true)
  3813. }
  3814. },
  3815. onSliderChange:(value:number)=>{
  3816. if(this.videoUrl!=item.filePath){
  3817. this.videoUrl==item.filePath
  3818. return
  3819. }
  3820. this.isSeekTo = true;
  3821. this.mDestroyPage = false;
  3822. this.showLoadIng();
  3823. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  3824. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3825. this.seekTo(seekValue + "");
  3826. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  3827. this.isSeekTo = false;
  3828. },
  3829. onResult:(result: boolean,outPath:string)=>{
  3830. if(result){//如果剪辑成功,更新数据
  3831. this.doUpdateData()
  3832. }else{
  3833. ToastUtil.showToast('剪辑失败')
  3834. }
  3835. }
  3836. }
  3837. )
  3838. }
  3839. }
  3840. .width('100%')
  3841. .height('100%')
  3842. }
  3843. //提取伴奏
  3844. @Builder
  3845. ConverterBuilder(item:VideoItem) {
  3846. Scroll() {
  3847. Column() {
  3848. AudioFormatConverter(
  3849. {
  3850. mVideoItem:item,
  3851. videoUrl:this.videoUrl,
  3852. currentPath:this.currentPath,
  3853. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3854. currentTime:this.currentTime,
  3855. progressValue:this.progressValue,
  3856. onBack:()=>{
  3857. this.isConverter = !this.isConverter
  3858. this.longItemFilePath = ''
  3859. },
  3860. onPlayOrPause:()=>{
  3861. if(this.videoUrl==item.filePath){
  3862. this.playOrPause()
  3863. }else{//如果不是当前播放的,则播放该文件
  3864. this.videoUrl==item.filePath
  3865. this.doPlay(item,0,false,true)
  3866. }
  3867. },
  3868. onSeeOutputPath:(outPutPath:string)=>{
  3869. this.isConverter = !this.isConverter
  3870. this.longItemFilePath = ''
  3871. this.modeType = 0
  3872. this.isShowFileName = true
  3873. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3874. },
  3875. onSliderChange:(value:number)=>{
  3876. if(this.videoUrl!=item.filePath){
  3877. this.videoUrl==item.filePath
  3878. return
  3879. }
  3880. this.isSeekTo = true;
  3881. this.mDestroyPage = false;
  3882. this.showLoadIng();
  3883. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3884. this.seekTo(seekValue + "");
  3885. this.isSeekTo = false;
  3886. },
  3887. onResult:(result: boolean,outPath:string)=>{
  3888. if(result){//如果成功,更新数据
  3889. this.doUpdateData()
  3890. }else{
  3891. ToastUtil.showToast('格式转化失败')
  3892. }
  3893. }
  3894. }
  3895. )
  3896. }
  3897. }
  3898. .width('100%')
  3899. .height('100%')
  3900. }
  3901. //提取伴奏
  3902. @Builder
  3903. ExtractAccBuilder(item:VideoItem) {
  3904. Scroll() {
  3905. Column() {
  3906. ExtractAccompaniment(
  3907. {
  3908. mVideoItem:item,
  3909. currentPath:this.currentPath,
  3910. videoUrl:this.videoUrl,
  3911. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3912. currentTime:this.currentTime,
  3913. progressValue:this.progressValue,
  3914. onBack:()=>{
  3915. this.isExtractAcc = !this.isExtractAcc
  3916. this.longItemFilePath = ''
  3917. },
  3918. onPlayOrPause:()=>{
  3919. if(this.videoUrl==item.filePath){
  3920. this.playOrPause()
  3921. }else{//如果不是当前播放的,则播放该文件
  3922. this.videoUrl==item.filePath
  3923. this.doPlay(item,0,false,true)
  3924. }
  3925. },
  3926. onSeeOutputPath:(outPutPath:string)=>{
  3927. this.isExtractAcc = !this.isExtractAcc
  3928. this.longItemFilePath = ''
  3929. this.modeType = 0
  3930. this.isShowFileName = true
  3931. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3932. },
  3933. onSliderChange:(value:number)=>{
  3934. if(this.videoUrl!=item.filePath){
  3935. this.videoUrl==item.filePath
  3936. return
  3937. }
  3938. this.isSeekTo = true;
  3939. this.mDestroyPage = false;
  3940. this.showLoadIng();
  3941. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3942. this.seekTo(seekValue + "");
  3943. this.isSeekTo = false;
  3944. },
  3945. onResult:(result: boolean,outPath:string)=>{
  3946. if(result){//如果成功,更新数据
  3947. this.doUpdateData()
  3948. }else{
  3949. ToastUtil.showToast('提取伴奏失败')
  3950. }
  3951. }
  3952. }
  3953. )
  3954. }
  3955. }
  3956. .width('100%')
  3957. .height('100%')
  3958. }
  3959. //AI人声分离
  3960. @Builder
  3961. AiBuilder(item:VideoItem) {
  3962. Scroll() {
  3963. Column() {
  3964. AIVoiceSeparation(
  3965. {
  3966. mVideoItem:item,
  3967. videoUrl:this.videoUrl,
  3968. currentPath:this.currentPath,
  3969. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3970. currentTime:this.currentTime,
  3971. progressValue:this.progressValue,
  3972. onBack:()=>{
  3973. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  3974. this.longItemFilePath = ''
  3975. },
  3976. onPlayOrPause:()=>{
  3977. if(this.videoUrl==item.filePath||this.isPlaying){
  3978. this.playOrPause()
  3979. }else{//如果不是当前播放的,则播放该文件
  3980. this.videoUrl==item.filePath
  3981. this.doPlay(item,0,false,true)
  3982. }
  3983. },
  3984. onPlayPath:(path:string)=>{
  3985. this.videoUrl==path
  3986. const itemP = Utility.getItemByFilePath(this.videoLocalList,path)
  3987. if(itemP)
  3988. this.doPlay(itemP,0,false,true)
  3989. },
  3990. onSeeOutputPath:(outPutPath:string)=>{
  3991. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  3992. this.longItemFilePath = ''
  3993. this.modeType = 0
  3994. this.isShowFileName = true
  3995. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3996. },
  3997. onSliderChange:(value:number)=>{
  3998. if(this.videoUrl!=item.filePath){
  3999. this.videoUrl==item.filePath
  4000. return
  4001. }
  4002. this.isSeekTo = true;
  4003. this.mDestroyPage = false;
  4004. this.showLoadIng();
  4005. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  4006. this.seekTo(seekValue + "");
  4007. this.isSeekTo = false;
  4008. },
  4009. onResult:(result: boolean,outPath:string)=>{
  4010. if(result){//如果成功,更新数据
  4011. this.doUpdateData()
  4012. }else{
  4013. ToastUtil.showToast('Ai人声分离失败')
  4014. }
  4015. }
  4016. }
  4017. )
  4018. }
  4019. }
  4020. .width('100%')
  4021. .height('100%')
  4022. }
  4023. //变速变调
  4024. @Builder
  4025. ChangeToneBuilder(item:VideoItem) {
  4026. Scroll() {
  4027. Column() {
  4028. ChangeTone(
  4029. {
  4030. mVideoItem:item,
  4031. currentPath:this.currentPath,
  4032. videoUrl:this.videoUrl,
  4033. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4034. currentTime:this.currentTime,
  4035. progressValue:this.progressValue,
  4036. onBack:()=>{
  4037. this.isChangeTone = !this.isChangeTone
  4038. this.longItemFilePath = ''
  4039. },
  4040. onPlayOrPause:()=>{
  4041. if(this.videoUrl==item.filePath){
  4042. this.playOrPause()
  4043. }else{//如果不是当前播放的,则播放该文件
  4044. this.videoUrl==item.filePath
  4045. this.doPlay(item,0,false,true)
  4046. }
  4047. },
  4048. onSeeOutputPath:(outPutPath:string)=>{
  4049. this.isChangeTone = !this.isChangeTone
  4050. this.longItemFilePath = ''
  4051. this.modeType = 0
  4052. this.isShowFileName = true
  4053. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4054. },
  4055. onSliderChange:(value:number)=>{
  4056. if(this.videoUrl!=item.filePath){
  4057. this.videoUrl==item.filePath
  4058. return
  4059. }
  4060. this.isSeekTo = true;
  4061. this.mDestroyPage = false;
  4062. this.showLoadIng();
  4063. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  4064. this.seekTo(seekValue + "");
  4065. this.isSeekTo = false;
  4066. },
  4067. onResult:(result: boolean,outPath:string)=>{
  4068. if(result){//如果成功,更新数据
  4069. this.doUpdateData()
  4070. }else{
  4071. ToastUtil.showToast('变速变调失败')
  4072. }
  4073. }
  4074. }
  4075. )
  4076. }
  4077. }
  4078. .width('100%')
  4079. .height('100%')
  4080. }
  4081. //提取视频中的音频
  4082. @Builder
  4083. extractAudioFromVideoBuilder(item:VideoItem) {
  4084. Scroll() {
  4085. Column() {
  4086. ExtractAudioFromVideo(
  4087. {
  4088. mVideoItem:item,
  4089. currentPath:this.currentPath,
  4090. videoUrl:this.videoUrl,
  4091. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4092. currentTime:this.currentTime,
  4093. progressValue:this.progressValue,
  4094. onBack:()=>{
  4095. this.isExtractAudio = !this.isExtractAudio
  4096. this.longItemFilePath = ''
  4097. },
  4098. onPlayOrPause:()=>{
  4099. if(this.videoUrl==item.filePath){
  4100. this.playOrPause()
  4101. }else{//如果不是当前播放的,则播放该文件
  4102. this.videoUrl==item.filePath
  4103. this.doPlay(item,0,false,true)
  4104. }
  4105. },
  4106. onSeeOutputPath:(outPutPath:string)=>{
  4107. this.isExtractAudio = !this.isExtractAudio
  4108. this.longItemFilePath = ''
  4109. this.modeType = 0
  4110. this.isShowFileName = true
  4111. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4112. },
  4113. onSliderChange:(value:number)=>{
  4114. if(this.videoUrl!=item.filePath){
  4115. this.videoUrl==item.filePath
  4116. return
  4117. }
  4118. this.isSeekTo = true;
  4119. this.mDestroyPage = false;
  4120. this.showLoadIng();
  4121. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  4122. this.seekTo(seekValue + "");
  4123. this.isSeekTo = false;
  4124. },
  4125. onResult:(result: boolean,outPath:string)=>{
  4126. if(result){//如果成功,更新数据
  4127. this.doUpdateData()
  4128. }else{
  4129. ToastUtil.showToast('提取音频失败')
  4130. }
  4131. }
  4132. }
  4133. )
  4134. }
  4135. }
  4136. .width('100%')
  4137. .height('100%')
  4138. }
  4139. //合并音频
  4140. @Builder
  4141. MergeAudioBuilder() {
  4142. Scroll() {
  4143. Column() {
  4144. MergeAudio(
  4145. {
  4146. videoUrl:this.videoUrl,
  4147. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4148. currentPath:this.currentPath,
  4149. selectedFiles:this.selectedFiles,
  4150. currentTime:this.currentTime,
  4151. progressValue:this.progressValue,
  4152. onBack:()=>{
  4153. this.isMergeAudio = !this.isMergeAudio
  4154. this.longItemFilePath = ''
  4155. },
  4156. // onPlayPath:(path:string)=>{
  4157. // if(this.videoUrl==item.filePath){
  4158. // this.playOrPause()
  4159. // }else{//如果不是当前播放的,则播放该文件
  4160. // this.videoUrl==item.filePath
  4161. // this.doPlay(item,0,false,true)
  4162. // }
  4163. //
  4164. // },
  4165. onSeeOutputPath:(outPutPath:string)=>{
  4166. this.isMergeAudio = !this.isMergeAudio
  4167. this.longItemFilePath = ''
  4168. this.modeType = 0
  4169. this.isShowFileName = true
  4170. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4171. },
  4172. onResult:(result: boolean,outPath:string)=>{
  4173. if(result){//如果成功,更新数据
  4174. this.doUpdateData()
  4175. }else{
  4176. if(this.selectedFiles.length>=3){
  4177. ToastUtil.showToast('合并数量太多导致失败')
  4178. }else{
  4179. ToastUtil.showToast('合并失败')
  4180. }
  4181. }
  4182. }
  4183. }
  4184. )
  4185. }
  4186. }
  4187. .width('100%')
  4188. .height('100%')
  4189. }
  4190. asyncCurrentPathData() {
  4191. if (this.modeType == 0) {
  4192. workerInstance.postMessage({
  4193. code: 1,
  4194. data1: this.context,
  4195. data2: this.currentPath,
  4196. data3: this.lockPath,
  4197. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  4198. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  4199. });
  4200. }
  4201. }
  4202. // 处理文件选择的函数
  4203. handleFileSelection(item: VideoItem, checked: boolean) {
  4204. if (checked) {
  4205. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  4206. this.selectedFiles.push(item);
  4207. }
  4208. } else {
  4209. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  4210. if (index > -1) {
  4211. this.selectedFiles.splice(index, 1);
  4212. }
  4213. }
  4214. }
  4215. private deleteComponentId: number = 0
  4216. //多选删除文件
  4217. showWarnIsDelete(){
  4218. this.getUIContext().getPromptAction().openCustomDialog({
  4219. builder: () => {
  4220. this.deleteComptentBuilder()
  4221. },
  4222. isModal:true,
  4223. showInSubWindow:false,
  4224. maskColor: Color.Transparent,
  4225. dialogTransition: // 设置弹窗内容显示的过渡效果
  4226. TransitionEffect.translate({ x: 0, y: 290, z: 0 })
  4227. .animation({ duration: 600, curve: Curve.Smooth }),
  4228. maskTransition: // 设置蒙层显示的过渡效果
  4229. TransitionEffect.opacity(0)
  4230. .animation({ duration: 600, curve: Curve.Smooth })
  4231. }).then((dialogId: number) => {
  4232. this.deleteComponentId = dialogId
  4233. })
  4234. .catch((error: BusinessError) => {
  4235. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  4236. })
  4237. }
  4238. @Builder
  4239. deleteComptentBuilder(){
  4240. DeleteComptent({
  4241. selectedFiles:this.selectedFiles,
  4242. onCancel:()=>{
  4243. this.isMultiSelect = false
  4244. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  4245. },
  4246. onDeleteResult:(result: boolean)=>{
  4247. this.isMultiSelect = false
  4248. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  4249. if(result){//如果删除成功,更新数据
  4250. this.selectedFiles = [];
  4251. this.isAllSelected = false
  4252. this.cache.delete(this.currentPath);
  4253. this.getSortedFiles(this.currentPath, true);
  4254. }
  4255. }
  4256. })
  4257. }
  4258. //多选移动文件
  4259. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  4260. Logger.info('onecold showCutDialogForMultipleFiles')
  4261. let mList: Array<string> = []
  4262. let rPath = this.rootPath
  4263. if (isCurrent) {
  4264. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  4265. rPath = this.currentPath
  4266. } else {
  4267. mList = Utility.getNameList(this.dirList);
  4268. rPath = this.rootPath
  4269. }
  4270. let dataBean = new BubbleBean();
  4271. dataBean.data = mList;
  4272. dataBean.color = this.themeColor
  4273. dataBean.onItemClick = (i) => {
  4274. const newDirPath = rPath + '/' + mList[i];
  4275. // Logger.info('newDirPath = ' + newDirPath)
  4276. this.selectedFiles.forEach((item) => {
  4277. const newPath = newDirPath + '/' + item.fileName;
  4278. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  4279. ToastUtil.showToast('移动成功');
  4280. this.table.deleteData(item, () => {
  4281. this.cache.delete(this.currentPath); // 删除原路径缓存
  4282. this.cache.delete(newDirPath); // 删除目标路径缓存
  4283. this.getSortedFiles(this.currentPath, true);
  4284. });
  4285. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  4286. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  4287. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  4288. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  4289. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  4290. this.table.insert(newItem, (id: number) => {
  4291. //加入数据库
  4292. });
  4293. }
  4294. }).catch((error: Error) => {
  4295. console.error(error.message);
  4296. });
  4297. });
  4298. this.isMultiSelect = false
  4299. this.selectedFiles = [];
  4300. this.isAllSelected = false
  4301. XPopup.dismissTop();
  4302. };
  4303. let pup: XPopup
  4304. if (this.isDarkMode) {
  4305. pup = XPopup.Builder()
  4306. .setPopupPosition(PopupPosition.TOP)
  4307. .atView(viewId)
  4308. .setBackgroundColor(Color.Black)
  4309. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4310. .show();
  4311. } else {
  4312. pup = XPopup.Builder()
  4313. .setPopupPosition(PopupPosition.TOP)
  4314. .atView(viewId)
  4315. .setBackgroundColor(Color.White)
  4316. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4317. .show();
  4318. }
  4319. }
  4320. /**
  4321. * 加载所有歌单
  4322. */
  4323. async loadAllPlaylists() {
  4324. try {
  4325. this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
  4326. LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
  4327. } catch (error) {
  4328. LogUtil.error('heaunp Failed to load playlists: ' + error.message)
  4329. }
  4330. }
  4331. /**
  4332. * 显示添加到歌单对话框
  4333. */
  4334. async openAddToPlaylistDialog(items: VideoItem | VideoItem[]) {
  4335. const songs = Array.isArray(items) ? items : [items]
  4336. const musicItems = songs.filter(song => song.type !== CommonConstants.TYPE_IS_DIR)
  4337. if (musicItems.length === 0) {
  4338. ToastUtil.showToast('请选择要添加的歌曲')
  4339. return
  4340. }
  4341. // 加载最新的歌单列表
  4342. await this.loadAllPlaylists()
  4343. showAddToPlaylistDialog(
  4344. musicItems,
  4345. this.allPlaylists,
  4346. async (playlistId: string) => {
  4347. // 添加歌曲到歌单
  4348. const success = await this.playlistTable?.addSongsToPlaylist(playlistId,
  4349. musicItems.map(song => song.filePath))
  4350. if (success) {
  4351. const count = musicItems.length
  4352. ToastUtil.showToast(count > 1 ? `已添加 ${count} 首歌曲` : '已添加到歌单')
  4353. // 重新加载歌单列表
  4354. await this.loadAllPlaylists()
  4355. } else {
  4356. ToastUtil.showToast(musicItems.length > 1 ? '选中的歌曲已在该歌单中' : '歌曲已在该歌单中')
  4357. }
  4358. this.longItemFilePath = ''
  4359. if (this.isMultiSelect) {
  4360. this.isMultiSelect = false
  4361. this.isAllSelected = false
  4362. this.selectedFiles = []
  4363. }
  4364. },
  4365. () => {
  4366. LogUtil.info('取消添加到歌单')
  4367. },
  4368. () => {
  4369. // 创建新歌单
  4370. showCreatePlaylistDialog(
  4371. async (name: string, description: string, coverPath?: string) => {
  4372. const success = await this.playlistTable?.createPlaylist(name, description, coverPath)
  4373. if (success) {
  4374. ToastUtil.showToast('歌单创建成功')
  4375. // 重新加载歌单列表并打开添加对话框
  4376. await this.loadAllPlaylists()
  4377. await this.openAddToPlaylistDialog(musicItems)
  4378. } else {
  4379. ToastUtil.showToast('歌单创建失败')
  4380. }
  4381. },
  4382. () => {
  4383. // 取消创建歌单
  4384. }
  4385. )
  4386. }
  4387. )
  4388. }
  4389. doFav(item: VideoItem) {
  4390. LogUtil.info('onecold doFav isFav=' + item.isFav)
  4391. let isFav = 0
  4392. if (Utility.getIsFav(this.favList, item)) {
  4393. isFav = 0
  4394. } else {
  4395. isFav = 1
  4396. }
  4397. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  4398. if (result) {
  4399. if (isFav === 1) {
  4400. ToastUtil.showToast('收藏成功');
  4401. } else {
  4402. ToastUtil.showToast('取消收藏成功');
  4403. }
  4404. this.deleteCache(this.currentPath)
  4405. this.getFavList(false)
  4406. if (this.modeType === 0 && !this.isFavMusic) {
  4407. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  4408. this.getSortedFiles(this.currentPath)
  4409. }
  4410. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  4411. workerInstance.postMessage({ code: 3, data: this.context });
  4412. workerInstance.postMessage({ code: 4, data: this.context });
  4413. }
  4414. })
  4415. }
  4416. //多选复制文件
  4417. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  4418. console.log('onecold showCopyDialogForMultipleFiles');
  4419. let mList: Array<string> = []
  4420. let rPath = this.rootPath
  4421. if (isCurrent) {
  4422. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  4423. rPath = this.currentPath
  4424. } else {
  4425. mList = Utility.getNameList(this.dirList);
  4426. rPath = this.rootPath
  4427. }
  4428. let dataBean = new BubbleBean();
  4429. dataBean.data = mList;
  4430. dataBean.isCopy = true
  4431. dataBean.color = this.themeColor
  4432. dataBean.onItemClick = (i) => {
  4433. const newDirPath = rPath + '/' + mList[i];
  4434. // Logger.info('newDirPath = ' + newDirPath)
  4435. this.selectedFiles.forEach((item) => {
  4436. const newPath = newDirPath + '/' + item.fileName;
  4437. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  4438. ToastUtil.showToast('复制成功');
  4439. this.cache.delete(newDirPath); // 删除目标路径缓存
  4440. this.getSortedFiles(this.currentPath);
  4441. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  4442. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  4443. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  4444. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  4445. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  4446. this.table.insert(newItem, (id: number) => {
  4447. //加入数据库
  4448. });
  4449. }
  4450. }).catch((error: Error) => {
  4451. console.error(error.message);
  4452. });
  4453. });
  4454. this.isMultiSelect = false
  4455. this.selectedFiles = [];
  4456. this.isAllSelected = false
  4457. XPopup.dismissTop();
  4458. };
  4459. let pup: XPopup
  4460. if (this.isDarkMode) {
  4461. pup = XPopup.Builder()
  4462. .setPopupPosition(PopupPosition.TOP)
  4463. .atView(viewId)
  4464. .setBackgroundColor(Color.Black)
  4465. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4466. .show();
  4467. } else {
  4468. pup = XPopup.Builder()
  4469. .setPopupPosition(PopupPosition.TOP)
  4470. .atView(viewId)
  4471. .setBackgroundColor(Color.White)
  4472. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4473. .show();
  4474. }
  4475. }
  4476. @Builder
  4477. private DirItem(item: VideoItem, index?: number) {
  4478. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  4479. Row() {
  4480. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  4481. $r('app.media.music_group'))
  4482. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4483. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4484. .fillColor(this.themeColor)// .fontSize(33)
  4485. .alt($r('app.media.music_group'))
  4486. .borderRadius(this.isCoverRectangle?9:'100%')
  4487. .clip(true)
  4488. .shadow({
  4489. radius: 2,
  4490. type: ShadowType.BLUR,
  4491. color: 'on_primary'
  4492. })
  4493. .sourceSize({width:38, height:38})
  4494. .margin({ left: 20, top: 8, bottom: 8 })
  4495. Column() {
  4496. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4497. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4498. .maxLines(1)// .width('88%')
  4499. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4500. .animation({
  4501. duration: 555,
  4502. curve: 'ease-in-out',
  4503. })
  4504. .transition({
  4505. type: TransitionType.Insert,
  4506. opacity: 0,
  4507. translate: { x: 160 }
  4508. })
  4509. .margin({ left: 10, right: 20 })
  4510. .fontColor($r('app.color.text_color'))
  4511. Row() {
  4512. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  4513. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4514. .padding({ top: 8 })
  4515. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  4516. .fontColor($r('app.color.text_color'))
  4517. .margin({ left: 10 })
  4518. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  4519. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4520. .padding({ top: 8 })
  4521. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  4522. .fontColor($r('app.color.text_color'))
  4523. .margin({ left: 10 })
  4524. Blank()
  4525. }
  4526. }
  4527. .height('100%')
  4528. .layoutWeight(1)
  4529. .justifyContent(FlexAlign.Center)
  4530. .alignItems(HorizontalAlign.Start)
  4531. Blank()
  4532. Image($r('app.media.arrow_right'))
  4533. .height(25)
  4534. .alignSelf(ItemAlign.Center)
  4535. .id(item.filePath)
  4536. .visibility(this.isShowAlphaBet?Visibility.None:Visibility.Visible)
  4537. .animation({ duration: 300, curve: Curve.Ease })
  4538. }
  4539. }
  4540. .backgroundColor(Color.Transparent)
  4541. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  4542. .width('98%')
  4543. .reuseId('dir_item')
  4544. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  4545. .opacity(this.opacityItem) // 绑定透明度
  4546. }
  4547. isShowDir(dirName: string) {
  4548. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  4549. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  4550. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  4551. if (dirName === undefined) {
  4552. return true
  4553. }
  4554. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  4555. return this.isShowSimi
  4556. }
  4557. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  4558. return this.isShowFAV
  4559. }
  4560. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  4561. return this.isShowHistory
  4562. }
  4563. return true
  4564. }
  4565. @State opacityItem: number = 1; // 控制透明度的状态变量
  4566. @Builder
  4567. private MusicItem(item: VideoItem, index?: number) {
  4568. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  4569. Row() {
  4570. Stack() {
  4571. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  4572. .fillColor(this.themeColor)
  4573. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4574. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4575. .alt($r('app.media.music_red'))
  4576. .borderRadius(this.isCoverRectangle?9:'100%')
  4577. .clip(true)
  4578. .draggable(false)
  4579. .sourceSize({width:38, height:38})
  4580. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4581. // .autoResize(true) // 重采样,可减少内存占用
  4582. .opacity(this.opacityItem)// 绑定透明度
  4583. .margin({ left: 20 })
  4584. .shadow({
  4585. radius: StrUtil.isEmpty(item.pixelMapPath) ?6:14,
  4586. type: ShadowType.BLUR,
  4587. color: 'on_primary'
  4588. })
  4589. .gesture(LongPressGesture()
  4590. .onAction(async () => {
  4591. //如果是专辑和艺术家的首页,不能长按
  4592. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4593. return
  4594. //如果是我的收藏 最近播放等也不能长按
  4595. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4596. item.name === LocalMusic.STR_HISTORY_MUSIC
  4597. )
  4598. return
  4599. this.longItemFilePath = item.filePath
  4600. this.tempLyricContent = await this.getLyricContent(item)
  4601. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4602. })
  4603. .onActionEnd((event: GestureEvent) => {
  4604. }))
  4605. .onClick(()=>{
  4606. if (this.isMultiSelect) {
  4607. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4608. this.handleFileSelection(item, !isChecked);
  4609. } else {
  4610. this.doPlay(item,index)
  4611. this.setShowPlayTrue()
  4612. }
  4613. })
  4614. }
  4615. Column() {
  4616. Column() {
  4617. Text(this.isShowFileName?item.fileName :item.name)
  4618. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4619. .maxLines(1)
  4620. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4621. .animation({
  4622. duration: 555,
  4623. curve: 'Linear',
  4624. })
  4625. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4626. $r('app.color.text_color'))
  4627. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4628. .padding({right:25})
  4629. .bindPopup(this.longItemFilePath === item.filePath, {
  4630. builder: this.MenuBuilder(item,index,item.filePath),
  4631. placement: Placement.Top,
  4632. // autoCancel: true,
  4633. mask: {color:'#33000000'},
  4634. // popupColor: Color.Yellow,
  4635. enableArrow: false,//是否显示箭头
  4636. showInSubWindow: false,
  4637. onStateChange: (e) => {
  4638. if (!e.isVisible) {
  4639. this.longItemFilePath = ''
  4640. this.tempLyricContent = ''
  4641. }
  4642. }
  4643. })
  4644. .gesture(LongPressGesture()
  4645. .onAction(async () => {
  4646. //如果是专辑和艺术家的首页,不能长按
  4647. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4648. return
  4649. //如果是我的收藏 最近播放等也不能长按
  4650. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4651. item.name === LocalMusic.STR_HISTORY_MUSIC
  4652. )
  4653. return
  4654. this.longItemFilePath = item.filePath
  4655. this.tempLyricContent = await this.getLyricContent(item)
  4656. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4657. })
  4658. .onActionEnd((event: GestureEvent) => {
  4659. })
  4660. )
  4661. Row() {
  4662. Column(){
  4663. Text(item.md5Str?.includes('Lossless')?
  4664. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4665. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  4666. .padding({ top: 3,right:6,left:6,bottom:3 })
  4667. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4668. $r('app.color.text_color'))
  4669. .fontWeight(500)
  4670. .borderRadius(12)
  4671. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  4672. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4673. .backgroundColor('#FFC107')
  4674. }
  4675. .padding({ top: 8 })
  4676. Text(StrUtil.isEmpty(item.artist) ? item.duration
  4677. :this.twoFingerType==2? item.artist +' ' + item.duration
  4678. : item.artist + ' ' + item?.duration)
  4679. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4680. .padding({ top: 8 ,right:25})
  4681. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  4682. .maxLines(1)
  4683. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4684. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4685. Color.Gray)
  4686. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4687. Blank()
  4688. Text(this.isShowFileName?item.duration:item.size)
  4689. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4690. .padding({ top: 8 })
  4691. .maxLines(1)
  4692. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  4693. ? Visibility.Visible : Visibility.None)
  4694. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4695. Color.Gray)
  4696. .margin({ left: StrUtil.isEmpty(item.artist) ?0:10 })
  4697. }
  4698. .gesture(LongPressGesture()
  4699. .onAction(async () => {
  4700. //如果是专辑和艺术家的首页,不能长按
  4701. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4702. return
  4703. //如果是我的收藏 最近播放等也不能长按
  4704. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4705. item.name === LocalMusic.STR_HISTORY_MUSIC
  4706. )
  4707. return
  4708. this.longItemFilePath = item.filePath
  4709. this.tempLyricContent = await this.getLyricContent(item)
  4710. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4711. })
  4712. .onActionEnd((event: GestureEvent) => {
  4713. })
  4714. )
  4715. }
  4716. .height('100%')
  4717. .width('100%')
  4718. .margin({ right: 10 })
  4719. .justifyContent(FlexAlign.Center)
  4720. .alignItems(HorizontalAlign.Start)
  4721. }
  4722. .height('100%')
  4723. .margin({ left: 5 })
  4724. .layoutWeight(1)
  4725. Column() {
  4726. Checkbox({ name: 'checkbox' + index })
  4727. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  4728. .selectedColor(this.themeColor)
  4729. .shape(CheckBoxShape.CIRCLE)
  4730. .opacity(this.isMultiSelect ? 1 : 0)
  4731. .animation({
  4732. duration: 666,
  4733. curve: 'Smooth' // 可选动画曲线
  4734. })
  4735. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  4736. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  4737. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  4738. .width(22)
  4739. .height(22)
  4740. ImageAnimator()
  4741. .images(this.imagesF)// 动画数组
  4742. .duration(1000)// 持续
  4743. .state(this.animationState)// 动画状态
  4744. .fillMode(FillMode.Forwards)
  4745. .width(18)
  4746. .margin({ right: 20, top: 8, bottom: 8 })
  4747. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  4748. Visibility.None)
  4749. .height(18)
  4750. .iterations(-1) // 播放次数
  4751. }
  4752. }
  4753. }
  4754. .backgroundColor(Color.Transparent)
  4755. .width('100%')
  4756. .reuseId('file_item')
  4757. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  4758. }
  4759. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  4760. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  4761. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  4762. direction: Direction.Ltr,
  4763. buttonPadding:{top:12,bottom:12},
  4764. backgroundColor: Color.Transparent,
  4765. fontSize:14,
  4766. selectedFontSize:15,
  4767. selectedFontColor:Color.White,
  4768. selectedBackgroundColor: this.themeColor,
  4769. localizedTextPadding: {
  4770. end: LengthMetrics.vp(20),
  4771. start: LengthMetrics.vp(20)
  4772. }
  4773. })
  4774. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  4775. //当胶囊按钮的选择发生变化时调用此函数
  4776. capsuleSelectedIndexesChanged() {
  4777. this.modeType = this.tabSelectedIndexes[0]
  4778. }
  4779. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  4780. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  4781. isShowCoverHeader() {
  4782. if (!this.isShowHeader) {
  4783. return false
  4784. }
  4785. if (this.modeType == 0) {
  4786. if (this.isHistory || this.isFavMusic) {
  4787. return true
  4788. }
  4789. if (this.currentPath != this.rootPath) {
  4790. return true
  4791. }
  4792. }
  4793. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  4794. }
  4795. getCoverTitleBg(): ResourceStr | image.PixelMap {
  4796. if (this.isCustomizeBg) {
  4797. return ('rgba(255,255,255,0.2)')
  4798. }
  4799. if (this.isDarkMode) {
  4800. return $r('app.color.user_center_card_background')
  4801. }
  4802. return this.currentTitleCover
  4803. }
  4804. // 第二步:popup构造器定义弹框内容
  4805. @Builder popupBuilder() {
  4806. Column({ space: 2 }) {
  4807. Text('友情提示:双指缩放可以放大缩小列表')
  4808. .fontSize(12)
  4809. .fontWeight(FontWeight.Regular)
  4810. .fontColor($r('app.color.text_color'))
  4811. }
  4812. .justifyContent(FlexAlign.SpaceAround)
  4813. .width(220)
  4814. .height(55)
  4815. .padding(15)
  4816. }
  4817. //搜索功能的实现
  4818. @State searchText: string = ''; // 用户输入内容
  4819. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  4820. @State isSearchMode: boolean = false
  4821. // 实时搜索逻辑(带防抖)
  4822. private onSearchInput(value: string) {
  4823. this.searchText = value.trim();
  4824. let mSearchList: Array<VideoItem> = []
  4825. switch (this.modeType) {
  4826. case 0:
  4827. case 1:
  4828. mSearchList = this.mediaKuList
  4829. break;
  4830. case 2:
  4831. mSearchList = this.artistList
  4832. break;
  4833. case 3:
  4834. mSearchList = this.albumList
  4835. break;
  4836. default :
  4837. mSearchList = this.videoLocalList
  4838. break;
  4839. }
  4840. // 新增条件判断:空输入时显示所有数据
  4841. if (this.searchText === '') {
  4842. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  4843. } else {
  4844. this.filteredList = mSearchList.filter((item: VideoItem) => {
  4845. //支持模糊匹配和艺术家 专辑匹配
  4846. const regex = new RegExp(this.searchText.toLowerCase().replace(/\s+/g, '.*'), 'i');
  4847. return regex.test(item.name.toLowerCase())||
  4848. regex.test(item.fileName?.toLowerCase() ?? "") ||
  4849. regex.test(item.artist?.toLowerCase() ?? "") ||
  4850. regex.test(item.album?.toLowerCase() ?? "")
  4851. });
  4852. }
  4853. this.updateListData(this.filteredList);
  4854. // this.isSearchMode = false; // 根据业务需求决定是否启用
  4855. }
  4856. @State dragItem: number = -1
  4857. @State scaleItem: number = -1
  4858. @State neighborItem: number = -1
  4859. @State neighborScale: number = -1
  4860. @State offsetY: number = 0
  4861. private dragRefOffset: number = 0
  4862. private ITEM_INTV: number = 78
  4863. scaleSelect(item: number): number {
  4864. if (this.scaleItem === item) {
  4865. return 1.05
  4866. } else if (this.neighborItem === item) {
  4867. return this.neighborScale
  4868. } else {
  4869. return 1
  4870. }
  4871. }
  4872. itemMove(index: number, newIndex: number): void {
  4873. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  4874. return;
  4875. }
  4876. let tmp = this.videoLocalList.splice(index, 1);
  4877. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  4878. this.dataSource.pushArrayData(this.videoLocalList)
  4879. if(this.modeType==4&&this.playlistTable){
  4880. updateAllSongsSortOrder(this.playlistTable, this.videoLocalList,this.currentSongListID)
  4881. }
  4882. }
  4883. //瀑布流布局 支持双指缩放
  4884. @State columns: number = 2;
  4885. @State waterFlowScale: number = 1;
  4886. @State imageScale: number = 1;
  4887. @State waterFlowOpacity: number = 1;
  4888. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  4889. private columnChanged: boolean = false;
  4890. private oldColumn: number = this.columns;
  4891. private pinchTime: number = 0;
  4892. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  4893. changeColumns(scale: number) {
  4894. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  4895. this.columns--;
  4896. this.columnChanged = true;
  4897. } else if (scale < 1 && this.columns < 4) {
  4898. this.columns++;
  4899. this.columnChanged = true;
  4900. }
  4901. }
  4902. @Builder
  4903. getWaterView(){
  4904. Scroll(this.scroller) {
  4905. Column() {
  4906. Blank().height(this.topSafeHeight + 55)
  4907. WaterFlow({
  4908. scroller:this.waterScroller,
  4909. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  4910. }) {
  4911. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  4912. FlowItem() {
  4913. this.MusicWaterCardItem(item,index)
  4914. }
  4915. .width('100%')
  4916. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  4917. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  4918. {
  4919. preview: MenuPreviewMode.IMAGE,
  4920. previewAnimationOptions: { scale: [0.8, 1.0] },
  4921. })
  4922. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  4923. {
  4924. preview: MenuPreviewMode.IMAGE,
  4925. previewAnimationOptions: { scale: [0.8, 1.0] },
  4926. })
  4927. .transition(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }))
  4928. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  4929. TransitionEffect.scale({ x: 0, y: 0 })))
  4930. .gesture(
  4931. GestureGroup(GestureMode.Exclusive,
  4932. SwipeGesture({ direction: SwipeDirection.Horizontal })
  4933. .onAction((event: GestureEvent) => {
  4934. if (event) {
  4935. // this.sideBarController.openSideBar()
  4936. }
  4937. }),
  4938. TapGesture({ count: 1, fingers: 1 })
  4939. .onAction(async () => {
  4940. })
  4941. )
  4942. )
  4943. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  4944. }
  4945. // .columnsTemplate('repeat(auto-fit, 160)')
  4946. .id('waterflow') // 设置id用于截图
  4947. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  4948. .columnsGap(12) // 列间距
  4949. .rowsGap(16) // 行间距
  4950. .cachedCount(6)
  4951. .padding({bottom:this.bottomBarHeight+10})
  4952. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4953. .animation({ duration: 500, curve: Curve.Ease }))
  4954. .scrollBar(BarState.Off)
  4955. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  4956. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  4957. .edgeEffect(EdgeEffect.Spring, { alwaysEnabled: true })
  4958. .width('90%')
  4959. .height('100%')
  4960. .opacity(this.waterFlowOpacity)
  4961. .scale({
  4962. x: this.waterFlowScale,
  4963. y: this.waterFlowScale,
  4964. centerX: 0,
  4965. centerY: 0
  4966. })
  4967. .onAppear(() => {
  4968. this.scroller.scrollEdge(Edge.Top)
  4969. })
  4970. .nestedScroll({
  4971. scrollForward: NestedScrollMode.PARENT_FIRST,
  4972. scrollBackward: NestedScrollMode.SELF_FIRST
  4973. })
  4974. .priorityGesture(
  4975. PinchGesture()
  4976. .onActionStart((event: GestureEvent) => {
  4977. // 双指捏合手势识别成功时截图
  4978. this.pinchTime = event.timestamp;
  4979. this.columnChanged = false;
  4980. this.oldColumn = this.columns;
  4981. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  4982. if (error) {
  4983. console.info('error:' + JSON.stringify(error));
  4984. return;
  4985. }
  4986. this.waterFlowSnapshot = pixmap;
  4987. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  4988. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  4989. if (this.oldColumn ===4) {
  4990. this.twoFingerType =3
  4991. this.isGridMusic = true
  4992. }else if (this.oldColumn ===1) {
  4993. this.twoFingerType =1
  4994. this.isGridMusic = false
  4995. }
  4996. return;
  4997. }
  4998. })
  4999. })
  5000. .onActionUpdate((event: GestureEvent) => {
  5001. // 手势更新:处理缩放逻辑和视觉效果
  5002. // 边界限制:防止超出列数范围时继续缩放
  5003. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  5004. return;
  5005. }
  5006. // 节流处理:避免过于频繁的更新,提升性能
  5007. if (event.timestamp - this.pinchTime < 10000000) {
  5008. return;
  5009. }
  5010. this.pinchTime = event.timestamp;
  5011. this.waterFlowScale = event.scale;
  5012. this.imageScale = event.scale;
  5013. // 根据缩放比例设置WaterFlow透明度
  5014. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  5015. this.waterFlowOpacity *= 3;
  5016. if (!this.columnChanged) {
  5017. this.changeColumns(event.scale);
  5018. }
  5019. // 列数改变后的缩放比例调整:避免出现空白区域
  5020. if (this.columnChanged) {
  5021. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  5022. // 限制缩放范围,确保视觉效果自然
  5023. if (event.scale < 1) {
  5024. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  5025. } else {
  5026. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  5027. }
  5028. }
  5029. })
  5030. .onActionEnd((event: GestureEvent) => {
  5031. // 手势结束:执行归位动画并保存状态
  5032. // 执行归位动画:平滑过渡到正常状态
  5033. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  5034. this.waterFlowScale = 1;
  5035. this.waterFlowOpacity = 1;
  5036. })
  5037. // 持久化保存当前列数:下次启动时恢复
  5038. PreferencesUtil.putSync('lastColumns', this.columns);
  5039. })
  5040. )
  5041. .onScrollFrameBegin((offset: number) => {
  5042. // 获取当前滚动偏移量
  5043. if(this.autoHideTitle){
  5044. const currentOffsetY = this.waterScroller.currentOffset().yOffset;
  5045. // 判断滚动方向
  5046. if (currentOffsetY > this.prevOffsetY) {
  5047. console.log("onecold 向上滚动");
  5048. this.isShowTitleBar = false
  5049. } else if (currentOffsetY < this.prevOffsetY) {
  5050. console.log("onecold 向下滚动");
  5051. this.isShowTitleBar = true
  5052. }
  5053. // 更新前一次偏移量
  5054. this.prevOffsetY = currentOffsetY;
  5055. }
  5056. return { offsetRemain: offset };
  5057. })
  5058. }
  5059. }
  5060. .scrollBar(BarState.Off)
  5061. }
  5062. //瀑布流卡片布局
  5063. @Builder
  5064. private MusicWaterCardItem(item: VideoItem, index: number) {
  5065. Button({ type: ButtonType.Normal, stateEffect: false }) {
  5066. Stack() {
  5067. Column() {
  5068. Image(item.pixelMapPath)
  5069. .backgroundImageSize(ImageSize.Auto)
  5070. .borderRadius({
  5071. topLeft: 12,
  5072. topRight : 12,
  5073. bottomLeft: 0,
  5074. bottomRight: 0
  5075. })
  5076. .draggable(false)// 禁止长按手势拖动
  5077. .autoResize(true) // 重采样,可减少内存占用
  5078. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  5079. .width('100%')
  5080. .height('auto')
  5081. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  5082. .objectFit(ImageFit.Auto)
  5083. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  5084. height: '99%' ,
  5085. dragBar: true,
  5086. onDisappear: () => {
  5087. this.longItemFilePath = '';
  5088. this.tempLyricContent = ''
  5089. },
  5090. showClose: true,
  5091. preferType: SheetType.CENTER ,
  5092. title: { title: '编辑标签' }
  5093. })
  5094. .draggable(false)
  5095. .opacity(this.opacityItem)// 绑定透明度
  5096. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  5097. // .animation({ duration: 500, curve: Curve.Ease }))
  5098. .animation({
  5099. duration: 666,
  5100. curve: 'ease-in-out' // 可选动画曲线
  5101. })
  5102. .margin({
  5103. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5104. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5105. })
  5106. Column() {
  5107. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5108. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  5109. .maxLines(1)
  5110. .fontWeight(FontWeight.Bold)
  5111. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5112. .animation({
  5113. duration: 555,
  5114. curve: 'Linear',
  5115. })
  5116. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  5117. height: '95%',
  5118. dragBar: true,
  5119. showClose: true,
  5120. onDisappear: () => {
  5121. this.longItemFilePathDetail = '';
  5122. },
  5123. blurStyle:BlurStyle.Thin,
  5124. backgroundColor:Color.Transparent,
  5125. preferType: SheetType.CENTER ,
  5126. title: { title: '详情' }
  5127. })
  5128. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5129. $r('app.color.text_color'))
  5130. Column() {
  5131. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  5132. .fontSize(11)
  5133. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  5134. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5135. .fontColor($r('app.color.text_color'))
  5136. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  5137. .fontSize(11)
  5138. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  5139. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5140. .fontColor($r('app.color.text_color'))
  5141. Row(){
  5142. Column(){
  5143. Text(item.md5Str?.includes('Lossless')?
  5144. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5145. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  5146. .padding({ top: 3,right:6,left:6,bottom:3 })
  5147. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5148. $r('app.color.text_color'))
  5149. .fontWeight(500)
  5150. .borderRadius(12)
  5151. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5152. .backgroundColor('#FFC107')
  5153. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  5154. }
  5155. .margin({ top: 2 ,right:6})
  5156. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  5157. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  5158. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  5159. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  5160. .maxLines(1)
  5161. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5162. .margin({ top: 2})
  5163. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  5164. || item.type == CommonConstants.TYPE_IS_ALBUM
  5165. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5166. .fontWeight(FontWeight.Medium)
  5167. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5168. $r('app.color.text_color'))
  5169. }
  5170. }
  5171. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  5172. }
  5173. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  5174. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  5175. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  5176. .width('100%')
  5177. .justifyContent(FlexAlign.Center)
  5178. .margin({
  5179. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5180. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5181. })
  5182. }
  5183. .width('100%')
  5184. .borderRadius(12)
  5185. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  5186. .backgroundImageSize({ height: '100%', width: '100%' })
  5187. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  5188. .animation({ curve: Curve.Sharp, duration: 300 })
  5189. Checkbox({ name: 'checkbox' + index })
  5190. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  5191. .selectedColor(this.themeColor)
  5192. .shape(CheckBoxShape.CIRCLE)
  5193. .opacity(this.isMultiSelect ? 1 : 0)
  5194. .animation({
  5195. duration: 666,
  5196. curve: 'Smooth' // 可选动画曲线
  5197. })
  5198. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  5199. Visibility.None)
  5200. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5201. .margin({ left: 20, top: 8, bottom: 8 })
  5202. .width(38)
  5203. .height(38)
  5204. }
  5205. }
  5206. .backgroundColor(Color.Transparent)
  5207. .width('100%')
  5208. .height('auto')
  5209. .padding({top:2})
  5210. .shadow({
  5211. radius: 10,
  5212. type: ShadowType.BLUR,
  5213. color: 'on_primary'
  5214. })
  5215. .reuseId('card_item')
  5216. .onClick(() => {
  5217. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5218. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5219. this.handleFileSelection(item, !isChecked);
  5220. } else {
  5221. this.doPlay(item, index)
  5222. }
  5223. })
  5224. }
  5225. // Grid布局的开始
  5226. private dragRefOffSetX: number = 0;
  5227. private dragRefOffSetY: number = 0;
  5228. private FIX_VP_X: number = 180;
  5229. private FIX_VP_Y: number = 84;
  5230. isDraggable(index: number): boolean {
  5231. return index >= 0;
  5232. }
  5233. getRowEnd(item: number) {
  5234. if (item.toString() === '0') {
  5235. return 1;
  5236. } else {
  5237. return 0;
  5238. }
  5239. }
  5240. isInLeft(index: number) {
  5241. return index % 2 == 0;
  5242. }
  5243. down(index: number): void {
  5244. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  5245. return;
  5246. }
  5247. this.offsetY -= this.FIX_VP_Y;
  5248. this.dragRefOffSetY += this.FIX_VP_Y;
  5249. this.itemMove(index, index + 1);
  5250. }
  5251. up(index: number): void {
  5252. if (!this.isDraggable(index - 2)) {
  5253. return;
  5254. }
  5255. this.offsetY += this.FIX_VP_Y;
  5256. this.dragRefOffSetY -= this.FIX_VP_Y;
  5257. this.itemMove(index, index - 1);
  5258. }
  5259. left(index: number): void {
  5260. if (this.isInLeft(index)) {
  5261. return;
  5262. }
  5263. if (!this.isDraggable(index - 1)) {
  5264. return;
  5265. }
  5266. this.offsetX += this.FIX_VP_X;
  5267. this.dragRefOffSetX -= this.FIX_VP_X;
  5268. this.itemMove(index, index - 1)
  5269. }
  5270. right(index: number): void {
  5271. if (!this.isInLeft(index)) {
  5272. return;
  5273. }
  5274. if (!this.isDraggable(index + 1)) {
  5275. return;
  5276. }
  5277. this.offsetX -= this.FIX_VP_X;
  5278. this.dragRefOffSetX += this.FIX_VP_X;
  5279. this.itemMove(index, index + 1)
  5280. }
  5281. private scroller: Scroller = new Scroller();
  5282. private waterScroller: Scroller = new Scroller();
  5283. @State startIndex: number = 0
  5284. @State endIndex: number = 0
  5285. @State scaleValue: number = 1
  5286. @State pinchValue: number = 1
  5287. layoutOptionsForHeader: GridLayoutOptions = {
  5288. regularSize: [1, 1], // 只支持[1, 1]
  5289. irregularIndexes: [0], // 索引为0的GridItem占用一行
  5290. };
  5291. @Builder
  5292. getGridView() {
  5293. Grid(this.scroller, this.layoutOptionsForHeader) {
  5294. GridItem() {
  5295. Column(){
  5296. Blank().height(this.topSafeHeight + 45)
  5297. }
  5298. }
  5299. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5300. GridItem() {
  5301. Stack({ alignContent: Alignment.Center }) {
  5302. this.MusicItemGrid(item, index)
  5303. }
  5304. }
  5305. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  5306. {
  5307. preview: MenuPreviewMode.IMAGE,
  5308. previewAnimationOptions: { scale: [0.8, 1.0] },
  5309. })
  5310. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  5311. {
  5312. preview: MenuPreviewMode.IMAGE,
  5313. previewAnimationOptions: { scale: [0.8, 1.0] },
  5314. })
  5315. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  5316. TransitionEffect.scale({ x: 0, y: 0 })))
  5317. .clickEffect({ level: ClickEffectLevel.LIGHT })
  5318. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  5319. .zIndex(this.dragItem === index ? 1 : 0)
  5320. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  5321. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5322. }
  5323. .width('94%')
  5324. .height('100%')
  5325. .editMode(true)
  5326. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  5327. .animation({ duration: 500, curve: Curve.Ease }))
  5328. .padding({bottom:this.bottomBarHeight+this.bottomSafeHeight+10})
  5329. .reuseId('grid_item')
  5330. .layoutWeight(1)
  5331. .scrollBar(BarState.Off)
  5332. .supportAnimation(true)
  5333. .cachedCount(this.twoFingerType==1?5:this.twoFingerType==2?4:3)
  5334. .columnsTemplate(
  5335. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  5336. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  5337. )
  5338. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  5339. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  5340. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5341. .gesture(PinchGesture({ fingers: 2 })
  5342. .onActionEnd((event: GestureEvent) => {
  5343. this.setGridTwoFingers()
  5344. })
  5345. .onActionUpdate(e => {
  5346. this.scaleValue = this.pinchValue * e.scale
  5347. })
  5348. .onActionStart(e => {
  5349. }))
  5350. .enableScrollInteraction(true)
  5351. .onScrollIndex((start: number, end: number) => {
  5352. this.startIndex = start
  5353. this.endIndex = end
  5354. })
  5355. .onScrollFrameBegin((offset: number) => {
  5356. if(this.autoHideTitle){
  5357. const currentOffsetY = this.scroller.currentOffset().yOffset;
  5358. // 判断滚动方向
  5359. if (currentOffsetY > this.prevOffsetY) {
  5360. console.log("onecold 向上滚动");
  5361. this.isShowTitleBar = false
  5362. } else if (currentOffsetY < this.prevOffsetY) {
  5363. console.log("onecold 向下滚动");
  5364. this.isShowTitleBar = true
  5365. }
  5366. // 更新前一次偏移量
  5367. this.prevOffsetY = currentOffsetY;
  5368. }
  5369. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  5370. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  5371. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  5372. if (this.isScrollHide) {
  5373. this.setBarHeightHide2(offset)
  5374. } else {
  5375. this.setBarHeightNormal()
  5376. }
  5377. } else {
  5378. this.setBarHeightHide(offset)
  5379. }
  5380. return { offsetRemain: offset };
  5381. })
  5382. }
  5383. @State targetFile: string = '';
  5384. setGridTwoFingers() {
  5385. this.pinchValue = this.scaleValue;
  5386. Logger.info('this.pinchValue = ' + this.pinchValue);
  5387. if (this.pinchValue >= 1) {
  5388. this.twoFingerType++
  5389. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  5390. if(this.twoFingerType >= 4){
  5391. this.twoFingerType = 4//切换成瀑布流
  5392. this.columns = 4
  5393. }
  5394. } else {
  5395. this.twoFingerType--
  5396. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  5397. if (this.twoFingerType < 1) {
  5398. this.twoFingerType = 3
  5399. this.isGridMusic = false
  5400. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5401. }
  5402. }
  5403. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5404. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5405. this.pinchValue = 1;
  5406. this.scaleValue = 1;
  5407. }
  5408. @State longItemFilePath: string = ''
  5409. @State tempLyricContent: string = ''
  5410. @State editingItem: VideoItem | null = null
  5411. @Builder
  5412. private MusicItemGrid(item: VideoItem, index: number) {
  5413. Button({ type: ButtonType.Normal, stateEffect: false }) {
  5414. Stack() {
  5415. Column() {
  5416. Image(item.pixelMapPath)
  5417. .height(this.getGridHeight())
  5418. .width(this.getGridWight())
  5419. .draggable(false)
  5420. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  5421. .autoResize(true) // 重采样,可减少内存占用
  5422. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  5423. .clip(true)
  5424. .borderRadius({
  5425. topLeft: 12,
  5426. topRight: 12,
  5427. bottomLeft: 0,
  5428. bottomRight: 0
  5429. })
  5430. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  5431. height: '99%' ,
  5432. dragBar: true,
  5433. onDisappear: () => {
  5434. this.longItemFilePath = '';
  5435. this.tempLyricContent = ''
  5436. },
  5437. showClose: true,
  5438. preferType: SheetType.CENTER ,
  5439. title: { title: '编辑标签' }
  5440. })
  5441. .draggable(false)
  5442. .opacity(this.opacityItem)// 绑定透明度
  5443. .animation({
  5444. duration: 666,
  5445. curve: 'ease-in-out' // 可选动画曲线
  5446. })
  5447. .margin({
  5448. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5449. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5450. })
  5451. Column() {
  5452. Text(this.isShowFileName&&item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5453. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5454. .maxLines(1)
  5455. .fontWeight(FontWeight.Bold)
  5456. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5457. .animation({
  5458. duration: 555,
  5459. curve: 'Linear',
  5460. })
  5461. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  5462. height: '95%',
  5463. dragBar: true,
  5464. showClose: true,
  5465. onDisappear: () => {
  5466. this.longItemFilePathDetail = '';
  5467. },
  5468. blurStyle:BlurStyle.Thin,
  5469. backgroundColor:Color.Transparent,
  5470. preferType: SheetType.CENTER ,
  5471. title: { title: '详情' }
  5472. })
  5473. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5474. $r('app.color.text_color'))
  5475. Column() {
  5476. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  5477. .fontSize(11)
  5478. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  5479. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5480. .fontColor($r('app.color.text_color'))
  5481. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  5482. .fontSize(11)
  5483. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  5484. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5485. .fontColor($r('app.color.text_color'))
  5486. Row(){
  5487. Column(){
  5488. Text(item.md5Str?.includes('Lossless')?
  5489. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5490. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5491. .padding({ top: 3,right:6,left:6,bottom:3 })
  5492. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5493. $r('app.color.text_color'))
  5494. .fontWeight(500)
  5495. .borderRadius(12)
  5496. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5497. .backgroundColor('#FFC107')
  5498. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  5499. }
  5500. .margin({ top: 2 ,right:6})
  5501. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  5502. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  5503. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  5504. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  5505. .maxLines(1)
  5506. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5507. .margin({ top: 2})
  5508. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  5509. || item.type == CommonConstants.TYPE_IS_ALBUM
  5510. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5511. .fontWeight(FontWeight.Medium)
  5512. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5513. $r('app.color.text_color'))
  5514. }
  5515. }
  5516. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  5517. }
  5518. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  5519. .width(this.getGridWight())
  5520. .justifyContent(FlexAlign.Center)
  5521. .margin({
  5522. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5523. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5524. })
  5525. }
  5526. .width(this.getGridWight())
  5527. .borderRadius(12)
  5528. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?$r('app.media.alt'):item.pixelMapPath)
  5529. .backgroundImageSize({ height: '100%', width: '100%' })
  5530. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  5531. .animation({ curve: Curve.Sharp, duration: 300 })
  5532. Checkbox({ name: 'checkbox' + index })
  5533. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  5534. .selectedColor(this.themeColor)
  5535. .shape(CheckBoxShape.CIRCLE)
  5536. .opacity(this.isMultiSelect ? 1 : 0)
  5537. .animation({
  5538. duration: 666,
  5539. curve: 'Smooth' // 可选动画曲线
  5540. })
  5541. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  5542. Visibility.None)
  5543. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5544. .margin({ left: 20, top: 8, bottom: 8 })
  5545. .width(38)
  5546. .height(38)
  5547. }
  5548. }
  5549. .backgroundColor(Color.Transparent)
  5550. .width('100%')
  5551. .padding({ top: 15 })
  5552. .height(this.getGridAllHeight())
  5553. .onClick(() => {
  5554. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5555. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5556. this.handleFileSelection(item, !isChecked);
  5557. } else {
  5558. this.doPlay(item, index)
  5559. }
  5560. })
  5561. }
  5562. getGridAllHeight() {
  5563. let heightG = 222
  5564. switch (this.twoFingerType) {
  5565. case 1:
  5566. heightG = 143
  5567. break;
  5568. case 2:
  5569. heightG = 178
  5570. break;
  5571. case 3:
  5572. heightG = 222
  5573. break;
  5574. }
  5575. return heightG
  5576. }
  5577. getGridHeight() {
  5578. let heightG = 150
  5579. switch (this.twoFingerType) {
  5580. case 1:
  5581. heightG = 80
  5582. break;
  5583. case 2:
  5584. heightG = 110
  5585. break;
  5586. case 3:
  5587. heightG = 150
  5588. break;
  5589. }
  5590. return heightG
  5591. }
  5592. getGridWight() {
  5593. let wightG = 158
  5594. switch (this.twoFingerType) {
  5595. case 1:
  5596. wightG = 80
  5597. break;
  5598. case 2:
  5599. wightG = 110
  5600. break;
  5601. case 3:
  5602. wightG = 158
  5603. break;
  5604. }
  5605. return wightG
  5606. }
  5607. @State isShowDetail:boolean = false
  5608. @State longItemFilePathDetail:string =''
  5609. @Builder
  5610. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  5611. if(
  5612. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  5613. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5614. item.name === LocalMusic.STR_HISTORY_MUSIC)
  5615. ){
  5616. //如果是专辑和艺术家的首页,不能长按
  5617. //如果是我的收藏 最近播放等也不能长按
  5618. }else{
  5619. Scroll() {
  5620. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  5621. Menu() {
  5622. MenuItem({
  5623. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  5624. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  5625. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  5626. })
  5627. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5628. .onClick(() => {
  5629. if (item) {
  5630. this.doFav(item)
  5631. }
  5632. this.longItemFilePath = ''
  5633. })
  5634. MenuItem({
  5635. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  5636. content: '下一首播放'
  5637. })
  5638. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5639. .onClick(() => {
  5640. this.addToNextPlay(item);
  5641. this.longItemFilePath = ''
  5642. })
  5643. MenuItem({
  5644. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  5645. content: '添加到歌单'
  5646. })
  5647. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5648. .onClick(async () => {
  5649. this.longItemFilePath = ''
  5650. await this.openAddToPlaylistDialog(item)
  5651. })
  5652. MenuItem({
  5653. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  5654. content: '编辑标签'
  5655. })
  5656. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  5657. height: '99%',
  5658. dragBar: true,
  5659. showClose: true,
  5660. preferType: SheetType.CENTER ,
  5661. title: { title: '编辑标签' }
  5662. })
  5663. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5664. .onClick(async() => {
  5665. this.initEditFields(item)
  5666. this.tempLyricContent = await this.getLyricContent(item);
  5667. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  5668. this.lyricConStr = this.tempLyricContent
  5669. }
  5670. if(this.isGridMusic||this.twoFingerType==4){
  5671. this.longItemFilePath = item.filePath
  5672. }else{
  5673. this.isShowEdit = !this.isShowEdit;
  5674. }
  5675. })
  5676. MenuItem({
  5677. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  5678. content: $r('app.string.select_all')
  5679. })
  5680. .onClick(() => {
  5681. this.isMultiSelect = !this.isMultiSelect
  5682. this.longItemFilePath = ''
  5683. this.selectedFiles.push(item)
  5684. })
  5685. MenuItem({
  5686. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.cut')),
  5687. content: $r('app.string.edit_audio')
  5688. })
  5689. .bindContentCover($$this.isEditAudio, this.EditAudioBuilder(item), {
  5690. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5691. })
  5692. .onClick(() => {
  5693. this.isEditAudio = !this.isEditAudio
  5694. })
  5695. MenuItem({
  5696. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  5697. content: $r('app.string.extract_accompaniment')
  5698. })
  5699. .bindContentCover($$this.isExtractAcc, this.ExtractAccBuilder(item), {
  5700. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5701. })
  5702. .onClick(() => {
  5703. if (!Utility.isNoble()) {
  5704. this.showVipDialog()
  5705. return
  5706. }
  5707. this.isExtractAcc = !this.isExtractAcc
  5708. })
  5709. MenuItem({
  5710. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.repeat')),
  5711. content: $r('app.string.converter_audio')
  5712. })
  5713. .bindContentCover($$this.isConverter, this.ConverterBuilder(item), {
  5714. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5715. })
  5716. .onClick(() => {
  5717. if (!Utility.isNoble()) {
  5718. this.showVipDialog()
  5719. return
  5720. }
  5721. this.isConverter = !this.isConverter
  5722. })
  5723. MenuItem({
  5724. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.ai_edit')),
  5725. content: $r('app.string.vocal_separation')
  5726. })
  5727. .bindContentCover($$this.isAIVoiceSeparation, this.AiBuilder(item), {
  5728. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5729. })
  5730. .onClick(() => {
  5731. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  5732. })
  5733. MenuItem({
  5734. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_counterclockwise_clock')),
  5735. content: $r('app.string.change_tone')
  5736. })
  5737. .bindContentCover($$this.isChangeTone, this.ChangeToneBuilder(item), {
  5738. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5739. })
  5740. .onClick(() => {
  5741. this.isChangeTone = !this.isChangeTone
  5742. })
  5743. if(Utility.isVideoByExtension(item.filePath)){
  5744. MenuItem({
  5745. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.identify_song')),
  5746. content: $r('app.string.extract_audio')
  5747. })
  5748. .bindContentCover($$this.isExtractAudio, this.extractAudioFromVideoBuilder(item), {
  5749. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5750. })
  5751. .onClick(() => {
  5752. this.isExtractAudio = !this.isExtractAudio
  5753. })
  5754. }
  5755. MenuItem({
  5756. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.phone')),
  5757. content: $r('app.string.set_ring')
  5758. })
  5759. .onClick(async () => {
  5760. await PermissionUtil.activatePermission(item.filePath)
  5761. // if(item.filePath.includes(this.packName)){
  5762. setRingTone(this.context, item.filePath,item.name)
  5763. // }else{
  5764. // ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限设置铃声')
  5765. // }
  5766. this.longItemFilePath = ''
  5767. })
  5768. MenuItem({
  5769. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  5770. content: $r('app.string.rename')
  5771. })
  5772. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  5773. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5774. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  5775. .onClick(() => {
  5776. this.showReNameDialog(item, index + '', filePath)
  5777. this.longItemFilePath = ''
  5778. })
  5779. MenuItem({
  5780. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  5781. content: $r('app.string.delete')
  5782. })
  5783. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  5784. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5785. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  5786. .onClick(() => {
  5787. this.selectedFiles.push(item)
  5788. this.showWarnIsDelete()
  5789. this.longItemFilePath = ''
  5790. })
  5791. MenuItem({
  5792. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  5793. content: $r('app.string.detail')
  5794. })
  5795. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  5796. height:'95%',
  5797. dragBar: true,
  5798. showClose: true,
  5799. blurStyle:BlurStyle.Thin,
  5800. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  5801. backgroundColor:Color.Transparent,
  5802. title: { title: '详情信息' }
  5803. })
  5804. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5805. .onClick(() => {
  5806. if(this.isGridMusic||this.twoFingerType==4){
  5807. this.longItemFilePathDetail = item.filePath
  5808. }else{
  5809. this.isShowDetail = !this.isShowDetail
  5810. }
  5811. })
  5812. MenuItem({
  5813. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  5814. content: $r('app.string.share')
  5815. })
  5816. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5817. .onClick(() => {
  5818. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  5819. this.longItemFilePath = ''
  5820. })
  5821. }
  5822. .font({ size: 14, weight: FontWeight.Normal })
  5823. }
  5824. .width(180)
  5825. }
  5826. .height('auto')
  5827. .enableScrollInteraction(true)
  5828. .scrollBar(this.isGridMusic?BarState.On:BarState.Off)
  5829. }
  5830. }
  5831. private listMaxScrollOffsetY: number = 0
  5832. @State selectedIndex: number = -1
  5833. setlistTwoFingers() {
  5834. this.pinchValue = this.scaleValue;
  5835. Logger.info('this.pinchValue = ' + this.pinchValue);
  5836. if (this.pinchValue >= 1) {
  5837. this.twoFingerType++
  5838. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  5839. if (this.twoFingerType > 3) {
  5840. this.twoFingerType = 1
  5841. this.isGridMusic = true
  5842. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5843. }
  5844. } else {
  5845. this.twoFingerType--
  5846. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  5847. if (this.twoFingerType < 1) {
  5848. this.twoFingerType = 4
  5849. this.columns = 1
  5850. }
  5851. }
  5852. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5853. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5854. this.pinchValue = 1;
  5855. this.scaleValue = 1;
  5856. }
  5857. @Builder
  5858. getList(){
  5859. Stack() {
  5860. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  5861. this.getListView()
  5862. }
  5863. .pullDownRatio(this.ratioL)
  5864. .pullToRefresh(true)
  5865. .refreshOffset(0)
  5866. .onOffsetChange((offset: number) => {
  5867. // 越接近最大距离,下拉跟手系数越小。
  5868. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  5869. })
  5870. .onStateChange((refreshStatus: RefreshStatus) => {
  5871. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  5872. })
  5873. .onRefreshing(async () => {
  5874. if(this.modeType==0){
  5875. this.getHistoryList(false)
  5876. this.asyncCurrentPathOnlyFile()
  5877. }else if(this.modeType == 1){
  5878. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  5879. }else if(this.modeType == 2){
  5880. workerInstance.postMessage({ code: 3, data: this.context });
  5881. }else if(this.modeType == 3){
  5882. workerInstance.postMessage({ code: 4, data: this.context });
  5883. }else if(this.modeType == 4){
  5884. this.doSongListTask()
  5885. }
  5886. console.log('onRefreshing test');
  5887. })
  5888. }
  5889. }
  5890. // 扫描当前目录下的文件,不扫描子目录
  5891. asyncCurrentPathOnlyFile(){
  5892. if(this.modeType==0){
  5893. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  5894. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  5895. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  5896. if(this.modeType==0){
  5897. setTimeout(()=>{
  5898. this.isRefreshing =false
  5899. this.deleteCache(this.currentPath)
  5900. this.getSortedFiles(this.currentPath)
  5901. },500)
  5902. }
  5903. }).catch((e:object)=>{
  5904. this.isRefreshing =false
  5905. console.info("onecold task1 catch e: " + e);
  5906. })
  5907. }
  5908. }
  5909. @Builder
  5910. getListView() {
  5911. List({ scroller: this.listScroller }) {
  5912. // ListItemGroup({ header: this.coverHeader() }) {
  5913. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5914. ListItem() {
  5915. Column() {
  5916. if (item.type === CommonConstants.TYPE_IS_DIR
  5917. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  5918. this.DirItem(item, index)
  5919. } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
  5920. } else {
  5921. this.MusicItem(item, index)
  5922. }
  5923. }
  5924. .shadow(this.scaleItem === index ? {
  5925. radius: 70,
  5926. color: '#15000000',
  5927. offsetX: 0,
  5928. offsetY: 0
  5929. } :
  5930. {
  5931. radius: 0,
  5932. color: '#15000000',
  5933. offsetX: 0,
  5934. offsetY: 0
  5935. })
  5936. .animation({ curve: Curve.Sharp, duration: 300 })
  5937. }
  5938. // .transition(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }))
  5939. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.9, y: 0.9 })
  5940. .animation({ duration: 500 }),
  5941. TransitionEffect.scale({ x: 0, y: 0 })))
  5942. .clickEffect({ level: ClickEffectLevel.LIGHT })
  5943. .swipeAction((
  5944. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  5945. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  5946. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  5947. start:null,edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  5948. .onClick(() => {
  5949. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5950. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5951. this.handleFileSelection(item, !isChecked);
  5952. } else {
  5953. this.doPlay(item, index)
  5954. }
  5955. })
  5956. //拖动List关键代码开始
  5957. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  5958. .zIndex(this.dragItem === index ? 1 : 0)
  5959. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  5960. .gesture(
  5961. GestureGroup(GestureMode.Sequence,
  5962. LongPressGesture({ repeat: true })
  5963. .onAction((event?: GestureEvent) => {
  5964. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5965. this.scaleItem = index
  5966. })
  5967. })
  5968. .onActionEnd(() => {
  5969. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5970. this.scaleItem = -1
  5971. })
  5972. }),
  5973. PanGesture({ fingers: 1, direction: null, distance: 0 })
  5974. .onActionStart(() => {
  5975. this.dragItem = index // 记录当前拖动项索引
  5976. this.dragRefOffset = 0 // 重置偏移基准
  5977. })
  5978. .onActionUpdate((event: GestureEvent) => {
  5979. this.offsetY = event.offsetY - this.dragRefOffset;
  5980. this.neighborItem = -1;
  5981. let indexA = this.videoLocalList.indexOf(item);
  5982. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  5983. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  5984. let value: number = 0;
  5985. if (this.offsetY < 0) {
  5986. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  5987. this.neighborItem = indexA - 1;
  5988. this.neighborScale = 1 - value / 20;
  5989. } else if (this.offsetY > 0) {
  5990. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  5991. this.neighborItem = indexA + 1;
  5992. this.neighborScale = 1 - value / 20;
  5993. }
  5994. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  5995. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5996. this.offsetY -= this.ITEM_INTV;
  5997. this.dragRefOffset += this.ITEM_INTV;
  5998. this.itemMove(indexA, indexA + 1);
  5999. });
  6000. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  6001. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6002. this.offsetY += this.ITEM_INTV;
  6003. this.dragRefOffset -= this.ITEM_INTV;
  6004. this.itemMove(indexA, indexA - 1);
  6005. });
  6006. }
  6007. let curListOffset = this.listScroller.currentOffset()
  6008. // 获取手指信息
  6009. let fingerInfo = event.fingerList[0]
  6010. let clickPercentY =
  6011. (fingerInfo.globalY - Number(this.listArea.globalPosition.y)) / Number(this.listArea.height)
  6012. if (clickPercentY > 0.8 && !this.listScroller.isAtEnd()) {
  6013. let scrollVelocity = clickPercentY > 0.9 ? 4 : 2
  6014. if (this.listMaxScrollOffsetY - curListOffset.yOffset > scrollVelocity + 5) {
  6015. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset += scrollVelocity })
  6016. }
  6017. } else if (clickPercentY < 0.2 && curListOffset.yOffset >= 0) {
  6018. let scrollVelocity = clickPercentY < 0.1 ? 4 : 2
  6019. if (curListOffset.yOffset > scrollVelocity + 5) {
  6020. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset -= scrollVelocity })
  6021. }
  6022. }
  6023. })
  6024. .onActionEnd((event: GestureEvent) => {
  6025. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6026. this.dragItem = -1
  6027. this.neighborItem = -1
  6028. })
  6029. animateTo({
  6030. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  6031. }, () => {
  6032. this.scaleItem = -1
  6033. })
  6034. })
  6035. )
  6036. .onCancel(() => {
  6037. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6038. this.dragItem = -1
  6039. this.neighborItem = -1
  6040. })
  6041. animateTo({
  6042. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  6043. }, () => {
  6044. this.scaleItem = -1
  6045. })
  6046. })
  6047. ) //拖动List关键代码结束
  6048. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  6049. // }
  6050. }
  6051. .onScrollStart(() => {
  6052. this.isScrolling = true
  6053. this.isShowAlphaBet = true
  6054. })
  6055. .onScrollIndex((start: number,center:number,end:number) => {
  6056. this.selectedIndex = start
  6057. if(start >= 0 && start < this.videoLocalList.length){
  6058. this.selectAlphaBetIndex = this.findAlphaBetIndex(this.videoLocalList[start])
  6059. }
  6060. })
  6061. .onScrollStop(() => {
  6062. if(this.isScrolling){
  6063. this.isScrolling = false
  6064. }
  6065. this.isShowAlphaBet = false
  6066. })
  6067. .scrollBar(BarState.Off)
  6068. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  6069. .gesture(PinchGesture({ fingers: 2 })
  6070. .onActionEnd((event: GestureEvent) => {
  6071. this.setlistTwoFingers()
  6072. })
  6073. .onActionUpdate(e => {
  6074. this.scaleValue = this.pinchValue * e.scale
  6075. })
  6076. .onActionStart(e => {
  6077. }))
  6078. .contentStartOffset(this.topSafeHeight + 55)
  6079. .scrollBar(BarState.Off)
  6080. .contentEndOffset(this.bottomBarHeight+this.bottomSafeHeight)
  6081. .cachedCount(10)
  6082. // .reuseId('list_item')
  6083. .borderRadius(20)
  6084. .layoutWeight(1)
  6085. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  6086. .lanes(
  6087. new BreakpointType<number>({
  6088. sm: 1,
  6089. md: 2,
  6090. lg: 2,
  6091. xl: 3,
  6092. xxl: 4
  6093. }).getValue(this.currentBreakpoint),
  6094. new BreakpointType<number>({
  6095. sm: 0,
  6096. md: 12,
  6097. lg: 12,
  6098. xl: 16,
  6099. xxl: 20
  6100. }).getValue(this.currentBreakpoint)
  6101. )
  6102. .onAreaChange((oldValue: Area, newValue: Area) => {
  6103. this.listArea = newValue
  6104. if (this.twoFingerType == 3) {
  6105. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  6106. } else if (this.twoFingerType == 2) {
  6107. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  6108. } else if (this.twoFingerType == 1) {
  6109. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  6110. }
  6111. })
  6112. .onScrollFrameBegin((offset: number) => {
  6113. // 获取当前滚动偏移量
  6114. if(this.autoHideTitle){
  6115. const currentOffsetY = this.listScroller.currentOffset().yOffset;
  6116. // 判断滚动方向
  6117. if (currentOffsetY > this.prevOffsetY) {
  6118. console.log("onecold 向上滚动");
  6119. this.isShowTitleBar = false
  6120. } else if (currentOffsetY < this.prevOffsetY) {
  6121. console.log("onecold 向下滚动");
  6122. this.isShowTitleBar = true
  6123. }
  6124. // 更新前一次偏移量
  6125. this.prevOffsetY = currentOffsetY;
  6126. }
  6127. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  6128. // if (this.isPhoneLan()) {
  6129. // this.setBarHeightHide(offset)
  6130. // } else
  6131. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  6132. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  6133. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  6134. if (this.isScrollHide) {
  6135. this.setBarHeightHide2(offset)
  6136. } else {
  6137. this.setBarHeightNormal()
  6138. }
  6139. } else {
  6140. this.setBarHeightHide(offset)
  6141. }
  6142. return { offsetRemain: offset };
  6143. })
  6144. }
  6145. setBarHeightNormal() {
  6146. this.hideDone = false;
  6147. this.getUIContext().animateTo({
  6148. duration: 300
  6149. }, () => {
  6150. this.bottomBarHeight = 68 + 0;
  6151. this.topBarHeight = 50 + 0;
  6152. this.barOpacity = 1;
  6153. this.barBottomOpacity = 1
  6154. this.currentYOffset = 0;
  6155. this.isHiding = false;
  6156. });
  6157. }
  6158. setBarHeightHide(offset: number) {
  6159. if (offset > 0 && !this.hideDone) {
  6160. this.currentYOffset += offset;
  6161. if (this.currentYOffset <= 100) {
  6162. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  6163. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  6164. this.barOpacity = 1 - this.currentYOffset / 100;
  6165. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  6166. } else {
  6167. this.topBarHeight = 0;
  6168. this.bottomBarHeight = 0;
  6169. this.barBottomOpacity = 0
  6170. this.barOpacity = 0;
  6171. this.hideDone = true;
  6172. }
  6173. this.isHiding = true;
  6174. }
  6175. if (offset < 0 && this.isHiding) {
  6176. this.hideDone = false;
  6177. this.getUIContext().animateTo({
  6178. duration: 300
  6179. }, () => {
  6180. this.bottomBarHeight = 68 + 0;
  6181. this.topBarHeight = 50 + 0;
  6182. this.barOpacity = 1;
  6183. this.barBottomOpacity = 1
  6184. this.currentYOffset = 0;
  6185. this.isHiding = false;
  6186. });
  6187. }
  6188. }
  6189. //这个方法没隐藏bottomBar,只隐藏topbar
  6190. setBarHeightHide2(offset: number) {
  6191. if (offset > 0 && !this.hideDone) {
  6192. this.currentYOffset += offset;
  6193. if (this.currentYOffset <= 100) {
  6194. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  6195. this.barOpacity = 1 - this.currentYOffset / 100;
  6196. } else {
  6197. this.topBarHeight = 0;
  6198. this.barOpacity = 0;
  6199. this.hideDone = true;
  6200. }
  6201. this.isHiding = true;
  6202. }
  6203. if (offset < 0 && this.isHiding) {
  6204. this.hideDone = false;
  6205. this.getUIContext().animateTo({
  6206. duration: 300
  6207. }, () => {
  6208. this.topBarHeight = 50 + 0;
  6209. this.barOpacity = 1;
  6210. this.currentYOffset = 0;
  6211. this.isHiding = false;
  6212. });
  6213. }
  6214. }
  6215. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  6216. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  6217. switch (item.type) {
  6218. case CommonConstants.TYPE_IS_DIR:
  6219. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  6220. let offsetB = 0
  6221. if(this.twoFingerType==4){
  6222. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6223. let cur = this.waterScroller.currentOffset()
  6224. if (cur && typeof cur.yOffset === 'number') {
  6225. offsetB = cur.yOffset
  6226. }
  6227. }
  6228. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  6229. }else
  6230. if (this.isGridMusic) {
  6231. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6232. let cur = this.scroller.currentOffset()
  6233. if (cur && typeof cur.yOffset === 'number') {
  6234. offsetB = cur.yOffset
  6235. }
  6236. }
  6237. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  6238. } else {
  6239. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6240. let cur = this.listScroller.currentOffset()
  6241. if (cur && typeof cur.yOffset === 'number') {
  6242. offsetB = cur.yOffset
  6243. }
  6244. }
  6245. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  6246. }
  6247. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  6248. this.showVerifyDialog()
  6249. this.currentTitleName = '私密音频'
  6250. this.currentTitleCover = $r('app.media.alt')
  6251. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  6252. this.titleName = '最近播放'
  6253. this.currentTitleCover = $r('app.media.alt')
  6254. this.currentTitleName = '最近播放'
  6255. //加载动画效果
  6256. this.updateListData(this.historyList, true)
  6257. // this.videoLocalList = this.historyList
  6258. if (ArrayUtil.isEmpty(this.historyList)) {
  6259. ToastUtil.showToast('最近播放记录空空如也')
  6260. } else {
  6261. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  6262. }
  6263. this.isHistory = true
  6264. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  6265. this.titleName = '我的收藏'
  6266. this.currentTitleName = '我的收藏'
  6267. this.currentTitleCover = $r('app.media.alt')
  6268. //加载动画效果
  6269. this.updateListData(this.favList)
  6270. if (ArrayUtil.isEmpty(this.favList)) {
  6271. ToastUtil.showToast('无音乐收藏记录')
  6272. } else {
  6273. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  6274. }
  6275. this.isFavMusic = true
  6276. } else {
  6277. this.currentTitleName = item.name
  6278. this.currentPath = item.filePath
  6279. this.currentTitleCover = $r('app.media.alt')
  6280. this.getSortedFiles(this.currentPath)
  6281. }
  6282. //进入歌单的时候的滚动位置在顶部
  6283. if(this.twoFingerType==4){
  6284. setTimeout(() => {
  6285. this.waterScroller.scrollEdge(Edge.Top)
  6286. this.scroller.scrollEdge(Edge.Top)
  6287. }, 380)
  6288. }else{
  6289. if (this.isGridMusic) {
  6290. this.scroller.scrollEdge(Edge.Top)
  6291. }else{
  6292. this.listScroller.scrollEdge(Edge.Top)
  6293. }
  6294. }
  6295. this.rightTopImage = $r('sys.symbol.chevron_left')
  6296. break;
  6297. case CommonConstants.TYPE_IS_ARTIST:
  6298. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  6299. let offsetA = 0
  6300. if(this.twoFingerType==4){
  6301. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6302. let cur = this.waterScroller.currentOffset()
  6303. if (cur && typeof cur.yOffset === 'number') {
  6304. offsetA = cur.yOffset
  6305. }
  6306. }
  6307. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  6308. }else
  6309. if (this.isGridMusic) {
  6310. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6311. let cur = this.scroller.currentOffset()
  6312. if (cur && typeof cur.yOffset === 'number') {
  6313. offsetA = cur.yOffset
  6314. }
  6315. }
  6316. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  6317. } else {
  6318. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6319. let cur = this.listScroller.currentOffset()
  6320. if (cur && typeof cur.yOffset === 'number') {
  6321. offsetA = cur.yOffset
  6322. }
  6323. }
  6324. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  6325. }
  6326. let mList = this.artistMap.get(item.name)
  6327. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  6328. Utility.doSortListAscending(mList)
  6329. this.isCanBack = true
  6330. this.titleName = item.name
  6331. this.currentTitleName = '艺术家:' + item.name
  6332. if (item.pixelMapPath) {
  6333. this.currentTitleCover = item.pixelMapPath
  6334. }
  6335. this.updateListData(mList)
  6336. }
  6337. this.rightTopImage = $r('sys.symbol.chevron_left')
  6338. //进入歌单的时候的滚动位置在顶部
  6339. if(this.twoFingerType==4){
  6340. setTimeout(() => {
  6341. this.waterScroller.scrollEdge(Edge.Top)
  6342. this.scroller.scrollEdge(Edge.Top)
  6343. }, 380)
  6344. }else{
  6345. if (this.isGridMusic) {
  6346. this.scroller.scrollEdge(Edge.Top)
  6347. }else{
  6348. this.listScroller.scrollEdge(Edge.Top)
  6349. }
  6350. }
  6351. break;
  6352. case CommonConstants.TYPE_IS_ALBUM:
  6353. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  6354. let offset = 0
  6355. if(this.twoFingerType==4){
  6356. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6357. let cur = this.waterScroller.currentOffset()
  6358. if (cur && typeof cur.yOffset === 'number') {
  6359. offset = cur.yOffset
  6360. }
  6361. }
  6362. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  6363. }else
  6364. if (this.isGridMusic) {
  6365. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6366. let cur = this.scroller.currentOffset()
  6367. if (cur && typeof cur.yOffset === 'number') {
  6368. offset = cur.yOffset
  6369. }
  6370. }
  6371. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  6372. } else {
  6373. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6374. let cur = this.listScroller.currentOffset()
  6375. if (cur && typeof cur.yOffset === 'number') {
  6376. offset = cur.yOffset
  6377. }
  6378. }
  6379. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  6380. }
  6381. let albumList = this.albumMap.get(item.name)
  6382. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  6383. Utility.doSortListAscending(albumList)
  6384. this.isCanBack = true
  6385. this.titleName = item.name
  6386. this.currentTitleName = '专辑:' + item.name
  6387. if (item.pixelMapPath) {
  6388. this.currentTitleCover = item.pixelMapPath
  6389. }
  6390. this.updateListData(albumList)
  6391. this.mScrollMap.set(item.name, this.selectedIndex)
  6392. this.rightTopImage = $r('sys.symbol.chevron_left')
  6393. }
  6394. //进入歌单的时候的滚动位置在顶部
  6395. if(this.twoFingerType==4){
  6396. setTimeout(() => {
  6397. this.waterScroller.scrollEdge(Edge.Top)
  6398. this.scroller.scrollEdge(Edge.Top)
  6399. }, 380)
  6400. }else{
  6401. if (this.isGridMusic) {
  6402. this.scroller.scrollEdge(Edge.Top)
  6403. }else{
  6404. this.listScroller.scrollEdge(Edge.Top)
  6405. }
  6406. }
  6407. break;
  6408. case CommonConstants.TYPE_IS_CSJAD:
  6409. return
  6410. break;
  6411. case CommonConstants.TYPE_LOCAL:
  6412. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  6413. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  6414. const cueTracks:CueTrack[] = cueinfo.tracks
  6415. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  6416. if(ArrayUtil.isNotEmpty(cueTracks)){
  6417. this.showCueDialog(cueTracks,cueinfo)
  6418. }
  6419. // this.showCueSheet = !this.showCueSheet
  6420. return
  6421. }
  6422. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6423. this.stop();
  6424. }
  6425. if (isOpen) {
  6426. this.currentSong = item
  6427. if (index !== undefined) {
  6428. this.curIndex = index
  6429. }
  6430. this.songList = []
  6431. this.songList.push(item)
  6432. this.sonDataSource.pushArrayData(this.songList)
  6433. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  6434. this.currentSong = item
  6435. if (index !== undefined) {
  6436. this.curIndex = index
  6437. }
  6438. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  6439. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  6440. }else {
  6441. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  6442. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  6443. this.songList = globalVideoList
  6444. this.sonDataSource.pushArrayData(this.songList)
  6445. this.currentSong = globalVideoList[this.curIndex]
  6446. }
  6447. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  6448. this.videoUrl = this.currentSong.filePath
  6449. this.name = this.currentSong.name
  6450. this.cover = this.currentSong.pixelMapPath
  6451. this.artist = this.currentSong.artist
  6452. LogUtil.info('onecold this.currentSong.cover =' + this.currentSong.pixelMapPath)
  6453. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  6454. this.startPlayOrResumePlay()
  6455. break;
  6456. case CommonConstants.TYPE_WEBDAV:
  6457. case CommonConstants.TYPE_SMB:
  6458. case CommonConstants.TYPE_NAVIDROME:
  6459. case CommonConstants.TYPE_FTP:
  6460. case CommonConstants.TYPE_BAIDU:
  6461. // 处理网络音频播放(WebDAV/SMB)
  6462. Logger.info(`heanup 处理云端音频播放: ${item.name}, URL: ${item.filePath}`)
  6463. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6464. this.stop();
  6465. }
  6466. if (isOpen) {
  6467. this.currentSong = item
  6468. if (index !== undefined) {
  6469. this.curIndex = index
  6470. }
  6471. this.songList = []
  6472. this.songList.push(item)
  6473. this.sonDataSource.pushArrayData(this.songList)
  6474. } else if (isFromSonPlayList) {
  6475. // 点击来自右下角的播放列表
  6476. this.currentSong = item
  6477. if (index !== undefined) {
  6478. this.curIndex = index
  6479. }
  6480. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  6481. Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  6482. } else {
  6483. // 从全局网络音频列表中查找
  6484. let globalVideoList = this.videoLocalList.filter(video => isRemoteCloudType(video.type)) as VideoItem[];
  6485. this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
  6486. if (this.curIndex === -1 && index !== undefined) {
  6487. this.curIndex = index;
  6488. }
  6489. this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
  6490. this.currentSong = this.songList[this.curIndex];
  6491. this.sonDataSource.pushArrayData(this.songList)
  6492. }
  6493. await this.hydrateRemoteSongFromDb(this.currentSong);
  6494. await this.hydrateRemoteSongFromDb(this.currentSong);
  6495. AppStorage.setOrCreate('currentSong', this.currentSong);
  6496. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  6497. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  6498. context: this.context,
  6499. autoParseMusicName: this.autoParseMusicName
  6500. });
  6501. Logger.info(TAG, `WebDAV URL同步构建完成(分支2): ${this.videoUrl}`);
  6502. this.name = this.currentSong.name
  6503. this.cover = this.currentSong.pixelMapPath
  6504. this.artist = this.currentSong.artist
  6505. Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 完整URL: ${this.videoUrl}`)
  6506. this.startPlayOrResumePlay()
  6507. break;
  6508. }
  6509. }
  6510. private cueComponentId: number = 0
  6511. //显示cue分轨列表对话框
  6512. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  6513. this.getUIContext().getPromptAction().openCustomDialog({
  6514. builder: () => {
  6515. this.cueComptentBuilder(cueTracks,cueinfo)
  6516. },
  6517. isModal:true,
  6518. showInSubWindow:false,
  6519. maskColor: Color.Transparent,
  6520. dialogTransition: // 设置弹窗内容显示的过渡效果
  6521. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  6522. .animation({ duration: 600, curve: Curve.Smooth }),
  6523. maskTransition: // 设置蒙层显示的过渡效果
  6524. TransitionEffect.opacity(0.5)
  6525. .animation({ duration: 600, curve: Curve.Smooth })
  6526. }).then((dialogId: number) => {
  6527. this.cueComponentId = dialogId
  6528. })
  6529. .catch((error: BusinessError) => {
  6530. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  6531. })
  6532. }
  6533. @Builder
  6534. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  6535. CueComptent({
  6536. title:cueinfo.title,
  6537. cueTracks:cueTracks,
  6538. isLongNameRoLL:this.isLongNameRoLL,
  6539. onCancel:()=>{
  6540. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  6541. },
  6542. onDoItemClick: async (item: CueTrack, index: number)=>{
  6543. //获取cueinfo对应的filePath
  6544. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  6545. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  6546. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  6547. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  6548. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  6549. if (this.currentSong){
  6550. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6551. this.stop();//播放之前先停止之前播放。
  6552. }
  6553. this.songList = globalVideoList
  6554. this.sonDataSource.pushArrayData(this.songList)
  6555. if (this.currentSong) {
  6556. try {
  6557. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  6558. context: this.context,
  6559. autoParseMusicName: this.autoParseMusicName
  6560. });
  6561. } catch (error) {
  6562. Logger.error(TAG, `CUE 点播构建播放地址失败: ${(error as Error).message}`);
  6563. this.videoUrl = this.currentSong.filePath;
  6564. }
  6565. }
  6566. this.name = item.title||this.currentSong.name
  6567. this.cover = this.currentSong.pixelMapPath
  6568. this.artist = item.performer||this.currentSong.artist
  6569. this.currentSong.name = this.name
  6570. this.currentSong.artist = this.artist
  6571. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  6572. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  6573. }
  6574. }
  6575. })
  6576. }
  6577. @State isFrontWhite: boolean = false
  6578. setShowPlayTrue(){
  6579. this.getUIContext()?.animateTo({
  6580. duration: 500,
  6581. curve: Curve.Friction
  6582. }, () => {
  6583. this.isShowPlay = true;
  6584. });
  6585. }
  6586. setShowPlayFalse(){
  6587. this.getUIContext()?.animateTo({
  6588. duration: 500,
  6589. curve: Curve.Friction
  6590. }, () => {
  6591. this.isShowPlay = false;
  6592. });
  6593. }
  6594. //打开播放页
  6595. showPlayerView() {
  6596. console.info('onecold showPlayerView this.songList'+ JSON.stringify(this.songList))
  6597. if (ArrayUtil.isNotEmpty(this.songList)) {
  6598. // this.setShowPlayTrue()
  6599. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  6600. this.initLyric(lyricPath);
  6601. this.startAutoHide();
  6602. } else {
  6603. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  6604. }
  6605. }
  6606. //打开播放列表
  6607. openPlayList(){
  6608. if (ArrayUtil.isNotEmpty(this.songList)) {
  6609. this.isShowSheet = !this.isShowSheet;
  6610. this.isFrontWhite = false
  6611. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  6612. this.scrollIndex()
  6613. } else {
  6614. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6615. }
  6616. }
  6617. scrollIndex(){
  6618. try {
  6619. setTimeout(() => {
  6620. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  6621. if(this.curIndex>60){
  6622. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  6623. }else{
  6624. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  6625. }
  6626. })
  6627. }, 123)
  6628. }catch (error) {
  6629. console.error(`onecold scrollIndex出错: ${error}`);
  6630. }
  6631. }
  6632. //播放列表布局
  6633. @Builder
  6634. PlayListSheet() {
  6635. Column() {
  6636. this.PlayList()
  6637. }
  6638. .width('100%')
  6639. .height('100%')
  6640. }
  6641. @State titleStr: string = ''
  6642. @State ablumStr: string = ''
  6643. @State artistStr: string = ''
  6644. @State lyricConStr: string = ''
  6645. @State currentEditItem: string = ''
  6646. @State yearStr: string = ''
  6647. @State trackStr: string = ''
  6648. @State genreStr: string = ''
  6649. @State imagePathStr: string = ''
  6650. @State albumArtistStr: string = ''
  6651. @State composerStr: string = ''
  6652. @State lyricistStr: string = ''
  6653. @State commentStr: string = ''
  6654. @State discStr: string = ''
  6655. doUpdateData() {
  6656. setTimeout(() => {
  6657. if (this.modeType === 0) {
  6658. this.deleteCache(this.currentPath)
  6659. this.getSortedFiles(this.currentPath)
  6660. }else if (this.modeType === 1){
  6661. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6662. }
  6663. }, 500)
  6664. }
  6665. doAllUpdateData() {
  6666. setTimeout(() => {
  6667. if (this.modeType === 0) {
  6668. this.deleteCache(this.currentPath)
  6669. this.getSortedFiles(this.currentPath)
  6670. }
  6671. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6672. workerInstance.postMessage({ code: 3, data: this.context });
  6673. workerInstance.postMessage({ code: 4, data: this.context });
  6674. }, 999)
  6675. }
  6676. //编辑信息
  6677. async doEdit(item: VideoItem) {
  6678. if (!item) {
  6679. return
  6680. }
  6681. if (StrUtil.isEmpty(this.titleStr)) {
  6682. ToastUtil.showToast('标题不能为空')
  6683. return
  6684. }
  6685. //内嵌音乐标签不能开启监听
  6686. // this.deletionWatcher?.stop();
  6687. DialogHelper.showLoadingDialog()
  6688. await PermissionUtil.activatePermission(item.filePath)
  6689. let tempOutPath = ''
  6690. // 如果不是 packName 包下的文件,则直接路径用this.currentPath
  6691. if(!item.filePath.toLowerCase().includes(this.packName)){
  6692. tempOutPath = this.currentPath + '/' + item.fileName
  6693. }
  6694. console.info('onecold tempOutPath ='+tempOutPath)
  6695. //用户更改了封面,那就内嵌下封面
  6696. if(StrUtil.isNotEmpty(this.imagePathStr)){
  6697. const resultCover:boolean = await changeMusicCover(this.context,
  6698. item.filePath,this.imagePathStr,true,tempOutPath);
  6699. this.imagePathStr = ''
  6700. if(resultCover){
  6701. ToastUtil.showToast('内嵌封面成功')
  6702. }
  6703. }
  6704. const metadata:FFMpegTags = {
  6705. title: this.titleStr,
  6706. artist: this.artistStr,
  6707. album: this.ablumStr,
  6708. TYER:this.yearStr,
  6709. genre:this.genreStr,
  6710. track:this.trackStr,
  6711. album_artist:this.albumArtistStr,
  6712. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  6713. COMPOSER:this.composerStr,
  6714. lyricist:this.lyricistStr,
  6715. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  6716. comment:this.commentStr,
  6717. disc:this.discStr,
  6718. };
  6719. let newInput = item.filePath
  6720. //内嵌标签歌路径如果不是包含包名,输入newInput要赋值tempOutPath,然后tempOutPath为空
  6721. if(!item.filePath.toLowerCase().includes(this.packName)&&FileUtil.accessSync(tempOutPath)){
  6722. newInput = tempOutPath
  6723. tempOutPath = ''
  6724. }
  6725. const isWav:boolean = newInput.toLowerCase().endsWith('.wav');
  6726. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  6727. const result:boolean = await repairAudioMetadata(
  6728. newInput,
  6729. this.lyricConStr,
  6730. metadata,
  6731. true,
  6732. tempOutPath
  6733. );
  6734. if (result||isWav) {
  6735. if(!item.filePath.includes(this.packName)){
  6736. //内嵌成功的歌路径如果不是包含包名,则要入库
  6737. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newInput,
  6738. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  6739. this.table.insert(newItem, (id: number) => {
  6740. //加入数据库
  6741. if(this.modeType==0){
  6742. this.deleteCache(this.currentPath)
  6743. this.getSortedFiles(this.currentPath)
  6744. }
  6745. });
  6746. }
  6747. const task = new taskpool.Task(
  6748. updateInfoDb,
  6749. this.context,
  6750. item.filePath,
  6751. this.titleStr,
  6752. this.artistStr,
  6753. this.ablumStr,
  6754. this.lyricConStr,
  6755. this.yearStr,this.genreStr,
  6756. this.trackStr,this.albumArtistStr,
  6757. this.composerStr, this.lyricistStr,
  6758. this.commentStr,this.discStr
  6759. );
  6760. taskpool.execute(task, taskpool.Priority.HIGH).then((result) => {
  6761. if (result) {
  6762. console.log(" onecold 编辑信息成功,数据库已同步");
  6763. if(isWav){
  6764. ToastUtil.showToast('wav格式有可能内嵌失败,但是编辑信息成功')
  6765. }else{
  6766. ToastUtil.showToast('内嵌音乐标签成功')
  6767. }
  6768. this.isShowMoreView = false
  6769. this.name = this.titleStr
  6770. this.syncEditedFields(item)
  6771. if (item.filePath == this.currentSong?.filePath) {
  6772. this.currentSong.name = this.titleStr
  6773. this.artist = this.artistStr
  6774. this.currentSong.artist = this.artistStr
  6775. this.currentSong.album = this.ablumStr
  6776. this.currentSong.year = this.yearStr
  6777. this.currentSong.genre = this.genreStr
  6778. this.currentSong.track = this.trackStr
  6779. this.currentSong.lyricContent = this.lyricConStr
  6780. this.currentSong.ALBUMARTIST = this.albumArtistStr
  6781. this.currentSong.COMPOSER = this.composerStr
  6782. this.currentSong.LYRICIST = this.lyricistStr
  6783. this.currentSong.COMMENT = this.commentStr
  6784. }
  6785. this.syncListsAfterEdit(item.filePath)
  6786. this.doUpateEditedFields(item)
  6787. //this.doUpdateData()
  6788. } else {
  6789. // ToastUtil.showToast('保存失败' + error?.toString())
  6790. console.error(" onecold 编辑信息数据库失败 ");
  6791. }
  6792. // 关闭进度条
  6793. DialogHelper.closeLoading();
  6794. }).catch((error: Error) => {
  6795. // 关闭进度条
  6796. DialogHelper.closeLoading();
  6797. console.error('onecold Subtitle sync failed:', error);
  6798. });
  6799. console.log(' onecold 元数据标签更新成功,');
  6800. } else {
  6801. // 关闭进度条
  6802. DialogHelper.closeLoading();
  6803. ToastUtil.showToast('内嵌音乐标签失败')
  6804. console.log('onecold 内嵌音乐标签失败');
  6805. }
  6806. this.longItemFilePath = ''
  6807. this.tempLyricContent = ''
  6808. this.isShowEdit = false
  6809. }
  6810. // 内嵌标签更新当前内嵌的Item
  6811. async doUpateEditedFields(item: VideoItem) {
  6812. // 找到当前项在 videoLocalList 中的索引
  6813. const index = this.videoLocalList.findIndex(video => video.filePath === item.filePath);
  6814. if (index !== -1) {
  6815. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  6816. const updatedItem = await this.table.queryVideoByFilePath(item.filePath)
  6817. // 只有当查询结果不为 null 时才更新列表
  6818. if (updatedItem !== null) {
  6819. // 更新 videoLocalList 中的项(通过创建新数组触发响应式更新)
  6820. this.videoLocalList = [
  6821. ...this.videoLocalList.slice(0, index),
  6822. updatedItem,
  6823. ...this.videoLocalList.slice(index + 1)
  6824. ];
  6825. // 同步更新 LazyDataSource
  6826. this.dataSource.pushArrayData(this.videoLocalList)
  6827. } else {
  6828. ToastUtil.showToast('未找到更新的数据');
  6829. }
  6830. }
  6831. DialogHelper.closeLoading();
  6832. }
  6833. @Builder
  6834. editSheet(item: VideoItem) {
  6835. Scroll() {
  6836. Column() {
  6837. this.editDetail(item)
  6838. }
  6839. }
  6840. .width('100%')
  6841. .height('100%')
  6842. }
  6843. @Builder
  6844. editDetail(item: VideoItem) {
  6845. Column() {
  6846. if (item) {
  6847. Row() {
  6848. Stack() {
  6849. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  6850. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  6851. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  6852. item.pixelMapPath)
  6853. .fillColor(this.themeColor)
  6854. .height(88)
  6855. .width(88)
  6856. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  6857. .borderRadius(12)
  6858. .clip(true)
  6859. .opacity(this.opacityItem)// 绑定透明度
  6860. .margin({ left: 25 })
  6861. }
  6862. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  6863. .onClick(async () => {
  6864. const imagePath:string | undefined = await this.goSelectImage(item);
  6865. if (imagePath) {
  6866. //用户更改过图片
  6867. this.imagePathStr = imagePath
  6868. }
  6869. })
  6870. .width('28%')
  6871. Row() {
  6872. Column() {
  6873. Text(item.name)
  6874. .fontSize(17)
  6875. .maxLines(1)
  6876. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6877. .animation({
  6878. duration: 555,
  6879. curve: 'Linear',
  6880. })
  6881. .fontColor(this.themeColor)
  6882. .margin({ left: 8 })
  6883. Row() {
  6884. Text(item.artist)
  6885. .fontSize(14)
  6886. .maxLines(1)
  6887. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6888. .padding({ top: 8 })
  6889. .fontColor(this.themeColor)
  6890. .margin({ left: 8 })
  6891. }
  6892. }
  6893. .height('100%')
  6894. .width(100)
  6895. .layoutWeight(1)
  6896. .justifyContent(FlexAlign.Center)
  6897. .alignItems(HorizontalAlign.Start)
  6898. Column() {
  6899. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6900. Row(){
  6901. SymbolGlyph($r('sys.symbol.picture'))
  6902. .fontSize(18)
  6903. .fontColor([Color.White])
  6904. Text('获取封面')
  6905. .margin({ left: 4 })
  6906. .fontSize(11)
  6907. .fontColor(Color.White)
  6908. .fontWeight(480)
  6909. .textAlign(TextAlign.Center)
  6910. }
  6911. .justifyContent(FlexAlign.Center)
  6912. }
  6913. .height(38)
  6914. .width(100)
  6915. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6916. .backgroundColor(this.themeColor)
  6917. .stateEffect(true)
  6918. .margin({ right: 35 })
  6919. .onClick(async () => {
  6920. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  6921. this.showTipsDialog();
  6922. return; // Return empty string when no API is configured
  6923. }
  6924. const imagePath:string | undefined = await this.doSearchCover(item,
  6925. this.titleStr,this.artistStr);
  6926. console.info('onecold imagePath = '+imagePath)
  6927. if (StrUtil.isNotEmpty(imagePath)) {
  6928. //用户更改过图片
  6929. this.imagePathStr = imagePath
  6930. ToastUtil.showToast('获取封面成功')
  6931. }else{
  6932. ToastUtil.showToast('获取封面失败,请重试')
  6933. }
  6934. })
  6935. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6936. Row(){
  6937. SymbolGlyph($r('sys.symbol.input_mode'))
  6938. .fontSize(18)
  6939. .fontColor([Color.White])
  6940. Text('获取歌词')
  6941. .margin({ left: 4 })
  6942. .fontSize(11)
  6943. .fontColor(Color.White)
  6944. .fontWeight(480)
  6945. .textAlign(TextAlign.Center)
  6946. }
  6947. .justifyContent(FlexAlign.Center)
  6948. }
  6949. .height(38)
  6950. .width(100)
  6951. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6952. .backgroundColor(this.themeColor)
  6953. .stateEffect(true)
  6954. .margin({ top: 9, right: 35 })
  6955. .onClick(async () => {
  6956. //判断有没有设置api
  6957. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  6958. if (StrUtil.isEmpty(apiUrl)) {
  6959. this.isLyricSetting = false
  6960. this.showTipsDialog()
  6961. return
  6962. }
  6963. let res: string | undefined = await getApiLyric(apiUrl,
  6964. this.titleStr, this.artistStr, false);
  6965. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  6966. this.lyricConStr = res;
  6967. ToastUtil.showToast('获取歌词成功')
  6968. }else{
  6969. ToastUtil.showToast('获取歌词失败,请重试')
  6970. }
  6971. })
  6972. }
  6973. .justifyContent(FlexAlign.Start)
  6974. }
  6975. .height('100%')
  6976. .justifyContent(FlexAlign.Start)
  6977. .layoutWeight(1)
  6978. }
  6979. .width('100%')
  6980. .height(98)
  6981. Row() {
  6982. Text('标题:')
  6983. .fontSize(14)
  6984. .fontColor($r('app.color.text_color'))
  6985. .margin({ left: 22 })
  6986. TextInput({ text: this.titleStr||item.name })
  6987. .height(40)
  6988. .maxLines(1)
  6989. .fontSize(14)
  6990. .layoutWeight(1)
  6991. .fontColor($r('app.color.text_color'))
  6992. .margin({ right: 15, left: 10 })
  6993. .onChange((val: string) => {
  6994. this.titleStr = val
  6995. })
  6996. Button('修复乱码',{ type: ButtonType.Capsule, stateEffect: true})
  6997. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6998. .backgroundColor(this.themeColor)
  6999. .fontSize(10)
  7000. .margin({ right: 20})
  7001. .onClick(async () => {
  7002. let hwTags = await extractHwMediaMetadata(item.filePath)
  7003. let artist = hwTags?.artist|| '';
  7004. let title = hwTags?.title|| '';
  7005. let album = hwTags?.album|| '';
  7006. console.info('onecold 乱码修正 artist='+artist);
  7007. console.info('onecold 乱码修正 title='+title);
  7008. console.info('onecold 乱码修正 album='+album);
  7009. this.titleStr = title;
  7010. this.artistStr = artist;
  7011. this.ablumStr = album;
  7012. })
  7013. }
  7014. .width('100%')
  7015. .margin({ top: 10, bottom: 10 })
  7016. .justifyContent(FlexAlign.Start)
  7017. Row() {
  7018. Text('艺术家:')
  7019. .fontSize(14)
  7020. .fontColor($r('app.color.text_color'))
  7021. .margin({ left: 22 })
  7022. TextInput({ text: this.artistStr||item.artist })
  7023. .height(40)
  7024. .maxLines(1)
  7025. .fontSize(14)
  7026. .layoutWeight(1)
  7027. .fontColor($r('app.color.text_color'))
  7028. .margin({ right: 20, left: 10 })
  7029. .onChange((val: string) => {
  7030. this.artistStr = val
  7031. })
  7032. }
  7033. .width('100%')
  7034. .margin({ top: 10, bottom: 10 })
  7035. .justifyContent(FlexAlign.Start)
  7036. Row() {
  7037. Text('专辑名:')
  7038. .fontSize(14)
  7039. .fontColor($r('app.color.text_color'))
  7040. .margin({ left: 22 })
  7041. TextInput({ text: this.ablumStr||item.album })
  7042. .height(40)
  7043. .maxLines(1)
  7044. .fontSize(14)
  7045. .layoutWeight(1)
  7046. .fontColor($r('app.color.text_color'))
  7047. .margin({ right: 20, left: 10 })
  7048. .onChange((val: string) => {
  7049. this.ablumStr = val
  7050. })
  7051. }
  7052. .width('100%')
  7053. .margin({ top: 10, bottom: 10 })
  7054. .justifyContent(FlexAlign.Start)
  7055. Row() {
  7056. Column(){
  7057. Column(){
  7058. Text('歌词:')
  7059. .fontSize(14)
  7060. .fontColor($r('app.color.text_color'))
  7061. .margin({ top:9,left: 22 })
  7062. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7063. SymbolGlyph($r('sys.symbol.trash_fill'))
  7064. .fontSize(25)
  7065. .alignSelf(ItemAlign.Center)
  7066. .margin({ left: 22,top:25})
  7067. }
  7068. .backgroundColor(Color.Transparent)
  7069. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7070. Visibility.None:Visibility.Visible)
  7071. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7072. .onClick(()=>{
  7073. this.lyricConStr = ''
  7074. this.lyricContent = ''
  7075. this.tempLyricContent = ''
  7076. })
  7077. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7078. SymbolGlyph($r('sys.symbol.plus'))
  7079. .fontSize(25)
  7080. .alignSelf(ItemAlign.Center)
  7081. .margin({ left: 22,top:25})
  7082. }
  7083. .backgroundColor(Color.Transparent)
  7084. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7085. .onClick( ()=>{
  7086. this.callFilePickerSelectFileForLyric()
  7087. })
  7088. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7089. SymbolGlyph($r('sys.symbol.traditional_square'))
  7090. .fontSize(25)
  7091. .alignSelf(ItemAlign.Center)
  7092. .margin({ left: 22,top:25})
  7093. }
  7094. .backgroundColor(Color.Transparent)
  7095. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7096. Visibility.None:Visibility.Visible)
  7097. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7098. .onClick( ()=>{
  7099. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  7100. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  7101. })
  7102. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7103. Image($r('app.media.jianti'))
  7104. .height(25)
  7105. .fillColor($r('app.color.text_color'))
  7106. .alignSelf(ItemAlign.Center)
  7107. .margin({ left: 22,top:25})
  7108. }
  7109. .backgroundColor(Color.Transparent)
  7110. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7111. Visibility.None:Visibility.Visible)
  7112. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7113. .onClick( ()=>{
  7114. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  7115. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  7116. })
  7117. }
  7118. .layoutWeight(1)
  7119. }
  7120. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  7121. this.tempLyricContent })
  7122. .type(TextAreaType.NORMAL)
  7123. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  7124. .fontSize(14)
  7125. .layoutWeight(1)
  7126. .fontColor($r('app.color.text_color'))
  7127. .margin({ right: 20, left: 10 })
  7128. .onChange((val: string) => {
  7129. this.lyricConStr = val
  7130. })
  7131. }
  7132. .width('100%')
  7133. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  7134. .margin({ top: 10, bottom: 10 })
  7135. .justifyContent(FlexAlign.Start)
  7136. Row() {
  7137. Text('年份:')
  7138. .fontSize(14)
  7139. .fontColor($r('app.color.text_color'))
  7140. .margin({ left: 22 })
  7141. TextInput({ text: item.year })
  7142. .height(40)
  7143. .maxLines(1)
  7144. .fontSize(14)
  7145. .type(InputType.Number)
  7146. .layoutWeight(1)
  7147. .fontColor($r('app.color.text_color'))
  7148. .margin({ right: 20, left: 10 })
  7149. .onChange((val: string) => {
  7150. this.yearStr = val
  7151. })
  7152. }
  7153. .width('100%')
  7154. .margin({ top: 10, bottom: 10 })
  7155. .justifyContent(FlexAlign.Start)
  7156. Row() {
  7157. Text('音轨号:')
  7158. .fontSize(14)
  7159. .fontColor($r('app.color.text_color'))
  7160. .margin({ left: 22 })
  7161. TextInput({ text:item.track=='未知'?'': item.track })
  7162. .height(40)
  7163. .maxLines(1)
  7164. .fontSize(14)
  7165. .type(InputType.Number)
  7166. .layoutWeight(1)
  7167. .fontColor($r('app.color.text_color'))
  7168. .margin({ right: 20, left: 10 })
  7169. .onChange((val: string) => {
  7170. this.trackStr = val
  7171. })
  7172. }
  7173. .width('100%')
  7174. .margin({ top: 10, bottom: 10 })
  7175. .justifyContent(FlexAlign.Start)
  7176. Row() {
  7177. Text('碟号:')
  7178. .fontSize(14)
  7179. .fontColor($r('app.color.text_color'))
  7180. .margin({ left: 22 })
  7181. TextInput({ text:item.disc })
  7182. .height(40)
  7183. .maxLines(1)
  7184. .fontSize(14)
  7185. .type(InputType.Number)
  7186. .layoutWeight(1)
  7187. .fontColor($r('app.color.text_color'))
  7188. .margin({ right: 20, left: 10 })
  7189. .onChange((val: string) => {
  7190. this.discStr = val
  7191. })
  7192. }
  7193. .width('100%')
  7194. .margin({ top: 10, bottom: 10 })
  7195. .justifyContent(FlexAlign.Start)
  7196. Row() {
  7197. Text('风格:')
  7198. .fontSize(14)
  7199. .fontColor($r('app.color.text_color'))
  7200. .margin({ left: 22 })
  7201. TextInput({ text: item.genre })
  7202. .height(40)
  7203. .maxLines(1)
  7204. .fontSize(14)
  7205. .layoutWeight(1)
  7206. .fontColor($r('app.color.text_color'))
  7207. .margin({ right: 20, left: 10 })
  7208. .onChange((val: string) => {
  7209. this.genreStr = val
  7210. })
  7211. }
  7212. .width('100%')
  7213. .margin({ top: 10, bottom: 10 })
  7214. .justifyContent(FlexAlign.Start)
  7215. Row() {
  7216. Text('专辑艺术家:')
  7217. .fontSize(14)
  7218. .fontColor($r('app.color.text_color'))
  7219. .margin({ left: 22 })
  7220. TextInput({ text: item.ALBUMARTIST })
  7221. .height(40)
  7222. .maxLines(1)
  7223. .fontSize(14)
  7224. .layoutWeight(1)
  7225. .fontColor($r('app.color.text_color'))
  7226. .margin({ right: 20, left: 10 })
  7227. .onChange((val: string) => {
  7228. this.albumArtistStr = val
  7229. })
  7230. }
  7231. .width('100%')
  7232. .margin({ top: 10, bottom: 10 })
  7233. .justifyContent(FlexAlign.Start)
  7234. Row() {
  7235. Text('作曲:')
  7236. .fontSize(14)
  7237. .fontColor($r('app.color.text_color'))
  7238. .margin({ left: 22 })
  7239. TextInput({ text: item.COMPOSER })
  7240. .height(40)
  7241. .maxLines(1)
  7242. .fontSize(14)
  7243. .layoutWeight(1)
  7244. .fontColor($r('app.color.text_color'))
  7245. .margin({ right: 20, left: 10 })
  7246. .onChange((val: string) => {
  7247. this.composerStr = val
  7248. })
  7249. }
  7250. .width('100%')
  7251. .margin({ top: 10, bottom: 10 })
  7252. .justifyContent(FlexAlign.Start)
  7253. Row() {
  7254. Text('作词:')
  7255. .fontSize(14)
  7256. .fontColor($r('app.color.text_color'))
  7257. .margin({ left: 22 })
  7258. TextInput({ text: item.LYRICIST })
  7259. .height(40)
  7260. .maxLines(1)
  7261. .fontSize(14)
  7262. .layoutWeight(1)
  7263. .fontColor($r('app.color.text_color'))
  7264. .margin({ right: 20, left: 10 })
  7265. .onChange((val: string) => {
  7266. this.lyricistStr = val
  7267. })
  7268. }
  7269. .width('100%')
  7270. .margin({ top: 10, bottom: 10 })
  7271. .justifyContent(FlexAlign.Start)
  7272. Row() {
  7273. Text('注释:')
  7274. .fontSize(14)
  7275. .fontColor($r('app.color.text_color'))
  7276. .margin({ left: 22 })
  7277. TextInput({ text: item.COMMENT })
  7278. .height(40)
  7279. .maxLines(1)
  7280. .fontSize(14)
  7281. .layoutWeight(1)
  7282. .fontColor($r('app.color.text_color'))
  7283. .margin({ right: 20, left: 10 })
  7284. .onChange((val: string) => {
  7285. this.commentStr = val
  7286. })
  7287. }
  7288. .width('100%')
  7289. .margin({ top: 10, bottom: 10 })
  7290. .justifyContent(FlexAlign.Start)
  7291. Row() {
  7292. Button('保存')
  7293. .fontColor(Color.White)
  7294. .layoutWeight(1)
  7295. .height(50)
  7296. .width(100)
  7297. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7298. .backgroundColor(this.themeColor)
  7299. .stateEffect(true)
  7300. .margin({ right: 20, bottom: 20 })
  7301. .onClick(async () => {
  7302. this.doEdit(item)
  7303. })
  7304. Button('取消')
  7305. .fontColor(Color.White)
  7306. .layoutWeight(1)
  7307. .height(50)
  7308. .width(100)
  7309. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7310. .backgroundColor(this.themeColor)
  7311. .stateEffect(true)
  7312. .margin({ left: 20, bottom: 20 })
  7313. .onClick(async () => {
  7314. if(this.isGridMusic){
  7315. this.longItemFilePath =''
  7316. }else{
  7317. this.isShowEdit = false
  7318. }
  7319. this.setEditStrEmpty()
  7320. if(this.isShowPlay){
  7321. this.isShowEdit = false
  7322. }
  7323. })
  7324. }
  7325. .margin({
  7326. left: 38,
  7327. right: 38,
  7328. top: 10,
  7329. bottom: 10
  7330. })
  7331. .width(250)
  7332. .height(60)
  7333. }
  7334. }
  7335. .margin({ bottom: 20 })
  7336. }
  7337. setEditStrEmpty(){
  7338. this.imagePathStr = ''
  7339. this.lyricConStr = ''
  7340. this.artistStr = ''
  7341. this.titleStr = ''
  7342. this.ablumStr = ''
  7343. this.genreStr = ''
  7344. this.yearStr = ''
  7345. this.trackStr = ''
  7346. this.albumArtistStr = ''
  7347. this.composerStr = ''
  7348. this.lyricistStr = ''
  7349. this.commentStr = ''
  7350. this.discStr = ''
  7351. }
  7352. initEditFields(item?: VideoItem) {
  7353. if (!item) {
  7354. this.setEditStrEmpty()
  7355. return
  7356. }
  7357. this.imagePathStr = ''
  7358. this.titleStr = item.name ?? ''
  7359. this.artistStr = item.artist ?? ''
  7360. this.ablumStr = item.album ?? ''
  7361. this.genreStr = item.genre ?? ''
  7362. this.yearStr = item.year ?? ''
  7363. this.trackStr = item.track ?? ''
  7364. this.albumArtistStr = item.ALBUMARTIST ?? ''
  7365. this.composerStr = item.COMPOSER ?? ''
  7366. this.lyricistStr = item.LYRICIST ?? ''
  7367. this.commentStr = item.COMMENT ?? ''
  7368. this.discStr = item.disc ?? ''
  7369. this.lyricConStr = item.lyricContent ?? ''
  7370. }
  7371. private syncEditedFields(target?: VideoItem) {
  7372. if (!target) {
  7373. return
  7374. }
  7375. target.name = this.titleStr
  7376. target.artist = this.artistStr
  7377. target.album = this.ablumStr
  7378. target.lyricContent = this.lyricConStr
  7379. target.year = this.yearStr
  7380. target.genre = this.genreStr
  7381. target.track = this.trackStr
  7382. target.ALBUMARTIST = this.albumArtistStr
  7383. target.COMPOSER = this.composerStr
  7384. target.LYRICIST = this.lyricistStr
  7385. target.COMMENT = this.commentStr
  7386. target.disc = this.discStr
  7387. }
  7388. private replaceItemInList(list: Array<VideoItem> | undefined, filePath: string,
  7389. apply?: (next: Array<VideoItem>) => void) {
  7390. if (!list || ArrayUtil.isEmpty(list)) {
  7391. return
  7392. }
  7393. const index = list.findIndex((video: VideoItem) => video.filePath === filePath)
  7394. if (index < 0) {
  7395. return
  7396. }
  7397. const nextList = [...list]
  7398. this.syncEditedFields(nextList[index])
  7399. apply?.(nextList)
  7400. }
  7401. private syncListsAfterEdit(filePath: string) {
  7402. this.replaceItemInList(this.videoLocalList, filePath, (next: Array<VideoItem>) => {
  7403. this.videoLocalList = next
  7404. this.dataSource.pushArrayData(next)
  7405. })
  7406. this.replaceItemInList(this.songList, filePath, (next: Array<VideoItem>) => {
  7407. this.songList = next
  7408. this.sonDataSource.pushArrayData(next)
  7409. })
  7410. this.replaceItemInList(this.favList, filePath, (next: Array<VideoItem>) => {
  7411. this.favList = next
  7412. })
  7413. this.replaceItemInList(this.historyList, filePath, (next: Array<VideoItem>) => {
  7414. this.historyList = next
  7415. })
  7416. this.replaceItemInList(this.currentSongList, filePath, (next: Array<VideoItem>) => {
  7417. this.currentSongList = next
  7418. })
  7419. this.replaceItemInList(this.mediaKuList, filePath, (next: Array<VideoItem>) => {
  7420. this.mediaKuList = next
  7421. })
  7422. this.replaceItemInList(this.filteredList, filePath, (next: Array<VideoItem>) => {
  7423. this.filteredList = next
  7424. })
  7425. this.replaceItemInList(this.artistList, filePath, (next: Array<VideoItem>) => {
  7426. this.artistList = next
  7427. })
  7428. this.replaceItemInList(this.albumList, filePath, (next: Array<VideoItem>) => {
  7429. this.albumList = next
  7430. })
  7431. this.listRefreshKey++
  7432. }
  7433. private refreshLazyListViews(mainListUpdated: boolean, playlistUpdated: boolean): void {
  7434. if (!mainListUpdated && !playlistUpdated) {
  7435. return;
  7436. }
  7437. this.listRefreshKey++;
  7438. if (mainListUpdated) {
  7439. this.dataSource.notifyDataReload();
  7440. }
  7441. if (playlistUpdated) {
  7442. this.sonDataSource.notifyDataReload();
  7443. }
  7444. }
  7445. @Builder
  7446. detailSheet(item:VideoItem) {
  7447. Scroll() {
  7448. Column() {
  7449. this.songDetail(item)
  7450. }
  7451. }
  7452. .width('100%')
  7453. .height('100%')
  7454. }
  7455. @Builder
  7456. songDetail(currentItem:VideoItem) {
  7457. Column() {
  7458. if (currentItem) {
  7459. Row() {
  7460. Stack() {
  7461. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.music_red') :
  7462. currentItem.pixelMapPath)
  7463. .fillColor(this.themeColor)
  7464. .height(80)
  7465. .width(80)
  7466. .borderRadius(10)
  7467. .opacity(this.opacityItem)// 绑定透明度
  7468. .margin({ left: 22 })
  7469. }
  7470. Column() {
  7471. Column() {
  7472. Text(currentItem.name)
  7473. .fontSize(16)
  7474. .maxLines(1)
  7475. .animation({
  7476. duration: 555,
  7477. curve: 'Linear',
  7478. })
  7479. .fontColor($r('app.color.text_color'))
  7480. .margin({ left: 15 })
  7481. }
  7482. .height('100%')
  7483. .width('100%')
  7484. .justifyContent(FlexAlign.Center)
  7485. .alignItems(HorizontalAlign.Start)
  7486. }
  7487. .height('100%')
  7488. }
  7489. .width('100%')
  7490. .height(90)
  7491. .justifyContent(FlexAlign.SpaceBetween)
  7492. Row() {
  7493. Text('艺术家:')
  7494. .fontSize(14)
  7495. .fontColor($r('app.color.text_color'))
  7496. .margin({ left: 22 })
  7497. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  7498. .fontSize(14)
  7499. .fontColor($r('app.color.text_color'))
  7500. .margin({ left: 10 })
  7501. .layoutWeight(1)
  7502. }
  7503. .width('100%')
  7504. .margin({ top: 10, bottom: 10 })
  7505. .justifyContent(FlexAlign.Start)
  7506. Row() {
  7507. Text('专辑名:')
  7508. .fontSize(14)
  7509. .fontColor($r('app.color.text_color'))
  7510. .margin({ left: 22 })
  7511. Text(currentItem?.album ?currentItem.album : '未知专辑')
  7512. .fontSize(14)
  7513. .margin({ left: 10 })
  7514. .fontColor($r('app.color.text_color'))
  7515. .layoutWeight(1)
  7516. }
  7517. .width('100%')
  7518. .margin({ top: 10, bottom: 10 })
  7519. .justifyContent(FlexAlign.Start)
  7520. Row() {
  7521. Text('时长:')
  7522. .fontSize(14)
  7523. .fontColor($r('app.color.text_color'))
  7524. .margin({ left: 22 })
  7525. Text(StrUtil.isEmpty(currentItem.duration)?
  7526. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  7527. .fontSize(14)
  7528. .margin({ left: 10 })
  7529. .fontColor($r('app.color.text_color'))
  7530. .layoutWeight(1)
  7531. }
  7532. .width('100%')
  7533. .margin({ top: 10, bottom: 10 })
  7534. .justifyContent(FlexAlign.Start)
  7535. Row() {
  7536. Text('采样率:')
  7537. .fontSize(14)
  7538. .fontColor($r('app.color.text_color'))
  7539. .margin({ left: 22 })
  7540. Text(Utility.convertToKHz(currentItem.sampleRate))
  7541. .fontSize(14)
  7542. .margin({ left: 10 })
  7543. .fontColor($r('app.color.text_color'))
  7544. .layoutWeight(1)
  7545. }
  7546. .width('100%')
  7547. .margin({ top: 10, bottom: 10 })
  7548. .justifyContent(FlexAlign.Start)
  7549. Row() {
  7550. Text('比特率:')
  7551. .fontSize(14)
  7552. .fontColor($r('app.color.text_color'))
  7553. .margin({ left: 22 })
  7554. Text(currentItem.bit_rate)
  7555. .fontSize(14)
  7556. .margin({ left: 10 })
  7557. .fontColor($r('app.color.text_color'))
  7558. .layoutWeight(1)
  7559. }
  7560. .width('100%')
  7561. .margin({ top: 10, bottom: 10 })
  7562. .justifyContent(FlexAlign.Start)
  7563. Row() {
  7564. Text('位深:')
  7565. .fontSize(14)
  7566. .fontColor($r('app.color.text_color'))
  7567. .margin({ left: 22 })
  7568. Text(`${currentItem.bits_per_raw_sample} bits`)
  7569. .fontSize(14)
  7570. .margin({ left: 10 })
  7571. .fontColor($r('app.color.text_color'))
  7572. .layoutWeight(1)
  7573. }
  7574. .width('100%')
  7575. .margin({ top: 10, bottom: 10 })
  7576. .justifyContent(FlexAlign.Start)
  7577. Row() {
  7578. Text('声道:')
  7579. .fontSize(14)
  7580. .fontColor($r('app.color.text_color'))
  7581. .margin({ left: 22 })
  7582. Text(`${currentItem.channels}`)
  7583. .fontSize(14)
  7584. .margin({ left: 10 })
  7585. .fontColor($r('app.color.text_color'))
  7586. .layoutWeight(1)
  7587. }
  7588. .width('100%')
  7589. .margin({ top: 10, bottom: 10 })
  7590. .justifyContent(FlexAlign.Start)
  7591. Row() {
  7592. Text('声道布局:')
  7593. .fontSize(14)
  7594. .fontColor($r('app.color.text_color'))
  7595. .margin({ left: 22 })
  7596. Text(`${currentItem.channel_layout}`)
  7597. .fontSize(14)
  7598. .margin({ left: 10 })
  7599. .fontColor($r('app.color.text_color'))
  7600. .layoutWeight(1)
  7601. }
  7602. .width('100%')
  7603. .margin({ top: 10, bottom: 10 })
  7604. .justifyContent(FlexAlign.Start)
  7605. Row() {
  7606. Text('起始播放点:')
  7607. .fontSize(14)
  7608. .fontColor($r('app.color.text_color'))
  7609. .margin({ left: 22 })
  7610. Text(`${currentItem.start_time}`)
  7611. .fontSize(14)
  7612. .margin({ left: 10 })
  7613. .fontColor($r('app.color.text_color'))
  7614. .layoutWeight(1)
  7615. }
  7616. .width('100%')
  7617. .margin({ top: 10, bottom: 10 })
  7618. .justifyContent(FlexAlign.Start)
  7619. Row() {
  7620. Text('风格:')
  7621. .fontSize(14)
  7622. .fontColor($r('app.color.text_color'))
  7623. .margin({ left: 22 })
  7624. Text(currentItem.genre)
  7625. .fontSize(14)
  7626. .margin({ left: 10 })
  7627. .fontColor($r('app.color.text_color'))
  7628. .layoutWeight(1)
  7629. }
  7630. .width('100%')
  7631. .margin({ top: 10, bottom: 10 })
  7632. .justifyContent(FlexAlign.Start)
  7633. Row() {
  7634. Text('发行时间:')
  7635. .fontSize(14)
  7636. .fontColor($r('app.color.text_color'))
  7637. .margin({ left: 22 })
  7638. Text(currentItem.year)
  7639. .fontSize(14)
  7640. .margin({ left: 10 })
  7641. .fontColor($r('app.color.text_color'))
  7642. .layoutWeight(1)
  7643. }
  7644. .width('100%')
  7645. .margin({ top: 10, bottom: 10 })
  7646. .justifyContent(FlexAlign.Start)
  7647. Row() {
  7648. Text('质量评分:')
  7649. .fontSize(14)
  7650. .fontColor($r('app.color.text_color'))
  7651. .margin({ left: 22 })
  7652. Text(currentItem.probe_score+"")
  7653. .fontSize(14)
  7654. .margin({ left: 10 })
  7655. .fontColor($r('app.color.text_color'))
  7656. .layoutWeight(1)
  7657. }
  7658. .width('100%')
  7659. .margin({ top: 10, bottom: 10 })
  7660. .justifyContent(FlexAlign.Start)
  7661. Row() {
  7662. Text('音轨号:')
  7663. .fontSize(14)
  7664. .fontColor($r('app.color.text_color'))
  7665. .margin({ left: 22 })
  7666. Text(currentItem.track)
  7667. .fontSize(14)
  7668. .margin({ left: 10 })
  7669. .fontColor($r('app.color.text_color'))
  7670. .layoutWeight(1)
  7671. }
  7672. .width('100%')
  7673. .margin({ top: 10, bottom: 10 })
  7674. .justifyContent(FlexAlign.Start)
  7675. Row() {
  7676. Text('碟号:')
  7677. .fontSize(14)
  7678. .fontColor($r('app.color.text_color'))
  7679. .margin({ left: 22 })
  7680. Text(currentItem.disc)
  7681. .fontSize(14)
  7682. .margin({ left: 10 })
  7683. .fontColor($r('app.color.text_color'))
  7684. .layoutWeight(1)
  7685. }
  7686. .width('100%')
  7687. .margin({ top: 10, bottom: 10 })
  7688. .justifyContent(FlexAlign.Start)
  7689. Row() {
  7690. Text('专辑艺术家:')
  7691. .fontSize(14)
  7692. .fontColor($r('app.color.text_color'))
  7693. .margin({ left: 22 })
  7694. Text(currentItem.ALBUMARTIST)
  7695. .fontSize(14)
  7696. .margin({ left: 10 })
  7697. .fontColor($r('app.color.text_color'))
  7698. .layoutWeight(1)
  7699. }
  7700. .width('100%')
  7701. .margin({ top: 10, bottom: 10 })
  7702. .justifyContent(FlexAlign.Start)
  7703. Row() {
  7704. Text('作曲家:')
  7705. .fontSize(14)
  7706. .fontColor($r('app.color.text_color'))
  7707. .margin({ left: 22 })
  7708. Text(currentItem.COMPOSER)
  7709. .fontSize(14)
  7710. .margin({ left: 10 })
  7711. .fontColor($r('app.color.text_color'))
  7712. .layoutWeight(1)
  7713. }
  7714. .width('100%')
  7715. .margin({ top: 10, bottom: 10 })
  7716. .justifyContent(FlexAlign.Start)
  7717. Row() {
  7718. Text('作词家:')
  7719. .fontSize(14)
  7720. .fontColor($r('app.color.text_color'))
  7721. .margin({ left: 22 })
  7722. Text(currentItem.LYRICIST)
  7723. .fontSize(14)
  7724. .margin({ left: 10 })
  7725. .fontColor($r('app.color.text_color'))
  7726. .layoutWeight(1)
  7727. }
  7728. .width('100%')
  7729. .margin({ top: 10, bottom: 10 })
  7730. .justifyContent(FlexAlign.Start)
  7731. Row() {
  7732. Text('注释:')
  7733. .fontSize(14)
  7734. .fontColor($r('app.color.text_color'))
  7735. .margin({ left: 22 })
  7736. Text(currentItem.COMMENT)
  7737. .fontSize(14)
  7738. .margin({ left: 10 })
  7739. .fontColor($r('app.color.text_color'))
  7740. .layoutWeight(1)
  7741. }
  7742. .width('100%')
  7743. .margin({ top: 10, bottom: 10 })
  7744. .justifyContent(FlexAlign.Start)
  7745. Row() {
  7746. Text('格式:')
  7747. .fontSize(14)
  7748. .fontColor($r('app.color.text_color'))
  7749. .margin({ left: 22 })
  7750. Text(Utility.formatMimeType(currentItem.mimeType))
  7751. .fontSize(14)
  7752. .margin({ left: 10 })
  7753. .fontColor($r('app.color.text_color'))
  7754. .layoutWeight(1)
  7755. }
  7756. .width('100%')
  7757. .margin({ top: 10, bottom: 10 })
  7758. .justifyContent(FlexAlign.Start)
  7759. Row() {
  7760. Text('播放次数:')
  7761. .fontSize(14)
  7762. .fontColor($r('app.color.text_color'))
  7763. .margin({ left: 22 })
  7764. Text(currentItem.playCount?.toString())
  7765. .fontSize(14)
  7766. .margin({ left: 10 })
  7767. .fontColor($r('app.color.text_color'))
  7768. .layoutWeight(1)
  7769. }
  7770. .width('100%')
  7771. .margin({ top: 10, bottom: 10 })
  7772. .justifyContent(FlexAlign.Start)
  7773. Row() {
  7774. Text('流数量:')
  7775. .fontSize(14)
  7776. .fontColor($r('app.color.text_color'))
  7777. .margin({ left: 22 })
  7778. Text(currentItem.nb_streams?.toString())
  7779. .fontSize(14)
  7780. .margin({ left: 10 })
  7781. .fontColor($r('app.color.text_color'))
  7782. .layoutWeight(1)
  7783. }
  7784. .width('100%')
  7785. .margin({ top: 10, bottom: 10 })
  7786. .justifyContent(FlexAlign.Start)
  7787. Row() {
  7788. Text('文件大小:')
  7789. .fontSize(14)
  7790. .fontColor($r('app.color.text_color'))
  7791. .margin({ left: 22 })
  7792. Text(currentItem.size)
  7793. .fontSize(14)
  7794. .margin({ left: 10 })
  7795. .fontColor($r('app.color.text_color'))
  7796. .layoutWeight(1)
  7797. }
  7798. .width('100%')
  7799. .margin({ top: 10, bottom: 10 })
  7800. .justifyContent(FlexAlign.Start)
  7801. Row() {
  7802. Text('文件名:')
  7803. .fontSize(14)
  7804. .fontColor($r('app.color.text_color'))
  7805. .margin({ left: 22 })
  7806. Text(currentItem.fileName)
  7807. .fontSize(14)
  7808. .margin({ left: 10 })
  7809. .fontColor($r('app.color.text_color'))
  7810. .layoutWeight(1)
  7811. }
  7812. .width('100%')
  7813. .margin({ top: 10, bottom: 10 })
  7814. .justifyContent(FlexAlign.Start)
  7815. Row() {
  7816. Text('修改时间:')
  7817. .fontSize(14)
  7818. .fontColor($r('app.color.text_color'))
  7819. .margin({ left: 22 })
  7820. Text(currentItem.cTime)
  7821. .fontSize(14)
  7822. .margin({ left: 10 })
  7823. .fontColor($r('app.color.text_color'))
  7824. .layoutWeight(1)
  7825. }
  7826. .width('100%')
  7827. .margin({ top: 10, bottom: 10 })
  7828. .justifyContent(FlexAlign.Start)
  7829. Row() {
  7830. Text('存放目录:')
  7831. .fontSize(14)
  7832. .fontColor($r('app.color.text_color'))
  7833. .margin({ left: 22 })
  7834. Text(currentItem.filePath)
  7835. .fontSize(12)
  7836. .margin({ left: 10 })
  7837. .fontColor($r('app.color.text_color'))
  7838. .layoutWeight(1)
  7839. }
  7840. .margin({ top: 10, bottom: 10 })
  7841. .width('100%')
  7842. .justifyContent(FlexAlign.Start)
  7843. Row() {
  7844. Text('内嵌歌词:')
  7845. .fontSize(14)
  7846. .fontColor($r('app.color.text_color'))
  7847. .margin({ left: 22 })
  7848. Text(currentItem.lyricContent)
  7849. .fontSize(12)
  7850. .copyOption(CopyOptions.InApp)
  7851. .margin({ left: 10 })
  7852. .fontColor($r('app.color.text_color'))
  7853. .layoutWeight(1)
  7854. }
  7855. .margin({ top: 10, bottom: 10 })
  7856. .width('100%')
  7857. .justifyContent(FlexAlign.Start)
  7858. }
  7859. }
  7860. .margin({ bottom: 20 })
  7861. }
  7862. //定时关闭布局
  7863. @Builder
  7864. TimeCloseSheet() {
  7865. Scroll() {
  7866. Column() {
  7867. this.TimeClose()
  7868. }
  7869. }
  7870. .width('100%')
  7871. .height('100%')
  7872. }
  7873. //倒计时关闭音乐,退出App功能实现。
  7874. @State selectedMinutes: number = 0 // 0表示未开启
  7875. @State remainingSeconds: number = 0
  7876. // 预设时间选项
  7877. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  7878. private formatTime(seconds: number): string {
  7879. const mins = Math.floor(seconds / 60)
  7880. const secs = seconds % 60
  7881. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  7882. }
  7883. // 开始倒计时
  7884. private handleTimeSelect(minutes: number) {
  7885. if (minutes === this.selectedMinutes) {
  7886. this.stopCountdown();
  7887. this.selectedMinutes = 0;
  7888. return;
  7889. }
  7890. this.selectedMinutes = minutes;
  7891. this.remainingSeconds = minutes * 60;
  7892. this.startCountdown(); // 新增调用
  7893. }
  7894. @Builder
  7895. TimeClose() {
  7896. Column() {
  7897. // 倒计时显示区域
  7898. Text(this.selectedMinutes > 0 ?
  7899. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  7900. "定时关闭未开启")
  7901. .fontSize(17)
  7902. .fontColor($r('app.color.text_color'))
  7903. .margin({ top: 2, bottom: 8 });
  7904. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  7905. ForEach(this.presetTimes, (minutes: number, index: number) => {
  7906. // 单行时间选项容器
  7907. Row() {
  7908. // 文字描述区域
  7909. Text(this.getDisplayText(minutes))
  7910. .fontSize(15)
  7911. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  7912. $r('app.color.text_color'))// 选中态颜色变化
  7913. .textAlign(TextAlign.Start)
  7914. .layoutWeight(1); // 占据剩余空间
  7915. // 复选框样式的选择器
  7916. Row() {
  7917. if (minutes === this.selectedMinutes) {
  7918. // 选中状态 - 带勾号的圆形复选框
  7919. Row() {
  7920. // 使用系统内置的勾号图标
  7921. Image($r('sys.media.ohos_ic_public_ok'))
  7922. .width(14)
  7923. .height(14)
  7924. .fillColor(Color.White)
  7925. }
  7926. .width(24)
  7927. .height(24)
  7928. .borderRadius(12)
  7929. .backgroundColor(this.themeColor)
  7930. .justifyContent(FlexAlign.Center)
  7931. .alignItems(VerticalAlign.Center)
  7932. } else {
  7933. // 未选中状态的圆形边框
  7934. Row()
  7935. .width(24)
  7936. .height(24)
  7937. .borderRadius(12)
  7938. .border({
  7939. width: 2,
  7940. color: $r('app.color.text_color'),
  7941. style: BorderStyle.Solid
  7942. })
  7943. .backgroundColor(Color.Transparent)
  7944. }
  7945. }
  7946. .width(24)
  7947. .height(24)
  7948. .margin({ left: 20 })
  7949. .justifyContent(FlexAlign.Center)
  7950. .alignItems(VerticalAlign.Center)
  7951. }
  7952. .width('100%')
  7953. .padding({
  7954. top: 18,
  7955. bottom: 18,
  7956. left: 18,
  7957. right: 18
  7958. })
  7959. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  7960. $r('app.color.bottom_control_background')) // 选中背景高亮
  7961. .borderRadius(12)
  7962. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7963. .margin({ bottom: 18 })
  7964. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  7965. });
  7966. }
  7967. .width('100%')
  7968. .padding(16)
  7969. }
  7970. }
  7971. // 获取显示文本
  7972. private getDisplayText(minutes: number): string {
  7973. if (minutes === -1) {
  7974. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  7975. }
  7976. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  7977. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  7978. }
  7979. // 处理选择事件
  7980. private handleSelect(minutes: number): void {
  7981. if (minutes === -1) { // 自定义
  7982. // 弹出自定义时间对话框
  7983. DialogHelper.showTextInputDialog({
  7984. title: '自定义时间',
  7985. maskColor: Color.Transparent,
  7986. inputType: InputType.Number,
  7987. text: '',
  7988. onChange: (text) => {
  7989. console.error("onChange: " + text);
  7990. },
  7991. onAction: (action, dialogId, content) => {
  7992. if (action == DialogAction.TWO) {
  7993. const customMinutes = Number(content);
  7994. if (customMinutes > 0) {
  7995. this.handleTimeSelect(customMinutes); // 设置自定义时间
  7996. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  7997. }
  7998. }
  7999. }
  8000. });
  8001. } else {
  8002. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  8003. }
  8004. }
  8005. // 添加定时器引用
  8006. private timerId: number = -1;
  8007. // 启动/重置倒计时
  8008. private startCountdown() {
  8009. // 清除旧定时器
  8010. if (this.timerId !== -1) {
  8011. clearInterval(this.timerId);
  8012. }
  8013. // 创建新定时器
  8014. if (this.selectedMinutes > 0) {
  8015. this.timerId = setInterval(() => {
  8016. if (this.remainingSeconds === 15) {
  8017. this.showConfirmationDialog();
  8018. }
  8019. if (this.remainingSeconds > 0) {
  8020. this.remainingSeconds -= 1;
  8021. } else {
  8022. this.stopCountdown();
  8023. this.handleTimeout();
  8024. }
  8025. }, 1000);
  8026. }
  8027. }
  8028. // 15倒计时后再次提示显示确认是否关闭App对话框
  8029. private showConfirmationDialog() {
  8030. DialogHelper.showAlertDialog({
  8031. backgroundColor: $r('app.color.btn_green'),
  8032. title: '确认关闭',
  8033. maskColor: Color.Transparent,
  8034. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  8035. borderStyle: BorderStyle.Dashed,
  8036. primaryButton: '暂不关闭',
  8037. secondaryButton: '确定',
  8038. onAction: (action) => {
  8039. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  8040. this.stopCountdown();
  8041. this.selectedMinutes = 0
  8042. } else if (action == DialogAction.TWO) {
  8043. }
  8044. }
  8045. })
  8046. }
  8047. // 停止倒计时
  8048. private stopCountdown() {
  8049. if (this.timerId !== -1) {
  8050. clearInterval(this.timerId);
  8051. this.timerId = -1;
  8052. }
  8053. }
  8054. // 超时处理
  8055. private handleTimeout() {
  8056. // 执行播放器关闭逻辑
  8057. this.selectedMinutes = 0;
  8058. ToastUtil.showToast(" 定时关闭已完成");
  8059. this.stop(); // 假设存在的播放器实例
  8060. //退出APP
  8061. const mContext = getContext(this) as common.UIAbilityContext
  8062. mContext.terminateSelf();
  8063. AvSessionController.getInstance(true).unregisterSessionListener()
  8064. }
  8065. //倒计时关闭音乐,退出App功能实现结束。
  8066. //播放列表的拖动List 重新排序
  8067. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  8068. //左滑操作 移动文件 重命名 删除等操作
  8069. @Builder
  8070. sonButton(item: VideoItem, index: number, filePath: string) {
  8071. Row() {
  8072. //加入下一首播放
  8073. Button() {
  8074. Image($r('app.media.next_to_play'))
  8075. .fillColor(Color.White)
  8076. .width(20)
  8077. }
  8078. .width(40)
  8079. .height(40)
  8080. .type(ButtonType.Circle)
  8081. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8082. .backgroundColor(this.themeColor)
  8083. .margin(5)
  8084. .onClick(() => {
  8085. this.addToNextPlay(item);
  8086. })
  8087. Button() {
  8088. Image($r('app.media.close'))
  8089. .fillColor(Color.White)
  8090. .width(20)
  8091. }
  8092. .width(40)
  8093. .height(40)
  8094. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8095. .type(ButtonType.Circle)
  8096. .backgroundColor(this.themeColor)
  8097. .margin(5)
  8098. .onClick(() => {
  8099. this.songList.splice(Number(index), 1)
  8100. this.sonDataSource.pushArrayData(this.songList)
  8101. })
  8102. Button() {
  8103. Image($r('app.media.share2'))
  8104. .fillColor(Color.White)
  8105. .width(20)
  8106. }
  8107. .width(40)
  8108. .height(40)
  8109. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8110. .type(ButtonType.Circle)
  8111. .backgroundColor(this.themeColor)
  8112. .margin(5)
  8113. .onClick(() => {
  8114. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  8115. })
  8116. }
  8117. }
  8118. itemMoveSon(index: number, newIndex: number): void {
  8119. if (newIndex < 0 || newIndex >= this.songList.length) {
  8120. return;
  8121. }
  8122. let tmp = this.songList.splice(index, 1);
  8123. this.songList.splice(newIndex, 0, tmp[0]);
  8124. this.sonDataSource.pushArrayData(this.songList)
  8125. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  8126. if(this.modeType==4&&this.playlistTable){
  8127. updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
  8128. }
  8129. }
  8130. @Builder
  8131. PlayList() {
  8132. List({ scroller: this.playListScroller }) {
  8133. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  8134. ListItem() {
  8135. this.MusicItemSon(item, index)
  8136. }
  8137. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  8138. .animation({
  8139. duration: 666,
  8140. curve: 'ease-in-out' // 可选动画曲线
  8141. })
  8142. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 600 }),
  8143. TransitionEffect.scale({ x: 0, y: 0 })))
  8144. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  8145. //拖动List关键代码开始
  8146. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  8147. .zIndex(this.dragItem === index ? 1 : 0)
  8148. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  8149. .gesture(
  8150. GestureGroup(GestureMode.Sequence,
  8151. LongPressGesture({ repeat: true })
  8152. .onAction((event?: GestureEvent) => {
  8153. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  8154. this.scaleItem = index
  8155. })
  8156. })
  8157. .onActionEnd(() => {
  8158. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  8159. this.scaleItem = -1
  8160. })
  8161. }),
  8162. PanGesture({ fingers: 1, direction: null, distance: 0 })
  8163. .onActionStart(() => {
  8164. this.dragItem = index // 记录当前拖动项索引
  8165. this.dragRefOffset = 0 // 重置偏移基准
  8166. })
  8167. .onActionUpdate((event: GestureEvent) => {
  8168. this.offsetY = event.offsetY - this.dragRefOffset;
  8169. this.neighborItem = -1;
  8170. let indexA = this.songList.indexOf(item);
  8171. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  8172. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  8173. let value: number = 0;
  8174. if (this.offsetY < 0) {
  8175. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  8176. this.neighborItem = indexA - 1;
  8177. this.neighborScale = 1 - value / 20;
  8178. } else if (this.offsetY > 0) {
  8179. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  8180. this.neighborItem = indexA + 1;
  8181. this.neighborScale = 1 - value / 20;
  8182. }
  8183. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  8184. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8185. this.offsetY -= this.ITEM_INTV;
  8186. this.dragRefOffset += this.ITEM_INTV;
  8187. this.itemMoveSon(indexA, indexA + 1);
  8188. });
  8189. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  8190. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8191. this.offsetY += this.ITEM_INTV;
  8192. this.dragRefOffset -= this.ITEM_INTV;
  8193. this.itemMoveSon(indexA, indexA - 1);
  8194. });
  8195. }
  8196. })
  8197. .onActionEnd((event: GestureEvent) => {
  8198. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8199. this.dragItem = -1
  8200. this.neighborItem = -1
  8201. })
  8202. animateTo({
  8203. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  8204. }, () => {
  8205. this.scaleItem = -1
  8206. })
  8207. })
  8208. )
  8209. .onCancel(() => {
  8210. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8211. this.dragItem = -1
  8212. this.neighborItem = -1
  8213. })
  8214. animateTo({
  8215. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  8216. }, () => {
  8217. this.scaleItem = -1
  8218. })
  8219. })
  8220. ) //拖动List关键代码结束
  8221. .onClick(() => {
  8222. this.doPlay(item, index, true)
  8223. })
  8224. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  8225. }
  8226. .width('100%')
  8227. .height('100%')
  8228. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  8229. // .animation({ duration: 500, curve: Curve.Ease }))
  8230. .cachedCount(10)
  8231. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  8232. .gesture(PinchGesture({ fingers: 2 })
  8233. .onActionEnd((event: GestureEvent) => {
  8234. this.setSonListTwoFingers()
  8235. })
  8236. .onActionUpdate(e => {
  8237. this.scaleValue = this.pinchValue * e.scale
  8238. })
  8239. .onActionStart(e => {
  8240. }))
  8241. .padding({
  8242. bottom: 0
  8243. })
  8244. }
  8245. setSonListTwoFingers() {
  8246. this.pinchValue = this.scaleValue;
  8247. Logger.info('this.pinchValue = ' + this.pinchValue);
  8248. if (this.pinchValue >= 1) {
  8249. this.sonTwoFingerType++
  8250. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  8251. if (this.sonTwoFingerType > 3) {
  8252. this.sonTwoFingerType = 1
  8253. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  8254. }
  8255. } else {
  8256. this.sonTwoFingerType--
  8257. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  8258. if (this.sonTwoFingerType < 1) {
  8259. this.sonTwoFingerType = 1
  8260. }
  8261. }
  8262. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  8263. this.pinchValue = 1;
  8264. this.scaleValue = 1;
  8265. }
  8266. @State sonTwoFingerType:number = 3
  8267. @Builder
  8268. private MusicItemSon(item: VideoItem, index?: number) {
  8269. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8270. Row() {
  8271. Stack() {
  8272. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  8273. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  8274. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  8275. .alt($r('app.media.music_red'))
  8276. .fillColor(this.themeColor)
  8277. .borderRadius(this.isCoverRectangle?11:'100%')
  8278. .clip(true)
  8279. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  8280. .draggable(false)// 禁止长按手势拖动
  8281. .autoResize(true) // 重采样,可减少内存占用
  8282. .margin({ left: 20 })
  8283. }
  8284. .width('15%')
  8285. Column() {
  8286. Column() {
  8287. Text(this.isShowFileName?item.fileName :item.name)
  8288. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  8289. .fontColor(this.curIndex === index ? this.themeColor :
  8290. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  8291. .maxLines(1)
  8292. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  8293. Row() {
  8294. Column(){
  8295. Text(item.md5Str?.includes('Lossless')?
  8296. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  8297. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  8298. .padding({ top: 3,right:6,left:6,bottom:3 })
  8299. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  8300. $r('app.color.text_color'))
  8301. .fontWeight(500)
  8302. .borderRadius(12)
  8303. .visibility(StrUtil.isEmpty(item.md5Str) ? Visibility.None : Visibility.Visible)
  8304. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  8305. .backgroundColor('#FFC107')
  8306. }
  8307. .padding({ top: 8 })
  8308. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  8309. item.artist + ' ' + item?.duration)
  8310. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  8311. .padding({ top: 8 })
  8312. .maxLines(1)
  8313. .fontColor(this.curIndex === index ? this.themeColor :
  8314. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  8315. .margin({ left: StrUtil.isEmpty(item.md5Str)? 12 :this.sonTwoFingerType == 3 ? 5 : 3 })
  8316. Blank()
  8317. Text(item.size)
  8318. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  8319. .padding({ top: 8 })
  8320. .maxLines(1)
  8321. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  8322. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  8323. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  8324. .margin({ left: 10 })
  8325. }
  8326. }
  8327. .height('100%')
  8328. .width('100%')
  8329. .justifyContent(FlexAlign.Center)
  8330. .alignItems(HorizontalAlign.Start)
  8331. }
  8332. .height('100%')
  8333. .width('65%')
  8334. Column() {
  8335. ImageAnimator()
  8336. .images(this.imagesF)// 动画数组
  8337. .duration(1000)// 持续
  8338. .state(this.animationState)// 动画状态
  8339. .fillMode(FillMode.Forwards)
  8340. .width(18)
  8341. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  8342. Visibility.None)
  8343. .height(18)
  8344. .iterations(-1) // 播放次数
  8345. }
  8346. .width('20%')
  8347. }
  8348. }
  8349. .backgroundColor(Color.Transparent)
  8350. .width('100%')
  8351. .reuseId('son_item')
  8352. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  8353. .shadow(this.scaleItem === index ? {
  8354. radius: 70,
  8355. color: '#15000000',
  8356. offsetX: 0,
  8357. offsetY: 0
  8358. } :
  8359. {
  8360. radius: 0,
  8361. color: '#15000000',
  8362. offsetX: 0,
  8363. offsetY: 0
  8364. })
  8365. .animation({ curve: Curve.Sharp, duration: 300 })
  8366. }
  8367. @Builder
  8368. MusicPlayBuilder() {
  8369. Column() {
  8370. this.IjkMusicPlayerView()
  8371. }
  8372. .transition(TransitionEffect.asymmetric(
  8373. TransitionEffect.opacity(1),
  8374. TransitionEffect.OPACITY
  8375. ))
  8376. .visualEffect(deviceInfo.sdkApiVersion>=20&&this.bgController?
  8377. new hdsEffect.HdsEffectBuilder()
  8378. .shaderEffect({
  8379. effectType: hdsEffect.EffectType.UV_BACKGROUND_FLOW_LIGHT,
  8380. animation: {
  8381. duration: 10000,
  8382. iterations: -1,
  8383. autoPlay: true,
  8384. onFinish: ()=> {
  8385. console.info('Succeeded in finishing');
  8386. }
  8387. },
  8388. controller: this.bgController,
  8389. })
  8390. .buildEffect():null)
  8391. .height('100%')
  8392. .width('100%')
  8393. .onDisAppear(() => {
  8394. this.translateY = 0;
  8395. })
  8396. .translate({ y: this.translateY })
  8397. .gesture(
  8398. PanGesture(this.panOption)
  8399. .onActionUpdate((event?: GestureEvent) => {
  8400. if (event) {
  8401. // 只允许向下滑动,向上滑动时限制为0
  8402. this.translateY = Math.max(0, event.offsetY);
  8403. this.getUIContext().animateTo({
  8404. duration: 500,
  8405. curve: Curve.Sharp
  8406. }, () => {
  8407. this.scaleValueImage = Math.min(1, Math.max(0.5, 1 - event.offsetY / 600));
  8408. console.info('onecold scaleValueImage:', this.scaleValueImage)
  8409. this.scaleValueText =Math.min(1, Math.max(0.6, 1 - event.offsetY / 700));
  8410. })
  8411. }
  8412. })
  8413. .onActionEnd((event?: GestureEvent) => {
  8414. // 使用更低的阈值和滑动速度判断
  8415. const minDistance = 300; // 最小滑动距离 100vp
  8416. const minVelocity = 500; // 最小滑动速度
  8417. // 获取滑动速度(如果可用)
  8418. const velocity = event?.velocityY || 0;
  8419. // 判断是否应该关闭:距离足够 或者 速度足够快
  8420. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  8421. if (shouldClose) {
  8422. // 添加关闭动画
  8423. this.getUIContext().animateTo({
  8424. duration: 600,
  8425. curve: Curve.Friction
  8426. }, () => {
  8427. this.isShowPlay = false;
  8428. this.scaleValueImage = 1
  8429. this.scaleValueText = 1
  8430. this.translateY = 0;
  8431. })
  8432. } else {
  8433. // 回弹动画
  8434. this.getUIContext().animateTo({
  8435. duration: 600,
  8436. curve: Curve.Friction
  8437. }, () => {
  8438. this.scaleValueImage = 1
  8439. this.scaleValueText = 1
  8440. this.translateY = 0;
  8441. })
  8442. }
  8443. })
  8444. )
  8445. }
  8446. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  8447. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  8448. HeightBreakpoint.HEIGHT_LG;
  8449. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  8450. @State topBarHeight: number = 50
  8451. @State barOpacity: number = 1
  8452. @State barBottomOpacity: number = 1
  8453. private hideDone: boolean = false;
  8454. @State currentYOffset: number = 0;
  8455. @State bottomBarHeight: number = 68;
  8456. private isHiding: boolean = false;
  8457. //是否是Pura X外屏,或者小屏幕
  8458. isPuraWP() {
  8459. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  8460. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  8461. }
  8462. //是否是Pura X外屏,或者小屏幕,手机横屏
  8463. /**
  8464. * 是否是Pura X外屏,或者小屏幕,手机横屏
  8465. * @returns
  8466. */
  8467. isCoverOpacity() {
  8468. if (this.isPuraWP()) {
  8469. return true
  8470. }
  8471. if (this.isPhoneLan()) {
  8472. return true
  8473. }
  8474. if (deviceInfo.marketName.includes('Pura X')
  8475. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  8476. return true
  8477. }
  8478. return false
  8479. }
  8480. //是不是手机横屏
  8481. isPhoneLan() {
  8482. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  8483. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  8484. logHiCarWindow(`isPhoneLan width=${this.windowWidth}`);
  8485. logHiCarWindow(`isPhoneLan height=${this.windowHeight}`);
  8486. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarStatus=${this.isHiCarStatus}`);
  8487. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, curDisplayIsHiCar=${this.curDisplayIsHiCar}`);
  8488. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall=${this.isHiCarSmall()}`);
  8489. if (this.isHiCarKuanBianPing()) {
  8490. return true
  8491. }
  8492. if (this.isHiCar()) {
  8493. return false
  8494. }
  8495. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8496. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  8497. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  8498. return true
  8499. }
  8500. return false
  8501. }
  8502. //是不是1920x720的hicar的屏幕分辨率
  8503. isHiCarKuanBianPing(){
  8504. if(!this.isHiCar()){
  8505. return false
  8506. }
  8507. const hiCarAspectRatios: HiCarAspectRatio[] = [
  8508. { ratio: 1920 / 720, name: "1920x720" },
  8509. ];
  8510. const currentRatio: number = this.windowWidth / this.windowHeight;
  8511. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  8512. logHiCarWindow(`HiCarKuanBianPing currentRatio=${currentRatio}`)
  8513. for (const hiCarRatio of hiCarAspectRatios) {
  8514. logHiCarWindow(`HiCarKuanBianPing hiCarRatio=${hiCarRatio.ratio}`)
  8515. logHiCarWindow(`HiCarKuanBianPing diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  8516. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  8517. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  8518. //宽扁平的尺寸设置列表展示
  8519. this.twoFingerType ==3
  8520. this.isGridMusic = false
  8521. return true;
  8522. }
  8523. }
  8524. return false;
  8525. }
  8526. //是不是hicar的屏幕分辨率
  8527. isHiCarSmall() {
  8528. if(!this.isHiCar()){
  8529. return false
  8530. }
  8531. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  8532. {
  8533. this.columns = 6
  8534. return false
  8535. }
  8536. const hiCarAspectRatios: HiCarAspectRatio[] = [
  8537. { ratio: 800 / 480, name: "800x480" },
  8538. { ratio: 1280 / 720, name: "1280x720" },
  8539. { ratio: 1920 / 1080, name: "1920x1080" },
  8540. ];
  8541. const currentRatio: number = this.windowWidth / this.windowHeight;
  8542. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  8543. logHiCarWindow(`HiCarSmall currentRatio=${currentRatio}`)
  8544. for (const hiCarRatio of hiCarAspectRatios) {
  8545. logHiCarWindow(`HiCarSmall hiCarRatio=${hiCarRatio.ratio}`)
  8546. logHiCarWindow(`HiCarSmall diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  8547. logHiCarWindow(`HiCarSmall isHiCarStatus=${this.isHiCarStatus}`);
  8548. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  8549. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  8550. //宽扁平的尺寸设置列表展示
  8551. return true;
  8552. }
  8553. }
  8554. return false;
  8555. }
  8556. isHiCar() {
  8557. return this.curDisplayIsHiCar;
  8558. }
  8559. //是不是正常的手机竖屏
  8560. isPhonePortrait() {
  8561. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  8562. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  8563. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  8564. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8565. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  8566. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  8567. return true
  8568. }
  8569. return false
  8570. }
  8571. @State showSpeedDialog: boolean = false
  8572. @State longPressSpeed: number = 3 //长按默认倍数
  8573. @Builder
  8574. SpeedDialog() {
  8575. Stack() {
  8576. Column() {
  8577. Text('已切换至' + this.longPressSpeed + '倍速播放')
  8578. .fontColor(Color.White)
  8579. .visibility(Visibility.Hidden)
  8580. }
  8581. .backgroundColor(Color.Black)
  8582. .borderRadius(20)
  8583. .padding({
  8584. top: 10,
  8585. right: 20,
  8586. left: 15,
  8587. bottom: 20
  8588. })
  8589. .opacity(0.6)
  8590. Text('已切换至' + this.longPressSpeed + '倍速播放')
  8591. .fontColor(Color.White)
  8592. }
  8593. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  8594. .zIndex(5)
  8595. .margin({ top: 80 })
  8596. }
  8597. @Builder
  8598. IjkMusicPlayerView() {
  8599. Stack() {
  8600. if(canIUse("SystemCapability.UIDesign.HDSComponent.Core")
  8601. &&deviceInfo.sdkApiVersion>=20&&this.sceneBgController){
  8602. HdsVisualComponent()
  8603. .scene(HdsSceneType.DUAL_EDGE_FLOW_LIGHT_WITH_BACKGROUND_MASK, this.sceneBgController, () => {
  8604. console.info('Succeeded in finishing');
  8605. })
  8606. .width('100%')
  8607. .height('100%')
  8608. .visibility(this.isShowBgLiuGUANG?Visibility.Visible:Visibility.None)
  8609. }
  8610. Column() {
  8611. Column() {
  8612. //播放标题
  8613. Column() {
  8614. this.PlayTitle()
  8615. }
  8616. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  8617. .width('100%')
  8618. .margin({ top: 0 })
  8619. .height(PlayConstants.HEIGHT)
  8620. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  8621. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  8622. if (this.showSpeedDialog) {
  8623. this.SpeedDialog()
  8624. }
  8625. Stack() {
  8626. //手势拖动快进
  8627. Column()
  8628. .width(CommonConstants.FULL_PERCENT)
  8629. .height('100%')
  8630. .gesture(
  8631. GestureGroup(GestureMode.Parallel,
  8632. // 长按屏幕倍数播放
  8633. LongPressGesture({ repeat: true })
  8634. .onAction(() => {
  8635. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8636. this.showSpeedDialog = true;
  8637. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  8638. }
  8639. })
  8640. .onActionEnd(() => {
  8641. this.showSpeedDialog = false;
  8642. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  8643. }),
  8644. //双击屏幕暂停或者播放
  8645. TapGesture({ count: 2 })
  8646. .onAction((event: GestureEvent) => {
  8647. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8648. ToastUtil.showToast('已暂停')
  8649. }
  8650. console.info('onecold playOrPause 6693')
  8651. this.playOrPause()
  8652. })
  8653. )
  8654. )
  8655. }
  8656. .height('65%')
  8657. Swiper() {
  8658. this.CoverInfo()
  8659. this.PlayerLyrics()
  8660. }
  8661. .onChange((index: number) => {
  8662. this.currentSwiperIndex = index
  8663. })
  8664. .indicator(false)
  8665. .displayCount(new BreakpointType({
  8666. sm: 1,
  8667. md: 2,
  8668. lg: 2,
  8669. xl: 2,
  8670. xxl: 2
  8671. }).getValue(this.currentBreakpoint))
  8672. .clip(false)
  8673. .loop(false)
  8674. .autoPlay(false)
  8675. // .interval(8000)
  8676. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  8677. .height('100%')
  8678. .hitTestBehavior(HitTestMode.Transparent)
  8679. Image($r('app.media.icon_replay'))
  8680. .objectFit(ImageFit.Auto)
  8681. .width('120px')
  8682. .height('120px')
  8683. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  8684. .border({ width: 0 })
  8685. .visibility(Visibility.None)
  8686. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  8687. .onClick(() => {
  8688. console.info('onecold startPlayOrResumePlay 6744')
  8689. this.startPlayOrResumePlay();
  8690. })
  8691. }
  8692. .width(CommonConstants.FULL_PERCENT)
  8693. .height(CommonConstants.FULL_PERCENT)
  8694. .justifyContent(FlexAlign.End)
  8695. }
  8696. .justifyContent(FlexAlign.End)
  8697. .margin({ bottom: 8 })
  8698. }
  8699. .backgroundImage(!this.isMusicBGCover||StrUtil.isEmpty(this.cover)?null: this.cover)
  8700. .backgroundImageSize(this.isPuraWP()||!this.isMusicBGCover ? { width: '100%' } : { height: '150%', width: '100%' })
  8701. .animation({
  8702. duration: 666,
  8703. curve: 'ease-in-out' // 可选动画曲线
  8704. })
  8705. .backgroundBlurStyle((this.isPuraWP() && this.currentSwiperIndex === 0) ||!this.isMusicBGCover
  8706. ? BlurStyle.NONE :
  8707. BlurStyle.BACKGROUND_ULTRA_THICK)
  8708. .hitTestBehavior(HitTestMode.Transparent)
  8709. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  8710. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  8711. .onClick(() => {
  8712. if(this.isHiCar())
  8713. return
  8714. if(this.is_auto_hide_progress){
  8715. this.is_auto_hide_progress = false
  8716. }
  8717. this.startAutoHide()
  8718. })
  8719. }
  8720. @Consume progressValue: number ;
  8721. @State currentTime: string = "00:00";
  8722. @State totalTime: string = "00:00";
  8723. @State loadingVisible: Visibility = Visibility.None;
  8724. @State replayVisible: Visibility = Visibility.None;
  8725. @State slideEnable: boolean = false;
  8726. @State aspRatio: number = 0.5;
  8727. @State mContext: object | undefined = undefined;
  8728. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  8729. @State mFirst: boolean = true;
  8730. @State mDestroyPage: boolean = false;
  8731. @State playSpeed: number = 1;
  8732. @State oldSeconds: number = 0;
  8733. @State isSeekTo: boolean = false;
  8734. @State isCurrentTime: boolean = false;
  8735. @State videoWidth: string = '100%';
  8736. @State videoHeight: string = '100%';
  8737. @State initAspectRatio: number = 1;
  8738. @State videoAspectRatio: number = this.initAspectRatio;
  8739. @State videoUrl: string = '';
  8740. private last: number = 0;
  8741. @State videoParentAspectRatio: number = this.initAspectRatio;
  8742. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  8743. @Consume CONTROL_PlayStatus: number ;
  8744. @State PROGRESS_MAX_VALUE: number = 100;
  8745. @State updateProgressTimer: number = 0;
  8746. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  8747. @State name: string = '';
  8748. // @State loop: boolean = false;
  8749. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  8750. @State multiple: string = '1.0X';
  8751. xcomponentController: XComponentController = new XComponentController()
  8752. private panOptionBright: PanGestureOptions =
  8753. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  8754. private panOptionVolume: PanGestureOptions =
  8755. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  8756. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  8757. //手势的音量控制和亮度控制
  8758. private positionX: number = PlayConstants.POSITION_X;
  8759. private positionY: number = PlayConstants.POSITION_Y;
  8760. private windowClass: window.Window = globalThis.windowClass
  8761. @State volume: number = 0.5;
  8762. @State volumeSmall: boolean = false
  8763. @State autoParseMusicName: boolean = true
  8764. @State isShowFileName: boolean = false
  8765. @State isLongNameRoLL: boolean = true//长歌名滚动
  8766. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  8767. @State bright: number = PlayConstants.BRIGHT;
  8768. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  8769. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  8770. @State screenWidth: number = 0
  8771. @State screenHeight: number = 0
  8772. @State statusBarHeight: number = 0
  8773. @State isYesFull: boolean = false
  8774. private seekValue: number = 0
  8775. @State isVideoLock: boolean = false; // Whether the video playback is locked
  8776. eventHub = getContext().eventHub;
  8777. //投播组件
  8778. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  8779. private castController: avSession.AVCastController | undefined = undefined;
  8780. @State isCastPlaying: boolean = false;
  8781. @State currentTime2: number = 0;
  8782. @State currentStringTime: string = '00:00';
  8783. @State duration: number = 0;
  8784. @State isReady: boolean = false;
  8785. @State durationTime: number = 0;
  8786. @State durationStringTime: string = '00:00';
  8787. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  8788. // @State isPlaying: boolean = false;
  8789. private castSeek: boolean = false;
  8790. private castItem: avSession.AVQueueItem | undefined = undefined;
  8791. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  8792. @State rotateAngle2: number = -9
  8793. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  8794. @Consume cover: string | undefined ;
  8795. @State artist: string | undefined = ''
  8796. // 1.初始化controller
  8797. private lyricController: LyricController = new LyricController()
  8798. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  8799. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  8800. private parser = new LyricParser()
  8801. @State randomColor: string = 'rgb(0,0,0)'
  8802. @State randomShakenX: number = 0
  8803. @State randomShakenY: number = 0
  8804. @State lyricTextSize: number = 24
  8805. @State lyricContent: string = ''
  8806. @State isDebug: boolean = false
  8807. @State isHightLightCenter: boolean = true
  8808. /**
  8809. * 初始化歌词加载与展示逻辑
  8810. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  8811. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  8812. * @param isApi2 是否使用API2获取歌词(可选)
  8813. *
  8814. * 主要流程:
  8815. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  8816. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  8817. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  8818. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  8819. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  8820. * 6. 解析失败或读取失败时,清空歌词显示。
  8821. *
  8822. * 注意事项:
  8823. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  8824. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  8825. * - 歌词内容解析后通过lyricController驱动UI渲染。
  8826. */
  8827. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  8828. if (StrUtil.isEmpty(lyricPath)) {
  8829. return
  8830. }
  8831. this.initPipLyricSetting()
  8832. this.lyricControllerSingle
  8833. .setTextSize(15)
  8834. .setCacheSize(4)
  8835. .setTextColor("#FFFFFF")
  8836. .setHighlightColor("#FFFFFF")
  8837. .setHighlightScale(1.2)
  8838. .setEmptyHint("")
  8839. .setAlignMode('center')
  8840. .setAnimationDuration(500)
  8841. .setSingleLine(true)
  8842. this.lyricContent = ''
  8843. this.lyricController
  8844. .setTextSize(this.currentLyricSize)
  8845. .setCacheSize(4)
  8846. .setTextColor("#DDDDDD")
  8847. .setHighlightColor("#FFFFFF")
  8848. .setEmptyHint("")
  8849. .setAnimationDuration(1000)
  8850. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  8851. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  8852. this.setBlurDegree(this.blurDegree, false)
  8853. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  8854. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  8855. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  8856. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  8857. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  8858. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  8859. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  8860. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  8861. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  8862. this.lyricController.setTextWeight(this.lyricTextWeight)
  8863. this.showSingleLyric = false
  8864. this.timeOffset = 0
  8865. this.lyricController.setLyric(null)
  8866. this.lyricControllerSingle.setLyric(null)
  8867. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  8868. console.log("onecold lyricPath =" + lyricPath)
  8869. let neiqianLrc = ''
  8870. let lyContent = this.currentSong?.lyricContent
  8871. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  8872. neiqianLrc = lyContent
  8873. }
  8874. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast&&!isLocal&&!isLocal) {
  8875. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  8876. //赋值给this.lyricContent,播控中心才可以显示歌词
  8877. this.lyricContent = neiqianLrc
  8878. // 将文件内容按行分割成字符串数组
  8879. let lines = neiqianLrc.split('\n').map(line => line.trim());
  8880. // 3.解析歌词
  8881. let lyric = this.parser.parse(lines);
  8882. // 4.设置歌词
  8883. this.lyricController.setLyric(lyric);
  8884. this.lyricControllerXF.setLyric(lyric)
  8885. this.lyricControllerSingle.setLyric(lyric)
  8886. return
  8887. }
  8888. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  8889. && !Utility.isVideoByExtension(this.videoUrl))) {
  8890. if (this.currentSong !== undefined) {
  8891. // ToastUtil.showShort('正在为你搜索在线歌词!')
  8892. //判断是不是赞助会员,是会员的话才开启歌词功能
  8893. // if (!this.isDebug) {
  8894. // if (!Utility.isNoble()) {
  8895. // LogUtil.debug("onecold 不是赞助会员")
  8896. // return
  8897. // }
  8898. // if(!Utility.isPassInstallTime(33)){
  8899. // LogUtil.debug("onecold not pass time")
  8900. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  8901. // return
  8902. // }
  8903. // }
  8904. let artist = this.currentSong?.artist
  8905. if (artist === undefined) {
  8906. artist = ''
  8907. }
  8908. if (isApi2 === undefined) {
  8909. isApi2 = false
  8910. }
  8911. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  8912. // LogUtil.debug("onecold res =" + res)
  8913. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  8914. if (StrUtil.isNotEmpty(res)) {
  8915. this.lyricContent = res
  8916. let lines = res.split('\n').map(line => line.trim());
  8917. // 3.解析歌词
  8918. let lyric = this.parser.parse(lines);
  8919. // 4.设置歌词
  8920. this.lyricController.setLyric(lyric);
  8921. this.lyricControllerXF.setLyric(lyric)
  8922. this.lyricControllerSingle.setLyric(lyric)
  8923. this.showSingleLyric = true
  8924. // 4.保存歌词文件lyric到本地
  8925. //2025年8月28日歌词不再加密下载
  8926. this.saveDataToFile(res, lyricPath, false)
  8927. } else {
  8928. this.lyricController.setLyric(null)
  8929. this.lyricControllerXF.setLyric(null)
  8930. this.lyricControllerSingle.setLyric(null)
  8931. if (isOnLineAndToast) {
  8932. ToastUtil.showShort('未获取到歌词!')
  8933. }
  8934. }
  8935. } else {
  8936. this.lyricController.setLyric(null)
  8937. this.lyricControllerXF.setLyric(null)
  8938. this.lyricControllerSingle.setLyric(null)
  8939. if (isOnLineAndToast) {
  8940. ToastUtil.showShort('未获取到歌词!')
  8941. }
  8942. }
  8943. })
  8944. } else {
  8945. this.lyricController.setLyric(null)
  8946. this.lyricControllerXF.setLyric(null)
  8947. this.lyricControllerSingle.setLyric(null)
  8948. if (isOnLineAndToast) {
  8949. ToastUtil.showShort('未获取到歌词!')
  8950. }
  8951. }
  8952. return
  8953. }
  8954. try {
  8955. let isJiaMi = false;
  8956. let realLyricPath = lyricPath
  8957. if (FileUtil.accessSync(jiaMilyricPath)) {
  8958. isJiaMi = true
  8959. realLyricPath = jiaMilyricPath
  8960. console.info("onecold 找到加密本地歌词 ");
  8961. } else {
  8962. isJiaMi = false
  8963. realLyricPath = lyricPath
  8964. console.info("onecold 找到本地歌词 ");
  8965. }
  8966. // 3.读取文件内容并指定编码为 UTF-8
  8967. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  8968. const stat = await fileIo.stat(file.fd);
  8969. const arrayBuffer = new ArrayBuffer(stat.size);
  8970. fs.read(file.fd, arrayBuffer)
  8971. .then((readLen: number) => {
  8972. console.info("read file data succeed");
  8973. // let buf = buffer.from(arrayBuffer, 0, readLen);
  8974. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  8975. // 检查 buf 是否为空
  8976. if (buf.length === 0) {
  8977. throw new Error("Buffer is empty after reading the file");
  8978. }
  8979. try {
  8980. // 检测文件编码
  8981. // let detectedEncoding = chardet.detect(buf);
  8982. // console.info("onecoldT Detected encoding: " + detectedEncoding);
  8983. let detectedEncoding = this.detect(arrayBuffer)
  8984. console.info("onecoldT Detected encoding: " + detectedEncoding);
  8985. // 使用检测到的编码解码,解决中文乱码问题
  8986. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  8987. console.info("onecoldT Detected textDecoder: " + textDecoder);
  8988. let fileContent = textDecoder.decode(buf);
  8989. console.info(`onecoldT The content of file1: ${fileContent}`);
  8990. //解密
  8991. if (isJiaMi) {
  8992. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  8993. }
  8994. console.info(`onecold The content of file2: ${fileContent}`);
  8995. this.lyricContent = fileContent
  8996. if(isLocal){//编辑标签选择本地歌词需要赋值给this.lyricConStr
  8997. this.lyricConStr = fileContent
  8998. }
  8999. // 将文件内容按行分割成字符串数组
  9000. let lines = fileContent.split('\n').map(line => line.trim());
  9001. console.info(`onecold The content of file: ${fileContent}`);
  9002. // 3.解析歌词
  9003. let lyric = this.parser.parse(lines);
  9004. // 4.设置歌词
  9005. this.lyricController.setLyric(lyric);
  9006. this.lyricControllerXF.setLyric(lyric)
  9007. this.lyricControllerSingle.setLyric(lyric)
  9008. this.showSingleLyric = true
  9009. console.info(`The content of file: ${fileContent}`);
  9010. } catch (chardetError) {
  9011. console.error("chardet.detect failed with error: " + chardetError.message);
  9012. this.lyricController.setLyric(null);
  9013. this.lyricControllerXF.setLyric(null)
  9014. this.lyricControllerSingle.setLyric(null)
  9015. }
  9016. })
  9017. .catch((err: BusinessError) => {
  9018. this.lyricController.setLyric(null)
  9019. this.lyricControllerXF.setLyric(null)
  9020. this.lyricControllerSingle.setLyric(null)
  9021. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  9022. })
  9023. .catch((err: Error) => {
  9024. this.lyricController.setLyric(null)
  9025. this.lyricControllerXF.setLyric(null)
  9026. this.lyricControllerSingle.setLyric(null)
  9027. console.error("read file 2 data failed with error message: " + err.message);
  9028. })
  9029. .finally(() => {
  9030. fs.closeSync(file);
  9031. });
  9032. } catch (error) {
  9033. this.lyricController.setLyric(null)
  9034. this.lyricControllerSingle.setLyric(null)
  9035. this.lyricControllerXF.setLyric(null)
  9036. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  9037. }
  9038. }
  9039. detect(data: ArrayBuffer): string {
  9040. //创建检测对象
  9041. let detector: UniversalDetector = new UniversalDetector();
  9042. // 传入检测数据并实时判断编码格式
  9043. detector.handleData(data, 0, data.byteLength);
  9044. // 标记检测数据 读取结束
  9045. detector.dataEnd();
  9046. // 获取检测结果
  9047. let detected: string = detector.getDetectedCharset();
  9048. // 释放资源
  9049. detector.reset();
  9050. return detected;
  9051. }
  9052. //初始化悬浮歌词的自定义设置
  9053. initPipLyricSetting() {
  9054. this.lyricControllerXF
  9055. .setTextSize(this.currentLyricSize)
  9056. .setCacheSize(4)
  9057. .setTextColor("#DDDDDD")
  9058. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  9059. .setEmptyHint("")
  9060. .setAnimationDuration(1000)
  9061. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  9062. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  9063. this.setBlurDegree(this.blurDegreePip, true)
  9064. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  9065. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  9066. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  9067. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  9068. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  9069. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  9070. this.lyricControllerXF.setHightLightCenter(true)
  9071. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  9072. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  9073. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  9074. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  9075. if (this.pipBgIndex === 0) {
  9076. if (this.cover) {
  9077. this.pipBg = this.cover
  9078. } else {
  9079. this.pipBg = this.imageColor
  9080. }
  9081. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  9082. }
  9083. }
  9084. //根据item返回歌词内容
  9085. async getLyricContent(item: VideoItem): Promise<string> {
  9086. let neiqianLrc = ''
  9087. let lyContent = item?.lyricContent
  9088. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  9089. neiqianLrc = lyContent
  9090. return neiqianLrc
  9091. }
  9092. try {
  9093. //取数据库里面的歌词lyContent
  9094. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  9095. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  9096. console.log("onecold Lyrics:", lyricContent);
  9097. neiqianLrc = lyricContent
  9098. return neiqianLrc
  9099. }
  9100. } catch (error) {
  9101. console.error("Error fetching lyrics:", error);
  9102. }
  9103. try {
  9104. let filePath = item.filePath;
  9105. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  9106. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  9107. let isJiaMi = false;
  9108. let realLyricPath = lyricPath;
  9109. if (FileUtil.accessSync(jiaMilyricPath)) {
  9110. isJiaMi = true;
  9111. realLyricPath = jiaMilyricPath;
  9112. console.info("onecold 找到加密本地歌词");
  9113. } else {
  9114. console.info("onecold 找到本地歌词");
  9115. }
  9116. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  9117. const stat = await fileIo.stat(file.fd);
  9118. const arrayBuffer = new ArrayBuffer(stat.size);
  9119. const readLen = await fs.read(file.fd, arrayBuffer);
  9120. console.info("read file data succeed");
  9121. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  9122. if (buf.length === 0) {
  9123. throw new Error("Buffer is empty after reading the file");
  9124. }
  9125. // let detectedEncoding = chardet.detect(buf);
  9126. let detectedEncoding = this.detect(arrayBuffer)
  9127. console.info("Detected encoding: " + detectedEncoding);
  9128. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  9129. let fileContent = textDecoder.decode(buf);
  9130. console.info(`onecold The content of file1: ${fileContent}`);
  9131. if (isJiaMi) {
  9132. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  9133. }
  9134. console.info(`onecold The content of file2: ${fileContent}`);
  9135. fs.closeSync(file);
  9136. return fileContent;
  9137. } catch (error) {
  9138. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  9139. return '';
  9140. }
  9141. }
  9142. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  9143. if (StrUtil.isEmpty(filePath)) {
  9144. return
  9145. }
  9146. try {
  9147. //将content进行加密
  9148. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  9149. let lyricContent = ''
  9150. if (isJiaMi) {
  9151. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  9152. } else {
  9153. lyricContent = content
  9154. }
  9155. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  9156. // 清空文件内容
  9157. await fileIo.truncate(file.fd, 0);
  9158. await fileIo.write(file.fd, lyricContent);
  9159. await fileIo.close(file);
  9160. console.log('onecold lyric file Data saved successfully.');
  9161. } catch (error) {
  9162. console.error('onecold lyric file Failed to save data:', error);
  9163. }
  9164. }
  9165. // 定义开始旋转的方法
  9166. // 定时器用于一百毫秒执行一次旋转角度
  9167. @State timer: number = 0
  9168. @State rotateAngle: number = 0
  9169. //封面旋转动画
  9170. animationRoFun() {
  9171. if (this.isPlaying && !this.isCoverRectangle) {
  9172. this.timer = setInterval(() => {
  9173. this.rotateAngle += 1
  9174. }, 100)
  9175. this.startRotation()
  9176. } else {
  9177. clearInterval(this.timer)
  9178. this.stopRotation()
  9179. }
  9180. }
  9181. // 定义开始旋转的方法
  9182. startRotation() {
  9183. if (this.isPlaying) {
  9184. animateTo({
  9185. duration: 777,
  9186. iterations: 1,
  9187. curve: Curve.Linear
  9188. }, () => {
  9189. this.rotateAngle2 = -9
  9190. })
  9191. }
  9192. }
  9193. // 回调,暂停和播放按钮回调,下一首和上一首
  9194. playChange() {
  9195. // if(this.isCoverRectangle){
  9196. // return
  9197. // }
  9198. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  9199. this.setIsPlaying(true)
  9200. this.animationState = AnimationStatus.Running
  9201. } else {
  9202. this.setIsPlaying(false)
  9203. this.animationState = AnimationStatus.Paused
  9204. }
  9205. AppStorage.setOrCreate('animationState', this.animationState);
  9206. }
  9207. // 定义停止旋转的方法
  9208. stopRotation() {
  9209. if (this.isCoverRectangle) {
  9210. this.rotateAngle = 0
  9211. } else {
  9212. //唱针以左上角为点选择逆时针40度
  9213. animateTo({
  9214. duration: 1000,
  9215. curve: Curve.Linear,
  9216. iterations: 1,
  9217. }, () => {
  9218. this.rotateAngle2 = -45;
  9219. });
  9220. }
  9221. }
  9222. @Builder
  9223. private LyricsTopItem() {
  9224. Row() {
  9225. Stack() {
  9226. Image(this.cover)
  9227. .height(58)
  9228. .width(58)
  9229. .alt($r('app.media.alt'))
  9230. .borderRadius(8)
  9231. .clickEffect({ level: ClickEffectLevel.HEAVY })
  9232. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  9233. .shadow({
  9234. radius: 22,
  9235. type: ShadowType.BLUR,
  9236. color: 'on_primary'
  9237. })
  9238. }
  9239. .width('18%')
  9240. Column() {
  9241. Column() {
  9242. Text(this.name)
  9243. .fontSize(16)
  9244. .maxLines(1)
  9245. .fontWeight(FontWeight.Bolder)
  9246. .fontColor(this.currentLyricColor)
  9247. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  9248. Row() {
  9249. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  9250. .fontSize(13)
  9251. .fontWeight(FontWeight.Bold)
  9252. .padding({ top: 8 })
  9253. .fontColor(this.currentLyricColor)
  9254. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  9255. Blank()
  9256. }
  9257. }
  9258. .height('100%')
  9259. .width('100%')
  9260. .justifyContent(FlexAlign.Center)
  9261. .alignItems(HorizontalAlign.Start)
  9262. }
  9263. .height('100%')
  9264. .width('65%')
  9265. Column() {
  9266. Image($r('app.media.lyric'))
  9267. .width(28)
  9268. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9269. .margin({ right: 30 })
  9270. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9271. .onClick(() => {
  9272. this.isLyricSetting = !this.isLyricSetting;
  9273. })
  9274. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  9275. height: '95%',
  9276. dragBar: true,
  9277. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9278. showClose: true,
  9279. blurStyle: BlurStyle.Thin,
  9280. backgroundColor: Color.Transparent,
  9281. // title: { title: $r('app.string.lyric_setting') }
  9282. })
  9283. }
  9284. .width('18%')
  9285. }
  9286. .width('82%')
  9287. .height(58)
  9288. .justifyContent(FlexAlign.SpaceBetween)
  9289. }
  9290. //歌词显示
  9291. @Builder
  9292. PlayerLyrics() {
  9293. Column() {
  9294. Column() {
  9295. this.LyricsTopItem()
  9296. }
  9297. .height(this.isPuraWP() ? 15 : 58)
  9298. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  9299. Visibility.None : Visibility.Visible)
  9300. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  9301. .width("100%")
  9302. Column() {
  9303. LyricView2({
  9304. controller: this.lyricController,
  9305. enableSeek: true,
  9306. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  9307. seekLineColor: "#80ffffff", // 滑动定位线颜色
  9308. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  9309. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  9310. if (!this.isPlaying) {
  9311. console.info('onecold startPlayOrResumePlay 7527')
  9312. this.startPlayOrResumePlay()
  9313. }
  9314. else {
  9315. this.isSeekTo = true;
  9316. this.mDestroyPage = false;
  9317. this.showLoadIng();
  9318. this.seekTo(position + "");
  9319. this.isSeekTo = false;
  9320. }
  9321. return true
  9322. }
  9323. })
  9324. .width("100%")
  9325. .layoutWeight(1)
  9326. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  9327. if (this.isPhoneLan()) {
  9328. Column() {
  9329. this.playProgressView()
  9330. // this.playCenterView()
  9331. }
  9332. .margin({ bottom: 30, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  9333. }
  9334. }
  9335. .position({
  9336. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  9337. (this.isPuraWP() ? 58 : 99)
  9338. })
  9339. .justifyContent(FlexAlign.Center)
  9340. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  9341. }
  9342. }
  9343. @Builder
  9344. SingleLyricView() {
  9345. Column() {
  9346. Column() {
  9347. LyricView2({
  9348. controller: this.lyricControllerSingle,
  9349. enableSeek: false,
  9350. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  9351. seekLineColor: "#80ffffff", // 滑动定位线颜色
  9352. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  9353. })
  9354. }
  9355. .height(66)
  9356. .margin({ bottom: 20 })
  9357. }
  9358. }
  9359. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  9360. @Builder
  9361. BottomControl() {
  9362. Column() {
  9363. this.TopPlayProgressView()
  9364. //播放 暂停,下一首,上一首
  9365. this.playCenterView()
  9366. if(!this.curDisplayIsHiCar){
  9367. //播放进度条
  9368. this.BottomView()
  9369. }
  9370. }
  9371. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  9372. }
  9373. //播放控制上一首 下一首 暂停和播放
  9374. @Builder
  9375. playCenterView(){
  9376. Row() {
  9377. Button({type:ButtonType.Circle,stateEffect:true}){
  9378. //更多功能
  9379. Image($r('app.media.menu'))
  9380. .width(24)
  9381. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9382. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  9383. height: '99%',
  9384. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  9385. dragBar: true,
  9386. showClose: true,
  9387. blurStyle: BlurStyle.Thin,
  9388. backgroundColor: Color.Transparent,
  9389. })
  9390. }
  9391. .height(45)
  9392. .width(45)
  9393. .margin({ left: 5 })
  9394. .backgroundColor(Color.Transparent)
  9395. .onClick(() => {
  9396. this.isShowMoreView = !this.isShowMoreView;
  9397. })
  9398. Button({type:ButtonType.Circle,stateEffect:true}){
  9399. Image($r('app.media.ic_previous'))
  9400. .width(33)
  9401. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9402. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9403. }
  9404. .height(45)
  9405. .width(45)
  9406. .onClick(async () => {
  9407. await this.playPrevious()
  9408. })
  9409. .backgroundColor(Color.Transparent)
  9410. Button({type:ButtonType.Circle,stateEffect:true}){
  9411. Column() {
  9412. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  9413. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  9414. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  9415. .width(this.isPhoneLan()?45:55)
  9416. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9417. .fillColor(Color.White)
  9418. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9419. }
  9420. }
  9421. .onClick(async () => {
  9422. this.playOrPause()
  9423. })
  9424. .backgroundColor(Color.Transparent)
  9425. .layoutWeight(1)
  9426. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9427. Image($r('app.media.ic_next'))
  9428. .width(33)
  9429. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9430. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9431. }
  9432. .height(45)
  9433. .width(45)
  9434. .backgroundColor(Color.Transparent)
  9435. .onClick(async () => {
  9436. await this.playNext();
  9437. })
  9438. if(this.curDisplayIsHiCar){
  9439. this.playModeButton()
  9440. }else{
  9441. this.fullButton()
  9442. }
  9443. }
  9444. .width('95%')
  9445. .margin({ bottom:this.isCoverOpacity()?0:15 })
  9446. .justifyContent(FlexAlign.SpaceEvenly)
  9447. }
  9448. @Builder
  9449. TopPlayProgressView(){
  9450. Column() {
  9451. Row(){
  9452. Stack(){
  9453. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  9454. .fontColor([Color.White])
  9455. .fontSize(21)
  9456. .effectStrategy(1)
  9457. Text(this.fastForwardSeconds)
  9458. .fontColor(Color.White)
  9459. .fontSize(10)
  9460. .fontWeight(FontWeight.Bold)
  9461. }
  9462. .padding({left:12,bottom:6})
  9463. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  9464. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9465. .onClick(()=>{
  9466. this.backForward()
  9467. })
  9468. Slider({
  9469. value: this.progressValue,
  9470. min: 0,
  9471. max: this.PROGRESS_MAX_VALUE,
  9472. step: 1,
  9473. style: SliderStyle.InSet
  9474. })
  9475. .height(20)
  9476. .blockColor('rgba(255,255,255,1)')
  9477. .trackColor('rgba(255,255,255,0.3)')
  9478. .selectedColor(Color.White)
  9479. .trackThickness(4)
  9480. .showSteps(false)
  9481. .showTips(true)
  9482. .layoutWeight(1)
  9483. .enabled(this.slideEnable)
  9484. .onChange((value: number, mode: SliderChangeMode) => {
  9485. // if (mode == 2) {
  9486. this.isSeekTo = true;
  9487. this.mDestroyPage = false;
  9488. this.showLoadIng();
  9489. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  9490. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  9491. this.seekTo(seekValue + "");
  9492. // this.setProgress()
  9493. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  9494. this.isSeekTo = false;
  9495. // }
  9496. })
  9497. Stack(){
  9498. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  9499. .fontColor([Color.White])
  9500. .fontSize(21)
  9501. .effectStrategy(1)
  9502. Text(this.fastForwardSeconds)
  9503. .fontColor(Color.White)
  9504. .fontSize(10)
  9505. .fontWeight(FontWeight.Bold)
  9506. }
  9507. .padding({right:10,bottom:6})
  9508. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  9509. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9510. .onClick(()=>{
  9511. this.fastForward()
  9512. })
  9513. }
  9514. .justifyContent(FlexAlign.Center)
  9515. .padding({left:20,right:20})
  9516. .width(this.isLandscape?'88%':'95%')
  9517. Row() {
  9518. Text(this.currentTime)
  9519. .fontSize(10)
  9520. .fontColor(Color.White)
  9521. .margin({left:25})
  9522. Blank()
  9523. Text(this.totalTime)
  9524. .fontSize(10)
  9525. .fontColor(Color.White)
  9526. .margin({right:25})
  9527. }
  9528. .width(this.isLandscape?'85%':'90%')
  9529. .height(10)
  9530. }
  9531. .width('100%')
  9532. .alignItems(HorizontalAlign.Center)
  9533. }
  9534. @Builder
  9535. playModeButton(){
  9536. Button({type:ButtonType.Circle,stateEffect:true}){
  9537. Column() {
  9538. if (this.playType === 0) {
  9539. Image($r('app.media.loop'))
  9540. .width(27)
  9541. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9542. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9543. } else if (this.playType === 1) {
  9544. Image($r('app.media.single'))
  9545. .width(27)
  9546. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9547. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9548. } else if (this.playType === 2) {
  9549. Image($r('app.media.normal_play'))
  9550. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9551. .width(27)
  9552. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9553. } else if (this.playType === 3) {
  9554. Image($r('app.media.random'))
  9555. .width(27)
  9556. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9557. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9558. }
  9559. }
  9560. }
  9561. .layoutWeight(1)
  9562. .margin({ left: 5 })
  9563. .height(45)
  9564. .width(45)
  9565. .backgroundColor(Color.Transparent)
  9566. .onClick(async () => {
  9567. this.setLoopMode()
  9568. })
  9569. }
  9570. //播放进度条
  9571. @Builder
  9572. BottomView(){
  9573. Row() {
  9574. this.playModeButton()
  9575. if(this.currentSong){
  9576. Button({type:ButtonType.Circle,stateEffect:true}){
  9577. Column() {
  9578. Image($r('app.media.rename2'))
  9579. .width(21)
  9580. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9581. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9582. }
  9583. }
  9584. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  9585. height: '99%',
  9586. dragBar: true,
  9587. showClose: true,
  9588. preferType: SheetType.BOTTOM,
  9589. title: { title: '编辑标签' }
  9590. })
  9591. .height(45)
  9592. .width(45)
  9593. .layoutWeight(1)
  9594. .backgroundColor(Color.Transparent)
  9595. .onClick(async () => {
  9596. this.initEditFields(this.currentSong)
  9597. this.tempLyricContent = this.lyricContent
  9598. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  9599. this.lyricConStr = this.tempLyricContent
  9600. }
  9601. this.isShowEdit = !this.isShowEdit;
  9602. })
  9603. }
  9604. Button({type:ButtonType.Circle,stateEffect:true}){
  9605. Column() {
  9606. Image($r('app.media.lyric'))
  9607. .width(26)
  9608. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9609. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9610. }
  9611. }
  9612. .height(45)
  9613. .width(45)
  9614. .layoutWeight(1)
  9615. .backgroundColor(Color.Transparent)
  9616. .onClick(async () => {
  9617. this.isLyricSetting = !this.isLyricSetting;
  9618. })
  9619. //播放列表
  9620. Button({type:ButtonType.Circle,stateEffect:true}){
  9621. Image($r('app.media.hm_playlist'))
  9622. .width(24)
  9623. .fillColor(Color.White)
  9624. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9625. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9626. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  9627. height: '95%',
  9628. dragBar: true,
  9629. showClose: true,
  9630. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9631. blurStyle: BlurStyle.Thin,
  9632. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  9633. title: {
  9634. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  9635. + `(${this.songList.length}首)`
  9636. }
  9637. })
  9638. }
  9639. .layoutWeight(1)
  9640. .height(45)
  9641. .width(45)
  9642. .backgroundColor(Color.Transparent)
  9643. .onClick(() => {
  9644. this.isShowSheetView = !this.isShowSheetView;
  9645. if(this.isPlayListBgGrass){
  9646. this.isFrontWhite = true
  9647. }else{
  9648. this.isFrontWhite = false
  9649. }
  9650. this.scrollIndex()
  9651. })
  9652. }
  9653. .width(this.isLandscape?'88%':'95%')
  9654. .justifyContent(FlexAlign.SpaceAround)
  9655. .height(30)
  9656. .animation({
  9657. duration: 666,
  9658. curve: 'ease-in-out' // 可选动画曲线
  9659. })
  9660. }
  9661. @Builder
  9662. fullButton(){
  9663. Button({type:ButtonType.Circle,stateEffect:true}){
  9664. Column() {
  9665. Image($r('app.media.full_4'))
  9666. .width(25)
  9667. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9668. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9669. }
  9670. }
  9671. .layoutWeight(1)
  9672. .backgroundColor(Color.Transparent)
  9673. .height(45)
  9674. .width(45)
  9675. .onClick(async () => {
  9676. if (this.isLandscape) {
  9677. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  9678. } else {
  9679. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  9680. }
  9681. })
  9682. }
  9683. //旧版本播放进度条
  9684. @Builder
  9685. playProgressView() {
  9686. Row() {
  9687. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9688. Column() {
  9689. if (this.playType === 0) {
  9690. Image($r('app.media.loop'))
  9691. .width($r('app.float.control_image_width'))
  9692. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9693. } else if (this.playType === 1) {
  9694. Image($r('app.media.single'))
  9695. .width($r('app.float.control_image_width'))
  9696. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9697. } else if (this.playType === 2) {
  9698. Image($r('app.media.normal_play'))
  9699. .width($r('app.float.control_image_width'))
  9700. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9701. } else if (this.playType === 3) {
  9702. Image($r('app.media.random'))
  9703. .width($r('app.float.control_image_width'))
  9704. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9705. }
  9706. }
  9707. }
  9708. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  9709. .animation({
  9710. duration: 666,
  9711. curve: 'ease-in-out' // 可选动画曲线
  9712. })
  9713. .backgroundColor(Color.Transparent)
  9714. .margin({ right: 10 })
  9715. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9716. .onClick(async () => {
  9717. this.setLoopMode()
  9718. })
  9719. Text(this.currentTime)
  9720. .fontSize($r('app.float.slider_font_size'))
  9721. .fontColor(Color.White)
  9722. .margin(3)
  9723. Slider({
  9724. value: this.progressValue,
  9725. min: 0,
  9726. max: this.PROGRESS_MAX_VALUE,
  9727. step: 1,
  9728. style: SliderStyle.OutSet
  9729. })
  9730. .width('600px')
  9731. .blockColor('rgba(255,255,255,1)')
  9732. .trackColor('rgba(255,255,255,0.3)')
  9733. .selectedColor(Color.White)
  9734. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  9735. .layoutWeight(1)
  9736. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  9737. .showSteps(false)
  9738. .showTips(true)
  9739. .enabled(this.slideEnable)
  9740. .onChange((value: number, mode: SliderChangeMode) => {
  9741. // if (mode == 2) {
  9742. this.isSeekTo = true;
  9743. this.mDestroyPage = false;
  9744. this.showLoadIng();
  9745. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  9746. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  9747. this.seekTo(seekValue + "");
  9748. // this.setProgress()
  9749. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  9750. this.isSeekTo = false;
  9751. // }
  9752. })
  9753. Text(this.totalTime)
  9754. .fontSize($r('app.float.slider_font_size'))
  9755. .fontColor(Color.White)
  9756. .margin(3)
  9757. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  9758. //播放列表
  9759. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9760. Image($r('app.media.hm_playlist'))
  9761. .width($r('app.float.control_image_width'))
  9762. .fillColor(Color.White)
  9763. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9764. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  9765. height: '95%',
  9766. dragBar: true,
  9767. showClose: true,
  9768. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9769. blurStyle: BlurStyle.Thin,
  9770. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  9771. title: {
  9772. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  9773. + `(${this.songList.length}首)`
  9774. }
  9775. })
  9776. }
  9777. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  9778. .animation({
  9779. duration: 666,
  9780. curve: 'ease-in-out' // 可选动画曲线
  9781. })
  9782. .backgroundColor(Color.Transparent)
  9783. .margin({ right: 20, left: 10 })
  9784. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9785. .onClick(() => {
  9786. this.isShowSheetView = !this.isShowSheetView;
  9787. if (this.isPlayListBgGrass) {
  9788. this.isFrontWhite = true
  9789. } else {
  9790. this.isFrontWhite = false
  9791. }
  9792. this.scrollIndex()
  9793. })
  9794. }
  9795. //x5的竖屏模式需要99%
  9796. .width(this.isPhonePortrait() ? '93.4%'
  9797. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  9798. .height(this.isPhoneLan() ? 25 : 33)
  9799. .animation({
  9800. duration: 666,
  9801. curve: 'ease-in-out' // 可选动画曲线
  9802. })
  9803. }
  9804. isBigScreen() {
  9805. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  9806. return true
  9807. }
  9808. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  9809. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  9810. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  9811. return false
  9812. } else {
  9813. return true
  9814. }
  9815. return false
  9816. }
  9817. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  9818. @State isCoverRectangle: boolean = false
  9819. @State isCoverTop: boolean = true
  9820. // 添加控制缩放的状态变量
  9821. @State scaleValueImage: number = 1
  9822. @State scaleValueText: number = 1
  9823. @Builder
  9824. CoverInfo() {
  9825. Column() {
  9826. //如果是方形,判断是不是封面在顶部,如果不是顶部,显示musicNameInfo, 如果是圆形显示musicNameInfo
  9827. if (this.isCoverRectangle) {
  9828. if (!this.isCoverTop) {
  9829. this.musicNameInfo(false)
  9830. }
  9831. } else {
  9832. this.musicNameInfo(false)
  9833. }
  9834. Stack() {
  9835. // 唱片旋转效果
  9836. Image($r('app.media.ic_music_disc'))
  9837. .width(245)
  9838. .height(245)
  9839. .margin({ right: 20, left: 20 ,top:this.isCoverRectangle||this.isLandscape?0:43})
  9840. .aspectRatio(1)
  9841. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  9842. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  9843. .borderRadius('100%')
  9844. .align(Alignment.Center)
  9845. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  9846. .rotate({
  9847. angle: this.rotateAngle,
  9848. centerX: "50%",
  9849. centerY: "50%",
  9850. })
  9851. .animation({
  9852. duration: 100,
  9853. curve: Curve.Linear
  9854. })
  9855. .shadow({
  9856. radius: 22,
  9857. type: ShadowType.BLUR,
  9858. color: 'on_primary'
  9859. })
  9860. Column() {
  9861. if (this.isCoverTop && this.isCoverRectangle) {
  9862. Image(this.cover)
  9863. .height(this.isHiCar()?(px2vp(this.windowHeight)*0.43):
  9864. this.isCoverOpacity()?(px2vp(this.windowHeight)*0.54):'auto')
  9865. .width(this.isHiCar()||this.isCoverOpacity()?'auto':this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '88%')
  9866. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  9867. .alt($r('app.media.alt'))
  9868. .margin({ right: 8, left: 8, top: 8 })
  9869. .aspectRatio(1)
  9870. .geometryTransition('cover') // 绑定标识符
  9871. .opacity(this.opacityValueImage)
  9872. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  9873. // 设置左下角为缩放中心点
  9874. centerX: '0%',
  9875. centerY: '100%' })
  9876. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  9877. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  9878. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  9879. .clip(true)
  9880. .rotate({
  9881. x: 0,
  9882. y: 0,
  9883. z: 1,
  9884. angle: this.rotateAngle
  9885. })
  9886. .shadow({
  9887. radius: 22,
  9888. type: ShadowType.BLUR,
  9889. color: 'on_primary'
  9890. })
  9891. .onClick(() => {
  9892. this.isMusicBGCover = !this.isMusicBGCover
  9893. })
  9894. // .visualEffect(new hdsEffect.HdsEffectBuilder()
  9895. // .shaderEffect({
  9896. // effectType: hdsEffect.EffectType.DUAL_EDGE_FLOW_LIGHT,
  9897. // animation: {
  9898. // duration: 4000,
  9899. // iterations: -1,
  9900. // autoPlay: true,
  9901. // onFinish: () => {
  9902. // console.info('Succeeded in finishing');
  9903. // }
  9904. // },
  9905. // controller: this.controller,
  9906. // params: {
  9907. // firstEdgeFlowLight: {
  9908. // startPos: 0,
  9909. // endPos: 1.0,
  9910. // color: '#1AD0F1',
  9911. // },
  9912. // secondEdgeFlowLight: {
  9913. // startPos: 0.5,
  9914. // endPos: 1.5,
  9915. // color: '#FFA4E5',
  9916. // }
  9917. // }
  9918. // })
  9919. // .buildEffect())
  9920. this.musicNameInfo(false)
  9921. } else {
  9922. Image(this.cover)
  9923. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  9924. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 162))
  9925. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  9926. .alt($r('app.media.alt'))
  9927. .geometryTransition('cover') // 绑定标识符
  9928. .margin({ right: 20, left: 20,top:this.isCoverRectangle||this.isLandscape?0:43 })
  9929. .aspectRatio(1)
  9930. .opacity(this.opacityValueImage)
  9931. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  9932. // 设置左下角为缩放中心点
  9933. centerX: '0%',
  9934. centerY: '100%' })
  9935. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  9936. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  9937. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  9938. .align(Alignment.Center)//
  9939. .clip(true)
  9940. .shadow({
  9941. radius: 22,
  9942. type: ShadowType.BLUR,
  9943. color: 'on_primary'
  9944. })
  9945. .rotate({
  9946. x: 0,
  9947. y: 0,
  9948. z: 1,
  9949. angle: this.rotateAngle
  9950. })
  9951. .onClick(() => {
  9952. this.isMusicBGCover = !this.isMusicBGCover
  9953. })
  9954. }
  9955. if (this.isPhoneLan()) {
  9956. Text(this.name)
  9957. .fontSize(18)
  9958. .fontWeight(FontWeight.Bold)
  9959. .margin({ top: 13 })
  9960. .textOverflow({ overflow: TextOverflow.Ellipsis })
  9961. .maxLines(1)
  9962. .width('99%')
  9963. .textAlign(TextAlign.Center)
  9964. .fontColor(Color.White)
  9965. }
  9966. }
  9967. .width('100%')
  9968. // 唱针以左上角为点选择逆时针40度
  9969. Image($r('app.media.ic_music_cover_hand'))
  9970. .height(130)
  9971. .margin({ bottom: 220, top: 0 })
  9972. .align(Alignment.Top)
  9973. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  9974. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  9975. .visibility(this.isHiCar()||this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  9976. Column({ space: 8 }) {
  9977. Text(this.name)
  9978. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  9979. .fontWeight(FontWeight.Bold)
  9980. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9981. .maxLines(1)
  9982. .width('85%')
  9983. .textAlign(TextAlign.Center)
  9984. .fontColor(Color.White)
  9985. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  9986. Text(this.artist)
  9987. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  9988. .fontColor(Color.White)
  9989. .fontWeight(FontWeight.Bold)
  9990. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  9991. }
  9992. .justifyContent(FlexAlign.Start)
  9993. .zIndex(1)
  9994. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  9995. }
  9996. .margin({
  9997. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  9998. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  9999. top: this.isCoverOpacity() ? 0 : 20
  10000. })
  10001. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  10002. this.SingleLyricView()
  10003. }
  10004. if (this.isPhoneLan()) {
  10005. Column() {
  10006. this.playCenterView()
  10007. // this.playProgressView()
  10008. }
  10009. .position({ left: 28, bottom: 38 })
  10010. } else {
  10011. this.BottomControl()
  10012. }
  10013. }
  10014. .width(CommonConstants.FULL_PERCENT)
  10015. .clip(true)
  10016. }
  10017. @Builder
  10018. private musicNameInfo(isHidden: boolean) {
  10019. Row(){
  10020. Column({ space: 8 }) {
  10021. Text(this.name)
  10022. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 20)
  10023. .fontWeight(FontWeight.Bold)
  10024. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  10025. .maxLines(1)
  10026. .width('99%')
  10027. .textAlign(TextAlign.Start)
  10028. .fontColor(Color.White)
  10029. Text(this.artist + ' ' + this.currentSong?.album)
  10030. .fontSize(this.isCoverOpacity() ? 12 : 15)
  10031. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  10032. .fontColor(Color.White)
  10033. .textAlign(TextAlign.Start)
  10034. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  10035. .width('99%')
  10036. .maxLines(1)
  10037. }
  10038. .zIndex(1)
  10039. .layoutWeight(1)
  10040. .margin({ left: 15 })
  10041. Blank()
  10042. Row(){
  10043. Button({type:ButtonType.Circle,stateEffect:true}){
  10044. //添加或取消收藏
  10045. SymbolGlyph(Utility.getIsFav(this.favList,this.currentSong)?
  10046. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'))
  10047. .fontSize(22)
  10048. .fontColor([Color.White])
  10049. .alignSelf(ItemAlign.Center)
  10050. // .width(24)
  10051. .clickEffect({level:ClickEffectLevel.MIDDLE})
  10052. .aspectRatio(CommonConstants.ASPECT_RATIO)
  10053. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  10054. .onClick(async () => {
  10055. if(this.currentSong){
  10056. this.doFav(this.currentSong)
  10057. }
  10058. })
  10059. }
  10060. .margin({ left: 8,right:8 })
  10061. .backgroundColor(Color.Transparent)
  10062. .width(45)
  10063. .height(45)
  10064. }
  10065. }
  10066. .width(this.isLandscape?'83%':'90%')
  10067. .scale({ x: this.scaleValueText, y: this.scaleValueText }) // 添加缩放效果
  10068. .margin({ top:this.isCoverTop?10: 15 })
  10069. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  10070. }
  10071. @Builder
  10072. private PlayTitle() {
  10073. Row() {
  10074. Row() {
  10075. Image($r('app.media.ic_back_down'))
  10076. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  10077. .hitTestBehavior(HitTestMode.Transparent)
  10078. Text(this.name + ' ' + this.artist)
  10079. .fontColor(Color.White)
  10080. .fontSize($r('app.float.title_font_size'))
  10081. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  10082. .maxLines(1)
  10083. .visibility(Visibility.None)
  10084. .margin({ left: 2, right: 30 })
  10085. }
  10086. .layoutWeight(1)
  10087. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10088. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  10089. .onClick(() => {
  10090. this.setShowPlayFalse()
  10091. })
  10092. Column() {
  10093. AVCastPicker({
  10094. normalColor: Color.White,
  10095. onStateChange: this.onStateVastChange
  10096. })
  10097. .width(24)
  10098. .height(24)
  10099. }
  10100. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  10101. }
  10102. .width(PlayConstants.ROW_WIDTH)
  10103. }
  10104. @Builder
  10105. lyricSettingSheet(isPip: boolean) {
  10106. Scroll() {
  10107. this.lyricSetting(isPip)
  10108. }
  10109. .width('100%')
  10110. .height('100%')
  10111. }
  10112. @Builder
  10113. lyricSetting(isPip: boolean) {
  10114. Column() {
  10115. // 时间调节模块
  10116. if (!isPip) {
  10117. this.BuildTimeControls()
  10118. }
  10119. // 字号控制模块
  10120. this.BuildFontControls(isPip)
  10121. }
  10122. }
  10123. // 歌词时间偏移状态
  10124. @State timeOffset: number = 0.0
  10125. @State currentLyricColor: string = '#FFFFFF'
  10126. @State currentLyricColorPip: string = '#FFFFFF'
  10127. @State currentHighLightLyricColor: string = '#FF4081'
  10128. @State currentHighLightLyricColorPip: string = '#FF4081'
  10129. // 歌词字号状态
  10130. @State currentLyricSize: number = 20
  10131. @State currentLyricSizePip: number = 20
  10132. // 高亮歌词放大倍数
  10133. @State currentHightLyricSize: number = 1.2
  10134. @State currentHightLyricSizePip: number = 1.2
  10135. @State currentLyricLineSpace: number = 10
  10136. @State currentLyricLineSpacePip: number = 10
  10137. @State currentLyricAlignMode: number = 1
  10138. @State currentLyricAlignModePip: number = 1
  10139. @State blurDegree: number = 2
  10140. @State blurDegreePip: number = 2
  10141. @State isShowSelectColor: boolean = false
  10142. @State isShowHLSelectColor: boolean = false
  10143. @State isShowPipBgSelectColor: boolean = false
  10144. @State pipLyWidth: number = 330
  10145. @State pipLyHeight: number = 120
  10146. // 构建颜色选择器
  10147. @Builder
  10148. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  10149. Row({ space: 10 }) {
  10150. HSBColorPicker({
  10151. color: '#FFFFFF',
  10152. radius: 8,
  10153. layout: HSBColorPickerLayout.COLUMN,
  10154. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  10155. '#fa7105'],
  10156. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  10157. this.changeLyricColor(value, isPip, isBGPip)
  10158. })
  10159. .height(250)
  10160. .layoutWeight(1)
  10161. .padding(25)
  10162. }
  10163. .width('66%')
  10164. }
  10165. @State isOpenPip: boolean = false
  10166. @State pipBgIndex: number = 0
  10167. // 构建字号控制器
  10168. @Builder
  10169. BuildFontControls(isPip: boolean) {
  10170. Column() {
  10171. if (isPip) {
  10172. Column() {
  10173. Row() {
  10174. Text('悬浮歌词')
  10175. .margin({ left: 18 })
  10176. .fontSize(15)
  10177. .fontColor(Color.White)
  10178. .fontWeight(480)
  10179. .layoutWeight(1)
  10180. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  10181. .selectedColor(this.themeColor)
  10182. .switchPointColor(Color.White)
  10183. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10184. .margin({ right: 18 })
  10185. .onChange((checked: boolean) => {
  10186. this.isOpenPip = checked;
  10187. if (this.isOpenPip) {
  10188. this.startPip()
  10189. } else {
  10190. this.stopPip()
  10191. }
  10192. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  10193. })
  10194. .width(50)
  10195. .height(30);
  10196. }
  10197. .height(55)
  10198. }
  10199. .backgroundColor(Color.Transparent)
  10200. .borderRadius(15)
  10201. .margin({
  10202. left: 30,
  10203. right: 30,
  10204. top: 0,
  10205. bottom: 20
  10206. })
  10207. .padding(0)
  10208. .border({
  10209. color: Color.White,
  10210. width: 1.8
  10211. })
  10212. }else{
  10213. Column() {
  10214. Row() {
  10215. Text('单行歌词')
  10216. .margin({ left: 18 })
  10217. .fontSize(15)
  10218. .fontColor(Color.White)
  10219. .fontWeight(480)
  10220. .layoutWeight(1)
  10221. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  10222. .selectedColor(this.themeColor)
  10223. .switchPointColor(Color.White)
  10224. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10225. .margin({ right: 18 })
  10226. .onChange((checked: boolean) => {
  10227. this.isShowSingleLineLyric = checked;
  10228. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  10229. })
  10230. .width(50)
  10231. .height(30);
  10232. }
  10233. .height(55)
  10234. }
  10235. .backgroundColor(Color.Transparent)
  10236. .borderRadius(15)
  10237. .margin({
  10238. left: 30,
  10239. right: 30,
  10240. top: 10,
  10241. bottom: 10
  10242. })
  10243. .padding(0)
  10244. .border({
  10245. color: Color.White,
  10246. width: 1.8
  10247. })
  10248. }
  10249. Row() {
  10250. Text(`歌词居中:`)
  10251. .fontSize(14)
  10252. .fontColor(Color.White)
  10253. .margin({ left: 2 })
  10254. Row() {
  10255. ForEach(['居中', '居左'], (size: string, index: number) => {
  10256. Button(size)
  10257. .width(60)
  10258. .height(28)
  10259. .fontSize(12)
  10260. .fontColor('#FFFFFF')
  10261. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  10262. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  10263. .border({
  10264. color: (!isPip && this.currentLyricAlignMode === index) ||
  10265. (isPip && this.currentLyricAlignModePip === index) ?
  10266. '#007DFF' : '#DDDDDD',
  10267. width: 1.8
  10268. })
  10269. .onClick(() => {
  10270. this.setLyricAlignMode(index, isPip)
  10271. })
  10272. .margin({ left: 10, right: 8 })
  10273. })
  10274. }
  10275. .width('76%')
  10276. Blank()
  10277. }
  10278. .margin({
  10279. top: 10,
  10280. bottom: 10,
  10281. right: 20,
  10282. left: 20
  10283. })
  10284. if (isPip) {
  10285. Row() {
  10286. Text(`悬浮背景:`)
  10287. .fontSize(14)
  10288. .fontColor(Color.White)
  10289. Select([
  10290. { value: CommonConstants.PIP_LYRIC_BG[0] },
  10291. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  10292. .font({ size: 13, weight: FontWeight.Medium })
  10293. .fontColor(Color.White)
  10294. .margin({ left: 10 })
  10295. .selected(this.pipBgIndex)
  10296. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  10297. .onSelect(async (_index: number, text?: string | undefined) => {
  10298. this.pipBgIndex = _index
  10299. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  10300. if (this.pipBgIndex === 0) {
  10301. if (this.cover) {
  10302. this.pipBg = this.cover
  10303. } else {
  10304. this.pipBg = this.imageColor
  10305. }
  10306. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  10307. } else {
  10308. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  10309. }
  10310. })
  10311. Column() {
  10312. }
  10313. .backgroundColor(this.pipBg)
  10314. .margin({ left: 10, right: 10 })
  10315. .borderRadius(20)
  10316. .height(28)
  10317. .width(28)
  10318. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10319. Row() {
  10320. SymbolGlyph($r('sys.symbol.paintbrush'))
  10321. .fontColor([Color.White])
  10322. .effectStrategy(1)
  10323. Text(`选择颜色`)
  10324. .fontSize(13)
  10325. .margin({ left: 10 })
  10326. .fontColor(Color.White)
  10327. }
  10328. }
  10329. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  10330. .backgroundColor(Color.Transparent)
  10331. .border({
  10332. color: '#FFFFFF',
  10333. radius: 20,
  10334. width: 1.8
  10335. })
  10336. .height(36)
  10337. .width(110)
  10338. .onClick(() => {
  10339. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  10340. })
  10341. .bindPopup(this.isShowPipBgSelectColor, {
  10342. builder: this.SelectColor(false, isPip, true),
  10343. placement: Placement.Top,
  10344. mask: { color: '#33000000' },
  10345. enableArrow: false, //是否显示箭头
  10346. showInSubWindow: false,
  10347. onStateChange: (e) => {
  10348. if (!e.isVisible) {
  10349. this.isShowPipBgSelectColor = false
  10350. }
  10351. }
  10352. })
  10353. }
  10354. .width('76%')
  10355. .margin({ bottom: 5, right: 45, left: 20 })
  10356. }
  10357. if (!isPip) {
  10358. Row() {
  10359. Text(`高亮居中:`)
  10360. .fontSize(14)
  10361. .fontColor(Color.White)
  10362. Column() {
  10363. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  10364. .selectedColor(this.themeColor)
  10365. .switchPointColor(Color.White)
  10366. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10367. .onChange((checked: boolean) => {
  10368. this.isHightLightCenter = checked;
  10369. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  10370. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  10371. })
  10372. .width(50)
  10373. .height(30)
  10374. .alignSelf(ItemAlign.Start)
  10375. .margin({ left: 12 })
  10376. Blank()
  10377. }
  10378. .width('76%')
  10379. }
  10380. .margin({
  10381. left: 20,
  10382. right: 15,
  10383. top: 10,
  10384. bottom: 10
  10385. })
  10386. }
  10387. Row() {
  10388. Text(`歌词颜色:`)
  10389. .fontSize(14)
  10390. .fontColor(Color.White)
  10391. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  10392. .fontSize(15)
  10393. .fontColor(Color.White)
  10394. .margin({ left: 12, right: 12 })
  10395. Column() {
  10396. }
  10397. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  10398. .margin({ right: 12 })
  10399. .borderRadius(20)
  10400. .height(28)
  10401. .width(28)
  10402. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10403. Row() {
  10404. SymbolGlyph($r('sys.symbol.paintbrush'))
  10405. .fontColor([Color.White])
  10406. .effectStrategy(1)
  10407. Text(`选择颜色`)
  10408. .fontSize(13)
  10409. .margin({ left: 10 })
  10410. .fontColor(Color.White)
  10411. }
  10412. }
  10413. .backgroundColor(Color.Transparent)
  10414. .border({
  10415. color: '#FFFFFF',
  10416. radius: 20,
  10417. width: 1.8
  10418. })
  10419. .height(36)
  10420. .width(110)
  10421. .onClick(() => {
  10422. this.isShowSelectColor = !this.isShowSelectColor
  10423. })
  10424. .bindPopup(this.isShowSelectColor, {
  10425. builder: this.SelectColor(false, isPip),
  10426. placement: Placement.Top,
  10427. mask: { color: '#33000000' },
  10428. enableArrow: false, //是否显示箭头
  10429. showInSubWindow: false,
  10430. onStateChange: (e) => {
  10431. if (!e.isVisible) {
  10432. this.isShowSelectColor = false
  10433. }
  10434. }
  10435. })
  10436. }
  10437. .width('76%')
  10438. .margin({
  10439. top: 10,
  10440. bottom: 10,
  10441. right: 45,
  10442. left: 20
  10443. })
  10444. Row() {
  10445. Text(`高亮颜色:`)
  10446. .fontSize(14)
  10447. .fontColor(Color.White)
  10448. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  10449. .fontSize(15)
  10450. .fontColor(Color.White)
  10451. .margin({ left: 12, right: 12 })
  10452. Column() {
  10453. }
  10454. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  10455. .margin({ right: 12 })
  10456. .borderRadius(20)
  10457. .height(28)
  10458. .width(28)
  10459. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10460. Row() {
  10461. SymbolGlyph($r('sys.symbol.paintbrush'))
  10462. .fontColor([Color.White])
  10463. .effectStrategy(1)
  10464. Text(`选择颜色`)
  10465. .fontSize(13)
  10466. .margin({ left: 10 })
  10467. .fontColor(Color.White)
  10468. }
  10469. }
  10470. .backgroundColor(Color.Transparent)
  10471. .border({
  10472. color: '#FFFFFF',
  10473. radius: 20,
  10474. width: 1.8
  10475. })
  10476. .height(36)
  10477. .width(110)
  10478. .onClick(() => {
  10479. this.isShowHLSelectColor = !this.isShowHLSelectColor
  10480. })
  10481. .bindPopup(this.isShowHLSelectColor, {
  10482. builder: this.SelectColor(true, isPip),
  10483. placement: Placement.Top,
  10484. mask: { color: '#33000000' },
  10485. enableArrow: false, //是否显示箭头
  10486. showInSubWindow: false,
  10487. onStateChange: (e) => {
  10488. if (!e.isVisible) {
  10489. this.isShowHLSelectColor = false
  10490. }
  10491. }
  10492. })
  10493. }
  10494. .width('76%')
  10495. .margin({
  10496. top: 10,
  10497. bottom: 10,
  10498. right: 45,
  10499. left: 20
  10500. })
  10501. if (isPip) {
  10502. Row() {
  10503. Text(`显示宽度:`)
  10504. .fontSize(14)
  10505. .fontColor(Color.White)
  10506. Slider({
  10507. value: this.pipLyWidth,
  10508. min: 10,
  10509. max: 800,
  10510. step: 1,
  10511. style: SliderStyle.OutSet
  10512. })
  10513. .blockColor(this.themeColor)
  10514. .trackColor($r('app.color.speed_text_color'))
  10515. .selectedColor(Color.White)
  10516. .trackThickness(6)
  10517. .onChange((value: number) => {
  10518. this.pipLyWidth = value
  10519. if (this.pipController) {
  10520. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10521. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  10522. }
  10523. })
  10524. .width('76%')
  10525. }
  10526. .margin({
  10527. left: 20,
  10528. right: 15,
  10529. top: 5,
  10530. bottom: 5
  10531. })
  10532. Row() {
  10533. Text(`显示高度:`)
  10534. .fontSize(14)
  10535. .fontColor(Color.White)
  10536. Slider({
  10537. value: this.pipLyHeight,
  10538. min: 10,
  10539. max: 1000,
  10540. step: 1,
  10541. style: SliderStyle.OutSet
  10542. })
  10543. .blockColor(this.themeColor)
  10544. .trackColor($r('app.color.speed_text_color'))
  10545. .selectedColor(Color.White)
  10546. .trackThickness(6)
  10547. .onChange((value: number) => {
  10548. this.pipLyHeight = value
  10549. if (this.pipController) {
  10550. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10551. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  10552. }
  10553. })
  10554. .width('76%')
  10555. }
  10556. .margin({
  10557. left: 20,
  10558. right: 15,
  10559. top: 5,
  10560. bottom: 5
  10561. })
  10562. }
  10563. Row() {
  10564. Text(`歌词字号:`)
  10565. .fontSize(14)
  10566. .fontColor(Color.White)
  10567. Slider({
  10568. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  10569. min: 12,
  10570. max: 30,
  10571. step: 0.1,
  10572. style: SliderStyle.OutSet
  10573. })
  10574. .blockColor(this.themeColor)
  10575. .trackColor($r('app.color.speed_text_color'))
  10576. .selectedColor(Color.White)
  10577. .trackThickness(6)
  10578. .onChange((value: number) => {
  10579. this.setLyricTextSize(value, isPip)
  10580. })
  10581. .width('76%')
  10582. }
  10583. .margin({
  10584. left: 20,
  10585. right: 15,
  10586. top: 5,
  10587. bottom: 5
  10588. })
  10589. Row() {
  10590. Text(`高亮倍数:`)
  10591. .fontSize(14)
  10592. .fontColor(Color.White)
  10593. Slider({
  10594. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  10595. min: 1,
  10596. max: 2,
  10597. step: 0.1,
  10598. style: SliderStyle.OutSet
  10599. })
  10600. .blockColor(this.themeColor)
  10601. .trackColor($r('app.color.speed_text_color'))
  10602. .selectedColor(Color.White)
  10603. .trackThickness(6)
  10604. .onChange((value: number) => {
  10605. this.setHighLyricTextSize(value, isPip)
  10606. })
  10607. .width('76%')
  10608. }
  10609. .margin({
  10610. left: 20,
  10611. right: 15,
  10612. top: 5,
  10613. bottom: 5
  10614. })
  10615. Row() {
  10616. Text(`歌词间隙:`)
  10617. .fontSize(14)
  10618. .fontColor(Color.White)
  10619. Slider({
  10620. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  10621. min: 0,
  10622. max: 100,
  10623. step: 1,
  10624. style: SliderStyle.OutSet
  10625. })
  10626. .blockColor(this.themeColor)
  10627. .trackColor($r('app.color.speed_text_color'))
  10628. .selectedColor(Color.White)
  10629. .trackThickness(6)
  10630. .onChange((value: number) => {
  10631. this.setLyricLineSpace(value, isPip)
  10632. })
  10633. .width('76%')
  10634. }
  10635. .margin({
  10636. left: 20,
  10637. right: 15,
  10638. top: 5,
  10639. bottom: 5
  10640. })
  10641. //取值间隔为100,默认为400,取值越大,字体越粗
  10642. Row() {
  10643. Text(`歌词字重:`)
  10644. .fontSize(14)
  10645. .fontColor(Color.White)
  10646. Slider({
  10647. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  10648. min: 100,
  10649. max: 900,
  10650. step: 100,
  10651. style: SliderStyle.OutSet
  10652. })
  10653. .blockColor(this.themeColor)
  10654. .trackColor($r('app.color.speed_text_color'))
  10655. .selectedColor(Color.White)
  10656. .trackThickness(6)
  10657. .onChange((value: number) => {
  10658. if (isPip) {
  10659. this.lyricTextWeightPip = value
  10660. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  10661. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  10662. } else {
  10663. this.lyricTextWeight = value
  10664. this.lyricController.setTextWeight(this.lyricTextWeight)
  10665. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  10666. }
  10667. })
  10668. .width('76%')
  10669. }
  10670. .margin({
  10671. left: 20,
  10672. right: 15,
  10673. top: 5,
  10674. bottom: 5
  10675. })
  10676. if (!isPip) {
  10677. Row() {
  10678. Text(`歌词模糊:`)
  10679. .fontSize(14)
  10680. .fontColor(Color.White)
  10681. Slider({
  10682. value: isPip ? this.blurDegreePip : this.blurDegree,
  10683. min: 0,
  10684. max: 5,
  10685. step: 0.1,
  10686. style: SliderStyle.OutSet
  10687. })
  10688. .blockColor(this.themeColor)
  10689. .trackColor($r('app.color.speed_text_color'))
  10690. .selectedColor(Color.White)
  10691. .trackThickness(6)
  10692. .onChange((value: number) => {
  10693. this.setBlurDegree(value, isPip)
  10694. })
  10695. .width('76%')
  10696. }
  10697. .margin({
  10698. left: 20,
  10699. right: 15,
  10700. top: 5,
  10701. bottom: 15
  10702. })
  10703. }
  10704. Row() {
  10705. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  10706. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  10707. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  10708. }
  10709. .justifyContent(FlexAlign.Center)
  10710. .margin({ top: 3, bottom: 10 })
  10711. }
  10712. }
  10713. private setBlurDegree(index: number, isPip: boolean) {
  10714. if (isPip) {
  10715. this.blurDegreePip = index
  10716. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  10717. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  10718. } else {
  10719. this.blurDegree = index
  10720. this.lyricController.setBlurDegree(this.blurDegree)
  10721. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  10722. }
  10723. }
  10724. private setLyricAlignMode(index: number, isPip: boolean) {
  10725. if (isPip) {
  10726. this.currentLyricAlignModePip = index
  10727. if (this.currentLyricAlignModePip === 1) {
  10728. this.lyricControllerXF.setAlignMode("left")
  10729. } else {
  10730. this.lyricControllerXF.setAlignMode("center")
  10731. }
  10732. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  10733. } else {
  10734. this.currentLyricAlignMode = index
  10735. if (this.currentLyricAlignMode === 1) {
  10736. this.lyricController.setAlignMode("left")
  10737. } else {
  10738. this.lyricController.setAlignMode("center")
  10739. }
  10740. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  10741. }
  10742. }
  10743. private setLyricTextSize(index: number, isPip: boolean) {
  10744. if (isPip) {
  10745. this.currentLyricSizePip = index
  10746. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  10747. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  10748. } else {
  10749. this.currentLyricSize = index
  10750. this.lyricController.setTextSize(this.currentLyricSize)
  10751. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  10752. }
  10753. }
  10754. private setHighLyricTextSize(scale: number, isPip: boolean) {
  10755. if (isPip) {
  10756. this.currentHightLyricSizePip = scale
  10757. this.lyricControllerXF
  10758. .setHighlightScale(this.currentHightLyricSizePip)
  10759. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  10760. } else {
  10761. this.currentHightLyricSize = scale
  10762. this.lyricController
  10763. .setHighlightScale(this.currentHightLyricSize)
  10764. PreferencesUtil.putSync('HighLyricTextSize', scale)
  10765. }
  10766. }
  10767. private setLyricLineSpace(index: number, isPip: boolean) {
  10768. if (isPip) {
  10769. this.currentLyricLineSpacePip = index
  10770. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  10771. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  10772. } else {
  10773. this.currentLyricLineSpace = index
  10774. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  10775. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  10776. }
  10777. }
  10778. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  10779. LogUtil.info('onecold isBG = ' + isBG)
  10780. if (isBG) { //如果是设置悬浮背景
  10781. this.pipBg = color
  10782. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  10783. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  10784. return
  10785. }
  10786. if (isPip) {
  10787. this.currentLyricColorPip = color
  10788. this.lyricControllerXF
  10789. .setTextColor(this.currentLyricColorPip)
  10790. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  10791. } else {
  10792. this.currentLyricColor = color
  10793. this.lyricController
  10794. .setTextColor(this.currentLyricColor)
  10795. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  10796. }
  10797. }
  10798. private changeLyricHightLightColor(color: string, isPip: boolean) {
  10799. if (isPip) {
  10800. this.currentHighLightLyricColorPip = color
  10801. this.lyricControllerXF
  10802. .setHighlightColor(this.currentHighLightLyricColorPip)
  10803. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  10804. } else {
  10805. this.currentHighLightLyricColor = color
  10806. this.lyricController
  10807. .setHighlightColor(this.currentHighLightLyricColor)
  10808. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  10809. }
  10810. }
  10811. // 构建时间控制器
  10812. @Builder
  10813. BuildTimeControls() {
  10814. Column() {
  10815. // 时间显示
  10816. Text(this.getTimeText())
  10817. .fontSize(18)
  10818. .fontColor(Color.White)
  10819. .margin({ bottom: 10 })
  10820. Row() {
  10821. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  10822. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  10823. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  10824. }
  10825. .justifyContent(FlexAlign.Center)
  10826. }
  10827. .margin({ top: 12, bottom: 8 })
  10828. }
  10829. // 精度按钮组件
  10830. @Builder
  10831. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  10832. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10833. Column() {
  10834. Image(icon)
  10835. .width(28)
  10836. .margin({ bottom: 5 })
  10837. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  10838. Text(label)
  10839. .fontSize(12)
  10840. .fontColor('#FFFFFF')
  10841. }
  10842. }
  10843. .backgroundColor(Color.Transparent)
  10844. .enabled(!this.isButtonDisabled(step))
  10845. .onClick(() => this.handlePrecisionAdjust(step))
  10846. .padding(5)
  10847. .width(66)
  10848. .height(66)
  10849. .margin({ left: 18, right: 18 })
  10850. .border({
  10851. color: '#FFFFFF',
  10852. width: 1.8
  10853. })
  10854. }
  10855. private handlePrecisionAdjust(step: number) {
  10856. if (step === 0) {
  10857. this.timeOffset = 0
  10858. return
  10859. }
  10860. // 精度处理:保留1位小数
  10861. const newOffset = Number((this.timeOffset + step).toFixed(5))
  10862. // 边界保护(±15.0秒)
  10863. if (newOffset < -30.0 || newOffset > 30.0) {
  10864. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  10865. return
  10866. }
  10867. // 状态更新
  10868. this.timeOffset = newOffset
  10869. }
  10870. // 按钮禁用逻辑
  10871. private isButtonDisabled(step: number): boolean {
  10872. const futureOffset = this.timeOffset + step
  10873. return (futureOffset < -30.0) || (futureOffset > 30.0)
  10874. }
  10875. // 时间显示文本升级
  10876. private getTimeText(): string {
  10877. const absValue = Math.abs(this.timeOffset)
  10878. return this.timeOffset === 0
  10879. ? '歌词时间已重置'
  10880. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  10881. }
  10882. // 导入 本地歌词 搜索歌词
  10883. @Builder
  10884. pushLyricButton(icon: Resource, step: number, label: string) {
  10885. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10886. Row() {
  10887. Image(icon)
  10888. .width(14)
  10889. .margin({ left: 13 })
  10890. Text(label)
  10891. .fontSize(12)
  10892. .margin({ left: 6 })
  10893. .fontColor('#FFFFFF')
  10894. }
  10895. }
  10896. .onClick(() => {
  10897. switch (step) {
  10898. case 0:
  10899. this.callFilePickerSelectFileForLyric()
  10900. break;
  10901. case 1:
  10902. //判断有没有设置api
  10903. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  10904. this.isLyricSetting = false
  10905. this.showTipsDialog()
  10906. return
  10907. }
  10908. if (StrUtil.isNotEmpty(this.videoUrl)) {
  10909. ToastUtil.showToast('正在获取')
  10910. this.isLyricSetting = false
  10911. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  10912. this.initLyric(lyricPath, true);
  10913. }
  10914. break;
  10915. }
  10916. })
  10917. .padding(5)
  10918. .width(110)
  10919. .backgroundColor(Color.Transparent)
  10920. .height(40)
  10921. .margin({ left: 6, right: 6 })
  10922. .border({
  10923. color: '#FFFFFF',
  10924. radius: 20,
  10925. width: 1.8
  10926. })
  10927. }
  10928. showVipDialog() {
  10929. DialogHelper.showCustomContentDialog({
  10930. dialogId: 'vip',
  10931. title: "友情提示",
  10932. autoCancel: false, //点击遮障层时,不关闭弹窗
  10933. backCancel: true, //点击返回键,不关闭弹窗
  10934. contentBuilder: () => {
  10935. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  10936. },
  10937. buttons: [],
  10938. })
  10939. }
  10940. //去赞助的自定义内容
  10941. @Builder
  10942. customVipBuilder(content: string) {
  10943. Column() {
  10944. Text(content)
  10945. .fontColor(Color.Gray)
  10946. .fontSize(16)
  10947. .alignSelf(ItemAlign.Start)
  10948. .margin({ bottom: 15 })
  10949. .fontSize(16)
  10950. Row() {
  10951. Button('取消')
  10952. .fontColor(Color.White)
  10953. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  10954. .height(50)
  10955. .layoutWeight(1)
  10956. .stateEffect(true)
  10957. .margin({ right: 6 })
  10958. .onClick(() => {
  10959. DialogHelper.closeDialog('vip'); //关闭弹框
  10960. })
  10961. Button('开通')
  10962. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  10963. .layoutWeight(1)
  10964. .height(50)
  10965. .backgroundColor(this.themeColor)
  10966. .stateEffect(true)
  10967. .margin({ left: 6 })
  10968. .onClick(() => {
  10969. DialogHelper.closeDialog('vip'); //关闭弹框
  10970. this.isShowPlay = false
  10971. this.mType = 1 //跳转到用户中心
  10972. // router.pushUrl({
  10973. // url: 'pages/VipPage'
  10974. // }, router.RouterMode.Single);
  10975. })
  10976. }
  10977. }
  10978. .width("100%")
  10979. .padding(10)
  10980. }
  10981. showTipsDialog() {
  10982. DialogHelper.showCustomContentDialog({
  10983. dialogId: 'tips',
  10984. title: "友情提示",
  10985. autoCancel: false, //点击遮障层时,不关闭弹窗
  10986. backCancel: true, //点击返回键,不关闭弹窗
  10987. contentBuilder: () => {
  10988. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  10989. },
  10990. buttons: [],
  10991. })
  10992. }
  10993. @Builder
  10994. customTipsBuilder(content: string) {
  10995. Column() {
  10996. Text(content)
  10997. .fontColor(Color.Gray)
  10998. .fontSize(16)
  10999. .alignSelf(ItemAlign.Start)
  11000. .margin({ bottom: 15 })
  11001. .fontSize(16)
  11002. Row() {
  11003. Button('取消')
  11004. .fontColor(Color.White)
  11005. .backgroundColor(this.themeColor)
  11006. .height(50)
  11007. .layoutWeight(1)
  11008. .stateEffect(true)
  11009. .margin({ right: 6 })
  11010. .onClick(() => {
  11011. DialogHelper.closeDialog('tips'); //关闭弹框
  11012. })
  11013. Button('跳转')
  11014. .fontColor(Color.White)//
  11015. .layoutWeight(1)
  11016. .height(50)
  11017. .backgroundColor(this.themeColor)
  11018. .stateEffect(true)
  11019. .margin({ left: 6 })
  11020. .onClick(() => {
  11021. DialogHelper.closeDialog('tips'); //关闭弹框
  11022. this.isShowEdit = false
  11023. this.longItemFilePath = ''
  11024. // if(this.isGridMusic&&!this.isShowPlay){
  11025. // this.longItemFilePath== ''
  11026. // }else{
  11027. // this.isShowEdit = false
  11028. // }
  11029. this.isShowMoreView = false;
  11030. this.isShowPlay = false
  11031. this.mType = 4
  11032. // router.pushUrl({
  11033. // url: 'pages/SettingPage'
  11034. // }, router.RouterMode.Single);
  11035. })
  11036. }
  11037. }
  11038. .width("100%")
  11039. .padding(10)
  11040. }
  11041. @Builder
  11042. PlayMoreSheet() {
  11043. Column() {
  11044. this.MoreList()
  11045. }
  11046. .width('100%')
  11047. .height('100%')
  11048. }
  11049. @Builder
  11050. MoreList() {
  11051. Scroll() {
  11052. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  11053. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  11054. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  11055. Row() {
  11056. if (more.id === 3&&this.currentSong) {
  11057. Image(more.image)
  11058. .width(24)
  11059. .height(24)
  11060. .margin({ left: 10, right: 10 })
  11061. Text(more.title)
  11062. .fontSize(16)
  11063. .fontColor(Color.White)
  11064. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  11065. height: this.isCoverOpacity() ? '95%' : '95%',
  11066. dragBar: true,
  11067. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11068. showClose: true,
  11069. blurStyle: BlurStyle.Thin,
  11070. backgroundColor: Color.Transparent,
  11071. title: { title: '歌曲信息' }
  11072. })
  11073. } else if (more.id === 15 && this.currentSong) { //编辑标签
  11074. Image(more.image)
  11075. .width(24)
  11076. .height(24)
  11077. .margin({ left: 10, right: 10 })
  11078. Text(more.title)
  11079. .fontSize(16)
  11080. .fontColor(Color.White)
  11081. } else if (more.id === 5) { //定时关闭
  11082. Image(more.image)
  11083. .width(24)
  11084. .height(24)
  11085. .margin({ left: 10, right: 10 })
  11086. Text(more.title)
  11087. .fontSize(16)
  11088. .fontColor(Color.White)
  11089. .onClick(() => {
  11090. this.doMore(more.id)
  11091. })
  11092. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  11093. height: this.isCoverOpacity() ? '95%' : '95%',
  11094. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11095. dragBar: true,
  11096. showClose: true,
  11097. title: { title: $r('app.string.time_close') }
  11098. })
  11099. } else if (more.id === 2) { //歌词设置
  11100. Image(more.image)
  11101. .width(24)
  11102. .height(24)
  11103. .margin({ left: 10, right: 10 })
  11104. Text(more.title)
  11105. .fontSize(16)
  11106. .fontColor(Color.White)
  11107. } else if (more.id === 16) { //悬浮歌词设置
  11108. Image(more.image)
  11109. .width(24)
  11110. .height(24)
  11111. .margin({ left: 10, right: 10 })
  11112. Text(more.title)
  11113. .fontSize(16)
  11114. .fontColor(Color.White)
  11115. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  11116. height: this.isCoverOpacity() ? '95%' : '95%',
  11117. dragBar: true,
  11118. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11119. showClose: true,
  11120. blurStyle: BlurStyle.Thin,
  11121. backgroundColor: Color.Transparent,
  11122. title: { title: '悬浮歌词' }
  11123. })
  11124. } else if (more.id === 11) {
  11125. Image(more.image)
  11126. .width(24)
  11127. .height(24)
  11128. .margin({ left: 10, right: 10 })
  11129. Text(more.title)
  11130. .fontSize(16)
  11131. .fontColor(Color.White)
  11132. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  11133. height: this.isCoverOpacity() ? '95%' : '60%',
  11134. dragBar: true,
  11135. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11136. showClose: true,
  11137. blurStyle: BlurStyle.Thin,
  11138. backgroundColor: Color.Transparent,
  11139. title: { title: '跳过头尾' }
  11140. })
  11141. } else if (more.id === 12) { //投播
  11142. AVCastPicker({
  11143. customPicker: (): void => this.TPImageBuilder(more),
  11144. onStateChange: (state) => {
  11145. if (state == AVCastPickerState.STATE_APPEARING) {
  11146. console.log(' The picker starts showing.');
  11147. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  11148. console.log(' The picker finishes presenting.');
  11149. }
  11150. },
  11151. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  11152. sessionType: 'video'
  11153. })
  11154. .id('AVCastPicker')
  11155. } else {
  11156. Image(more.image)
  11157. .width(24)
  11158. .height(24)
  11159. .fillColor(Color.White)
  11160. .margin({ left: 10, right: 10 })
  11161. .onClick(() => {
  11162. this.doMore(more.id)
  11163. })
  11164. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  11165. .fontSize(16)
  11166. .fontColor(Color.White)
  11167. .onClick(() => {
  11168. this.doMore(more.id)
  11169. })
  11170. Select([//倍速
  11171. { value: '0.25x' },
  11172. { value: '0.5x' },
  11173. { value: '0.75x' },
  11174. { value: '1x' },
  11175. { value: '1.25x' },
  11176. { value: '1.5x' },
  11177. { value: '1.75x' },
  11178. { value: '2x' },
  11179. { value: '3x' }])
  11180. .font({ size: 16, weight: FontWeight.Medium })
  11181. .fontColor($r('sys.color.white'))
  11182. .margin({ left: 25 })
  11183. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  11184. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  11185. .value(Utility.optimizedFormat(this.playSpeed))
  11186. .onSelect(async (_index: number, text?: string | undefined) => {
  11187. let speed = parseFloat(text?.replace('x', '') || '1');
  11188. if (!CommonConstants.video_speed_list.includes(speed)) {
  11189. speed = 1;
  11190. }
  11191. this.playSpeed = speed
  11192. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  11193. })
  11194. Slider({
  11195. value: this.volume,
  11196. min: 0,
  11197. max: 1,
  11198. step: 0.1,
  11199. style: SliderStyle.OutSet
  11200. })
  11201. .margin({ left: 18, right: 8 })
  11202. .blockColor(this.themeColor)
  11203. .trackColor($r('app.color.speed_text_color'))
  11204. .selectedColor(Color.White)
  11205. .trackThickness(9)
  11206. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  11207. .onChange((value: number) => {
  11208. this.volume = value;
  11209. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  11210. PreferencesUtil.putSync('DefalutVolume',this.volume)
  11211. })
  11212. .layoutWeight(1)
  11213. Blank()
  11214. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  11215. .selectedColor(this.themeColor)
  11216. .switchPointColor(Color.White)
  11217. .margin({ right: 15 })
  11218. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11219. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  11220. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11221. if (more.id == 6) {
  11222. this.isMusicMemoryPlay = checked;
  11223. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  11224. if (this.isMusicMemoryPlay) {
  11225. ToastUtil.showToast('记忆播放已开启')
  11226. } else {
  11227. ToastUtil.showToast('记忆播放已关闭')
  11228. }
  11229. }
  11230. })
  11231. .width(48)
  11232. .height(24);
  11233. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  11234. .selectedColor(this.themeColor)
  11235. .switchPointColor(Color.White)
  11236. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11237. .margin({ right: 15 })
  11238. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  11239. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11240. if (more.id == 7) {
  11241. this.isMusicBGCover = checked;
  11242. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  11243. if (this.isMusicBGCover) {
  11244. ToastUtil.showToast('播放背景随音乐封面已开启')
  11245. } else {
  11246. ToastUtil.showToast('播放背景随音乐封面已关闭')
  11247. }
  11248. }
  11249. })
  11250. .width(48)
  11251. .height(24);
  11252. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  11253. .selectedColor(this.themeColor)
  11254. .switchPointColor(Color.White)
  11255. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11256. .margin({ right: 15 })
  11257. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  11258. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11259. if (more.id == 8) {
  11260. this.isSavePlayMode = checked;
  11261. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  11262. if (this.isSavePlayMode) {
  11263. ToastUtil.showToast('保存播放模式已开启')
  11264. } else {
  11265. ToastUtil.showToast('保存播放模式已关闭')
  11266. }
  11267. }
  11268. })
  11269. .width(48)
  11270. .height(24);
  11271. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  11272. .selectedColor(this.themeColor)
  11273. .switchPointColor(Color.White)
  11274. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11275. .margin({ right: 15 })
  11276. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  11277. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11278. if (more.id == 13) {
  11279. this.isCoverRectangle = checked;
  11280. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  11281. if (this.isCoverRectangle) {
  11282. ToastUtil.showToast('封面方形已开启')
  11283. this.animationRoFun()
  11284. } else {
  11285. ToastUtil.showToast('封面圆形已开启')
  11286. this.animationRoFun()
  11287. }
  11288. }
  11289. })
  11290. .width(48)
  11291. .height(24);
  11292. Toggle({ type: ToggleType.Switch, isOn: this.isShowBgLiuGUANG })
  11293. .selectedColor(this.themeColor)
  11294. .switchPointColor(Color.White)
  11295. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11296. .margin({ right: 15 })
  11297. .visibility(more.id == 21 ? Visibility.Visible : Visibility.None)
  11298. .onChange((checked: boolean) => { // 是否开启背景流光效果
  11299. if (more.id == 21) {
  11300. this.isShowBgLiuGUANG = checked;
  11301. PreferencesUtil.putSync('isShowBgLiuGUANG',this.isShowBgLiuGUANG)
  11302. }
  11303. })
  11304. .width(48)
  11305. .height(24);
  11306. }
  11307. }
  11308. .width('100%')
  11309. .height(45)
  11310. .padding(15)
  11311. .backgroundColor(Color.Transparent)
  11312. .borderRadius(12)
  11313. .margin({ bottom: 6 })
  11314. }
  11315. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  11316. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  11317. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  11318. .backgroundColor(Color.Transparent)
  11319. .onClick(() => {
  11320. this.doMore(more.id)
  11321. })
  11322. });
  11323. }
  11324. .width('100%')
  11325. .padding(16)
  11326. }.margin({ bottom: 18 })
  11327. }
  11328. @Builder
  11329. TPImageBuilder(more: MoreItem): void {
  11330. Row() {
  11331. Image($r('app.media.tuoping'))
  11332. .width(22)
  11333. .height(22)
  11334. .margin({ left: 10, right: 10 })
  11335. Text(more.title)
  11336. .fontSize(16)
  11337. .fontColor(Color.White)
  11338. }
  11339. .width('100%')
  11340. .layoutWeight(1)
  11341. .alignItems(VerticalAlign.Center)
  11342. .justifyContent(FlexAlign.Start)
  11343. }
  11344. private moreItems: MoreItem[] = [
  11345. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  11346. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  11347. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  11348. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  11349. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  11350. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  11351. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  11352. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  11353. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  11354. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  11355. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  11356. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  11357. { id: 4, image: $r('app.media.share2'), title: '分享' },
  11358. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  11359. // { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  11360. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  11361. { id : 21, image: $r('app.media.music_red'), title: '开启背景流光' },
  11362. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  11363. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  11364. ];
  11365. @State isShowBgLiuGUANG: boolean = false;
  11366. @State isShowMoreView: boolean = false;
  11367. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  11368. @State isShowTimeCloseMore: boolean = false
  11369. @State isShowDetailMore: boolean = false
  11370. @State isMusicBGCover: boolean = true
  11371. @State isSavePlayMode: boolean = true
  11372. @State isLyricSetting: boolean = false
  11373. @State isJumpSetting: boolean = false
  11374. @State isShowEdit: boolean = false
  11375. @State showPipLyric: boolean = false
  11376. async setRingTone() {
  11377. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  11378. return
  11379. }
  11380. // 确定后的逻辑
  11381. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  11382. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  11383. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  11384. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  11385. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  11386. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  11387. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  11388. , this.videoUrl, this.name).then(res => {
  11389. LogUtil.info('onecold setFlag :' + res);
  11390. });
  11391. }
  11392. doMore(moreId: number) {
  11393. switch (moreId) {
  11394. case 2: //歌词
  11395. this.isLyricSetting = !this.isLyricSetting;
  11396. this.isShowMoreView = false
  11397. break;
  11398. case 3: //详情
  11399. this.isShowDetailMore = !this.isShowDetailMore;
  11400. break;
  11401. case 4: //分享
  11402. if (this.currentSong !== undefined) {
  11403. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  11404. }
  11405. this.isShowMoreView = false
  11406. break;
  11407. case 5: //定时关闭
  11408. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  11409. break;
  11410. case 10: //设为铃声
  11411. this.setRingTone()
  11412. this.isShowMoreView = false
  11413. break;
  11414. case 11: //跳过头尾
  11415. this.isJumpSetting = !this.isJumpSetting;
  11416. break;
  11417. case 13: //倍速
  11418. break;
  11419. case 14: //搜索封面
  11420. if (this.currentSong !== undefined) {
  11421. this.doSearchCover(this.currentSong)
  11422. }
  11423. this.isShowMoreView = false
  11424. break;
  11425. case 15: //编辑标签
  11426. this.initEditFields(this.currentSong)
  11427. this.tempLyricContent = this.lyricContent
  11428. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  11429. this.lyricConStr = this.tempLyricContent
  11430. }
  11431. this.isShowEdit = !this.isShowEdit;
  11432. break;
  11433. case 16: //悬浮歌词
  11434. this.showPipLyric = !this.showPipLyric;
  11435. break;
  11436. case 17: //横屏模式
  11437. if (this.isLandscape) {
  11438. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  11439. } else {
  11440. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  11441. }
  11442. this.isShowMoreView = false
  11443. break;
  11444. case 20://AB循环
  11445. this.isABSheet = !this.isABSheet
  11446. break;
  11447. }
  11448. }
  11449. //AB循环
  11450. @State isOpenAB:boolean = false
  11451. @State jumpATime:number = 0
  11452. @State jumpBTime:number = 0
  11453. @State isABSheet:boolean = false
  11454. @Builder
  11455. ABLoopSheet() {
  11456. ABLoopComptent({
  11457. jumpATime:this.jumpATime,
  11458. jumpBTime:this.jumpBTime,
  11459. onClickAItem: async ()=>{
  11460. if(this.mIjkMediaPlayer){
  11461. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  11462. }
  11463. },
  11464. onClickBItem: async ()=>{
  11465. if(this.mIjkMediaPlayer){
  11466. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  11467. if(this.jumpBTime<=this.jumpATime){
  11468. ToastUtil.showToast('设置B点时间不能小于A点时间')
  11469. this.jumpBTime = 0
  11470. }
  11471. }
  11472. },
  11473. onCancleButtonClick: async ()=>{
  11474. this.isOpenAB = false
  11475. this.isABSheet = false
  11476. },
  11477. onStartButtonClick: async ()=>{
  11478. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  11479. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  11480. return
  11481. }
  11482. this.isABSheet = false
  11483. this.startABLoop()
  11484. },
  11485. })
  11486. }
  11487. //开始AB循环
  11488. startABLoop(){
  11489. if(this.mIjkMediaPlayer){
  11490. this.seekTo(this.jumpATime+'')
  11491. this.isOpenAB = true
  11492. }
  11493. }
  11494. /**
  11495. * 切换横竖屏
  11496. *
  11497. */
  11498. setOrientation(orientation: number) {
  11499. this.windowClass.setPreferredOrientation(orientation).then(() => {
  11500. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  11501. }).catch((err: BusinessError) => {
  11502. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  11503. });
  11504. }
  11505. /**
  11506. * 画中画功能(悬浮歌词功能)
  11507. *
  11508. */
  11509. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  11510. pipController?: PiPWindow.PiPController;
  11511. navigationId: string = '';
  11512. @State curState: string = '';
  11513. @State curError: ResourceStr = '';
  11514. @State pipBg: string = '#E8E8E8'
  11515. @State buttonAction: string = '';
  11516. //开启画中画功能
  11517. async startPip() {
  11518. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  11519. if (!this.pipController) {
  11520. await this.createPipController();
  11521. }
  11522. if (!this.pipController) {
  11523. Logger.info(`[${TAG}] pipController create error`);
  11524. return;
  11525. }
  11526. await this.pipController.startPiP();
  11527. }
  11528. async stopPip() {
  11529. if (!this.pipController) {
  11530. Logger.info(`[${TAG}] pipController is not exist`);
  11531. return;
  11532. }
  11533. this.isOpenPip = false
  11534. await this.pipController.stopPiP();
  11535. }
  11536. async createPipController() {
  11537. this.pipController = await PiPWindow.create({
  11538. context: getContext(this),
  11539. componentController: this.xcomponentController,
  11540. navigationId: this.navigationId,
  11541. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  11542. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  11543. customUIController: this.nodeController,
  11544. });
  11545. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  11546. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  11547. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  11548. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  11549. this.onStateChange(state, reason);
  11550. });
  11551. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  11552. this.onActionEvent(event, status);
  11553. });
  11554. }
  11555. destroyPipController() {
  11556. if (!this.pipController) {
  11557. return;
  11558. }
  11559. this.pipController.off('stateChange');
  11560. this.pipController.off('controlPanelActionEvent');
  11561. this.pipController = undefined;
  11562. }
  11563. onStateChange(state: PiPWindow.PiPState, reason: string) {
  11564. switch (state) {
  11565. case PiPWindow.PiPState.ABOUT_TO_START:
  11566. this.curState = 'ABOUT_TO_START';
  11567. this.curError = $r('app.string.current_error_hint');
  11568. break;
  11569. case PiPWindow.PiPState.STARTED:
  11570. this.curState = 'STARTED';
  11571. this.curError = $r('app.string.current_error_hint');
  11572. break;
  11573. case PiPWindow.PiPState.ABOUT_TO_STOP:
  11574. this.curState = 'ABOUT_TO_STOP';
  11575. this.curError = $r('app.string.current_error_hint');
  11576. break;
  11577. case PiPWindow.PiPState.STOPPED:
  11578. this.curState = 'STOPPED';
  11579. this.curError = $r('app.string.current_error_hint');
  11580. this.stopPip()
  11581. this.destroyPipController()
  11582. break;
  11583. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  11584. this.curState = 'ABOUT_TO_RESTORE';
  11585. this.curError = $r('app.string.current_error_hint');
  11586. break;
  11587. case PiPWindow.PiPState.ERROR:
  11588. this.curState = 'ERROR';
  11589. this.curError = reason;
  11590. break;
  11591. default:
  11592. break;
  11593. }
  11594. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  11595. }
  11596. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  11597. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  11598. switch (event) {
  11599. case 'playbackStateChanged':
  11600. if (status === 0) {
  11601. this.pause();
  11602. } else {
  11603. console.info('onecold startPlayOrResumePlay 9869')
  11604. this.startPlayOrResumePlay();
  11605. }
  11606. break;
  11607. case 'nextVideo':
  11608. // 切换到下一个视频
  11609. this.playNext().catch(() => {
  11610. Logger.error('heanup onActionEvent playNext', `播放下一首失败`);
  11611. });
  11612. break;
  11613. case 'previousVideo':
  11614. // 切换到上一个视频
  11615. this.playPrevious().catch(() => {
  11616. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败`);
  11617. });
  11618. break;
  11619. case 'previousVideo':
  11620. // 切换到上一个视频
  11621. this.playPrevious().catch(() => {
  11622. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败:`);
  11623. });
  11624. break;
  11625. default:
  11626. }
  11627. this.buttonAction = event + `-status:${status}`;
  11628. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  11629. }
  11630. /**
  11631. * 画中画功能(悬浮歌词功能)结束
  11632. *
  11633. */
  11634. async doSearchCover(item: VideoItem,title?:string,artist?:string): Promise<string> {
  11635. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  11636. this.isShowMoreView = false;
  11637. this.showTipsDialog();
  11638. return ''; // Return empty string when no API is configured
  11639. }
  11640. if (!item) {
  11641. return ''; // Return empty string if item is undefined
  11642. }
  11643. const titleS = title||item?.name || '';
  11644. const artistS = artist||item?.artist || ''; // Use empty string if artist is missing
  11645. return this.searchCover(item, titleS, artistS); // Await is not needed here as we return the promise directly
  11646. }
  11647. /**
  11648. *api搜索封面
  11649. *item,根据title和artist
  11650. */
  11651. searchCover(item: VideoItem, title: string, artist: string): Promise<string> {
  11652. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  11653. LogUtil.debug("onecold res =" + res);
  11654. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  11655. if (item.filePath == this.currentSong?.filePath) {
  11656. this.cover = res;
  11657. if (this.currentSong) {
  11658. this.currentSong.pixelMapPath = res;
  11659. }
  11660. }
  11661. // Update pixel map path but always return res regardless of success
  11662. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  11663. if (success) {
  11664. this.doUpdateData();
  11665. console.log("onecold 更新音乐封面成功,数据库已同步");
  11666. } else {
  11667. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  11668. }
  11669. // Note: We don't resolve/reject here because we already returned res
  11670. });
  11671. LogUtil.debug("onecold this.cover =" + this.cover);
  11672. }
  11673. return res; // Always return res regardless of updatePixelMapPath result
  11674. });
  11675. }
  11676. @State jumpTopTime: number = 0
  11677. @State jumpEndTime: number = 0
  11678. @State isOpenJump: boolean = false
  11679. @Builder
  11680. JumpTopEndSheet() {
  11681. Scroll() {
  11682. Column() {
  11683. Column() {
  11684. Text('仅对本播放列表有效')
  11685. .fontSize(16)
  11686. .fontColor($r('app.color.text_color'))
  11687. // 跳过头尾
  11688. Column() {
  11689. Row() {
  11690. Text('跳过片头:')
  11691. .fontSize(16)
  11692. .fontColor($r('app.color.text_color'))
  11693. Text(this.jumpTopTime + 's')
  11694. .fontSize(16)
  11695. .fontColor($r('app.color.text_color'))
  11696. }
  11697. .margin({ bottom: 5 })
  11698. Row() {
  11699. Slider({
  11700. value: this.jumpTopTime,
  11701. min: 0,
  11702. max: 120,
  11703. step: 1,
  11704. style: SliderStyle.OutSet
  11705. })
  11706. .blockColor(this.themeColor)
  11707. .trackColor($r('app.color.speed_text_color'))
  11708. .selectedColor(Color.White)
  11709. .trackThickness(8)
  11710. .onChange((value: number) => {
  11711. this.jumpTopTime = value;
  11712. })
  11713. .width('85%')
  11714. }
  11715. .alignItems(VerticalAlign.Top)
  11716. }
  11717. .margin({ top: 10, bottom: 10 })
  11718. // 跳过头尾
  11719. Column() {
  11720. Row() {
  11721. Text('跳过片尾:')
  11722. .fontSize(16)
  11723. .fontColor($r('app.color.text_color'))
  11724. Text(this.jumpEndTime + 's')
  11725. .fontSize(16)
  11726. .fontColor($r('app.color.text_color'))
  11727. }
  11728. .margin({ bottom: 5 })
  11729. Row() {
  11730. Slider({
  11731. value: this.jumpEndTime,
  11732. min: 0,
  11733. max: 120,
  11734. step: 1,
  11735. style: SliderStyle.OutSet
  11736. })
  11737. .blockColor(this.themeColor)
  11738. .trackColor($r('app.color.speed_text_color'))
  11739. .selectedColor(Color.White)
  11740. .trackThickness(8)
  11741. .onChange((value: number) => {
  11742. this.jumpEndTime = value;
  11743. })
  11744. .width('85%')
  11745. }
  11746. .alignItems(VerticalAlign.Top)
  11747. }
  11748. .margin({ top: 10, bottom: 10 })
  11749. Row() {
  11750. Button('保存设置')
  11751. .fontColor(Color.White)
  11752. .layoutWeight(1)
  11753. .height(40)
  11754. .width(80)
  11755. .backgroundColor(this.themeColor)
  11756. .stateEffect(true)
  11757. .margin({ left: 0, bottom: 20 })
  11758. .onClick(async () => {
  11759. if (!Utility.isNoble()) {
  11760. this.isJumpSetting = false
  11761. this.isShowMoreView = false
  11762. this.showVipDialog()
  11763. return
  11764. }
  11765. if (this.currentSong === undefined) {
  11766. return
  11767. }
  11768. if (this.modeType === 0) {
  11769. let parentPath = FileUtil.getParentPath(this.videoUrl)
  11770. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  11771. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  11772. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  11773. } else if (this.modeType === 1) { //媒体库
  11774. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  11775. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  11776. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  11777. } else if (this.modeType === 2) { //艺术家
  11778. if (this.currentSong?.artist) {
  11779. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  11780. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  11781. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  11782. }
  11783. } else if (this.modeType === 3) { //专辑
  11784. if (this.currentSong?.album) {
  11785. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  11786. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  11787. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  11788. }
  11789. }
  11790. ToastUtil.showShort("保存成功")
  11791. this.isJumpSetting = false
  11792. })
  11793. }
  11794. .margin({
  11795. left: 38,
  11796. right: 38,
  11797. top: 10,
  11798. bottom: 10
  11799. })
  11800. .width(120)
  11801. .height(50)
  11802. }
  11803. }
  11804. }
  11805. .width('100%')
  11806. .height('100%')
  11807. }
  11808. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  11809. private onStateVastChange(state: AVCastPickerState) {
  11810. if (state == AVCastPickerState.STATE_APPEARING) {
  11811. console.log('The picker starts showing.');
  11812. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  11813. console.log('The picker finishes presenting.');
  11814. }
  11815. }
  11816. private showSelectLyric() {
  11817. DialogHelper.showActionSheetDialog({
  11818. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  11819. // sheets: ["本地歌词", "搜索歌词"],
  11820. sheets: [
  11821. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  11822. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  11823. ],
  11824. maskColor: Color.Transparent,
  11825. backgroundColor: $r('app.color.bg_card'),
  11826. transition: AnimationHelper.transitionInDown(666),
  11827. onAction: (index) => {
  11828. switch (index) {
  11829. case 0:
  11830. this.callFilePickerSelectFileForLyric()
  11831. break;
  11832. case 1:
  11833. if (StrUtil.isNotEmpty(this.videoUrl)) {
  11834. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  11835. this.initLyric(lyricPath);
  11836. }
  11837. break;
  11838. }
  11839. }
  11840. })
  11841. }
  11842. // 拉起picker选择文件管理器
  11843. async callFilePickerSelectFileForLyric(): Promise<void> {
  11844. try {
  11845. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  11846. DocumentSelectOptions.maxSelectNumber = 1
  11847. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  11848. let documentPicker = new picker.DocumentViewPicker();
  11849. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  11850. Logger.info(TAG,
  11851. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  11852. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  11853. this.saveVideoDatasLyric(DocumentSelectResult)
  11854. }
  11855. }).catch((err: BusinessError) => {
  11856. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  11857. });
  11858. } catch (err) {
  11859. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  11860. }
  11861. }
  11862. async saveVideoDatasLyric(uris: string[]) {
  11863. if (ArrayUtil.isEmpty(uris)) {
  11864. return
  11865. }
  11866. let newUris: string[] = [];
  11867. for (let i = 0; i < uris.length; i++) {
  11868. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  11869. Logger.info(TAG, 'filePath uri: ' + filePath);
  11870. newUris.push(filePath)
  11871. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  11872. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  11873. fileIo.copyFileSync(file.fd, file2.fd)
  11874. fileIo.closeSync(file);
  11875. fileIo.closeSync(file2);
  11876. this.initLyric(filePath,false,false,true)
  11877. }
  11878. }
  11879. private initDelayPlay(context: object) {
  11880. this.mContext = context;
  11881. }
  11882. startPipLyric() {
  11883. if (this.pipController) {
  11884. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  11885. PiPWindow.PiPControlStatus.PLAY);
  11886. }
  11887. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  11888. if (this.isOpenPip) {
  11889. this.startPip()
  11890. } else {
  11891. this.stopPip()
  11892. }
  11893. }
  11894. //startOffset 从cue分轨时间开始播
  11895. private startPlayOrResumePlay(startOffset?:number) {
  11896. //针对dsf文件高采样率,统一转wav播放
  11897. const sampleRate = this.currentSong?.sampleRate||0
  11898. if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  11899. console.info('onecold 采样率 ='+sampleRate)
  11900. let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  11901. console.info('onecold newDsfPath ='+newDsfPath)
  11902. if(!FileUtil.accessSync(newDsfPath)){
  11903. const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  11904. taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  11905. this.videoUrl = newDsfPath
  11906. this.startPlay(startOffset)
  11907. }).catch((e:object)=>{
  11908. console.info("task1 catch e: " + e);
  11909. })
  11910. }else{
  11911. this.videoUrl = newDsfPath
  11912. this.startPlay(startOffset)
  11913. }
  11914. }else{
  11915. this.startPlay(startOffset)
  11916. }
  11917. }
  11918. startPlay(startOffset?:number) {
  11919. this.startPipLyric()
  11920. this.mDestroyPage = false;
  11921. this.animationState = AnimationStatus.Running
  11922. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  11923. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  11924. this.stopProgressTask();
  11925. this.startProgressTask();
  11926. this.play(this.videoUrl.toString(),startOffset);
  11927. }
  11928. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  11929. this.mIjkMediaPlayer.start();
  11930. this.setProgress()
  11931. this.CONTROL_PlayStatus = PlayStatus.PLAY
  11932. }
  11933. this.setIsPlaying(true)
  11934. this.updateSessionPlayState(true)
  11935. this.watchStatus();
  11936. this.updateLastPlayTimeStr(this.videoUrl)
  11937. }
  11938. updateLastPlayTimeStr(filePath: string) {
  11939. // 检查是否为网络音频(WebDAV),如果是则不更新本地数据库
  11940. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  11941. Logger.info(`heanup 检测到网络音频播放,跳过数据库更新: ${filePath}`)
  11942. return;
  11943. }
  11944. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  11945. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  11946. if (success) {
  11947. this.getHistoryList(false)
  11948. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  11949. } else {
  11950. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  11951. }
  11952. });
  11953. }
  11954. private completionNum(num: number): string | number {
  11955. if (num < 10) {
  11956. return '0' + num;
  11957. } else {
  11958. return num;
  11959. }
  11960. }
  11961. private stringForTime(timeMs: number): string {
  11962. let totalSeconds: number | string = (timeMs / 1000);
  11963. let newSeconds: number | string = totalSeconds % 60;
  11964. let minutes: number | string = (totalSeconds / 60) % 60;
  11965. let hours: number | string = totalSeconds / 3600;
  11966. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  11967. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  11968. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  11969. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  11970. if (this.isCurrentTime) {
  11971. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  11972. this.oldSeconds = newSeconds
  11973. } else {
  11974. newSeconds = this.oldSeconds
  11975. }
  11976. }
  11977. newSeconds = this.completionNum(newSeconds);
  11978. if (hours > 0) {
  11979. return hours + ":" + minutes + ":" + newSeconds;
  11980. } else {
  11981. return minutes + ":" + newSeconds;
  11982. }
  11983. }
  11984. private setProgress() {
  11985. let position = this.mIjkMediaPlayer.getCurrentPosition();
  11986. let duration = this.mIjkMediaPlayer.getDuration();
  11987. let pos = 0;
  11988. if (duration > 0) {
  11989. this.slideEnable = true;
  11990. let curPercent = position / duration;
  11991. pos = curPercent * 100;
  11992. if (pos > this.PROGRESS_MAX_VALUE) {
  11993. this.progressValue = this.PROGRESS_MAX_VALUE
  11994. } else {
  11995. this.progressValue = pos;
  11996. }
  11997. }
  11998. // LogUtils.getInstance()
  11999. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  12000. this.totalTime = this.stringForTime(duration);
  12001. if (position > duration) {
  12002. position = duration;
  12003. }
  12004. this.isCurrentTime = true;
  12005. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  12006. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  12007. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  12008. this.currentTime = this.stringForTime(position);
  12009. this.isCurrentTime = false
  12010. if (this.mIjkMediaPlayer.isPlaying()) {
  12011. this.randomColor =
  12012. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  12013. //如果是开启AB循环
  12014. if(this.isOpenAB){
  12015. if(position >=this.jumpBTime){
  12016. this.seekTo(this.jumpATime+'')
  12017. return
  12018. }
  12019. }
  12020. // 判断是否播放到结束时间
  12021. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  12022. if (position >= duration - this.jumpEndTime * 1000) {
  12023. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  12024. this.CONTROL_PlayStatus = PlayStatus.INIT
  12025. this.startPlayOrResumePlay();
  12026. }else if (this.playType == 2) { //2:正常播放,单曲播完
  12027. this.showRePlay();
  12028. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  12029. this.progressValue = this.PROGRESS_MAX_VALUE;
  12030. this.slideEnable = false;
  12031. this.stop();
  12032. // ToastUtil.showToast('开始重新播放')
  12033. }else{
  12034. this.playNext().catch(() => {
  12035. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  12036. });
  12037. }
  12038. }
  12039. }
  12040. } else {
  12041. this.randomColor = 'rbg(0,0,0)'
  12042. }
  12043. }
  12044. private startProgressTask() {
  12045. let that = this;
  12046. this.updateProgressTimer = setInterval(() => {
  12047. //LogUtils.getInstance().LOGI("startProgressTask");
  12048. if (!that.mDestroyPage) {
  12049. that.setProgress();
  12050. }
  12051. }, 300);
  12052. }
  12053. private stopProgressTask() {
  12054. LogUtils.getInstance().LOGI("stopProgressTask");
  12055. clearInterval(this.updateProgressTimer);
  12056. }
  12057. private showLoadIng() {
  12058. this.loadingVisible = Visibility.Visible;
  12059. this.replayVisible = Visibility.None;
  12060. }
  12061. private hideLoadIng() {
  12062. this.loadingVisible = Visibility.None;
  12063. this.replayVisible = Visibility.None;
  12064. }
  12065. private showRePlay() {
  12066. this.loadingVisible = Visibility.None;
  12067. this.replayVisible = Visibility.Visible;
  12068. }
  12069. private async play(url: string,startOffset?:number) {
  12070. this.isShowBgLiuGUANG = PreferencesUtil.getBooleanSync('isShowBgLiuGUANG', false)
  12071. console.info('onecold this.url 1= '+url)
  12072. if(!url.toLowerCase().startsWith('http')){
  12073. let hasPermission = await PermissionUtil.activatePermission(url)
  12074. console.info('onecold this.hasPermission 1= '+hasPermission)
  12075. if(!url.includes(this.packName)){
  12076. const file = fs.openSync(url)
  12077. this.videoUrl = file.path
  12078. url= this.videoUrl
  12079. }
  12080. console.info('onecold this.hasPermission 1= '+hasPermission)
  12081. console.info('onecold this.videoUrl 1= '+this.videoUrl)
  12082. }
  12083. let that = this;
  12084. that.showLoadIng();
  12085. this.isOpenAB = false
  12086. //设置XComponent回调的context
  12087. if (!!this.mContext) {
  12088. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  12089. }
  12090. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  12091. this.mIjkMediaPlayer.reset();
  12092. }
  12093. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  12094. //设置debug模式
  12095. this.mIjkMediaPlayer.setDebug(false);
  12096. //初始化配置
  12097. this.mIjkMediaPlayer.native_setup();
  12098. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  12099. if(this.volumeSmall){
  12100. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  12101. this.mIjkMediaPlayer.setVolume('1', '1');
  12102. }else{
  12103. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  12104. }
  12105. }else{
  12106. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  12107. }
  12108. //设置视频源
  12109. Logger.info(TAG, `IjkPlayer setDataSource url=${url}`);
  12110. this.mIjkMediaPlayer.setDataSource(url);
  12111. // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
  12112. const headers = new Map<string, string>();
  12113. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  12114. headers.set("Accept", "*/*");
  12115. if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
  12116. &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
  12117. //如果封面为空,则搜索封面
  12118. this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
  12119. }
  12120. // 如果是WebDAV网络音频,使用webdav_account_id获取认证信息(等待完成后再设置一次性头部)
  12121. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type)) {
  12122. Logger.info(`heanup WebDAV歌曲认证 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
  12123. if (this.currentSong.webdav_account_id) {
  12124. try {
  12125. const webdavManager = RemoteDriveManager.getInstance();
  12126. const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  12127. if (webDavHeaders && webDavHeaders.size > 0) {
  12128. webDavHeaders.forEach((value, key) => headers.set(key, value));
  12129. Logger.info(`heanup 成功通过webdav_account_id获取并合并WebDAV认证头`);
  12130. } else {
  12131. Logger.warn(`heanup 通过webdav_account_id获取认证头失败,播放可能无法继续`);
  12132. }
  12133. } catch (error) {
  12134. const err = error as Error;
  12135. Logger.error(`heanup 获取WebDAV认证头时出错: ${err.message}`);
  12136. }
  12137. } else {
  12138. Logger.error(`heanup WebDAV歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法进行认证`);
  12139. }
  12140. }
  12141. // 统一设置带认证的请求头
  12142. // 百度类型也需要特殊请求头
  12143. if (this.currentSong && isBaiduType(this.currentSong.type)) {
  12144. try {
  12145. const webdavManager = RemoteDriveManager.getInstance();
  12146. const baiduHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  12147. baiduHeaders.forEach((value, key) => headers.set(key, value));
  12148. const headerSnapshot: Record<string, string> = {};
  12149. headers.forEach((value, key) => headerSnapshot[key] = value);
  12150. Logger.info(TAG, `Baidu播放请求头: ${JSON.stringify(headerSnapshot)}`);
  12151. } catch (error) {
  12152. Logger.error(`heanup 构建百度请求头失败: ${(error as Error).message}`);
  12153. }
  12154. }
  12155. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  12156. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type)) {
  12157. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  12158. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  12159. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  12160. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  12161. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  12162. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  12163. // 缓冲和播放优化设置
  12164. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  12165. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  12166. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1"); // 预加载启动
  12167. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  12168. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  12169. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  12170. // 网络相关设置
  12171. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  12172. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  12173. // 重连设置
  12174. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  12175. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  12176. } else if (this.currentSong && isBaiduType(this.currentSong.type)) {
  12177. console.log(`heanup 为百度网盘播放设置IjkPlayer选项`);
  12178. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "15000000");
  12179. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "15000000");
  12180. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1");
  12181. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "1");
  12182. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "2097152");
  12183. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "25");
  12184. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", BaiduConstants.USER_AGENT);
  12185. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", "3");
  12186. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http-detect-range-support", "1");
  12187. console.log(`heanup 百度网盘 IjkPlayer 选项设置完成`);
  12188. }
  12189. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  12190. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  12191. // }
  12192. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  12193. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  12194. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  12195. const fileSize = await this.getFileSize(this.videoUrl);
  12196. let bufferSize = 100 * 1024 ; // 默认缓冲区大小为1MB
  12197. // 使用软件解码(通常比硬件解码更节省内存)
  12198. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", '0');
  12199. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", '0');
  12200. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", '1024');
  12201. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzeduration", '500000');
  12202. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  12203. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  12204. //停止预读的最小帧数
  12205. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  12206. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  12207. // 设置其他缓冲相关选项
  12208. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  12209. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  12210. //启动预加载
  12211. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  12212. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  12213. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  12214. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  12215. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  12216. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  12217. // 因此需要播放器丢包,才不会累积延时
  12218. // 这个和第三个参数packet-buffering无关。
  12219. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  12220. // 无限制收流
  12221. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  12222. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  12223. // 屏幕常亮
  12224. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  12225. // 设置超时
  12226. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  12227. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  12228. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  12229. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  12230. // 变速播放
  12231. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  12232. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  12233. let Speed = this.mIjkMediaPlayer.getSpeed()
  12234. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  12235. //是否开启循环播放
  12236. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  12237. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  12238. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  12239. if (height === 0) {
  12240. return;
  12241. }
  12242. const va = width / height;
  12243. const vpa = that.videoParentAspectRatio;
  12244. if (vpa > va) {
  12245. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  12246. } else {
  12247. that.videoWidth = '100%';
  12248. }
  12249. if (width && height) {
  12250. that.videoAspectRatio = width / height;
  12251. }
  12252. LogUtils.getInstance()
  12253. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  12254. that.hideLoadIng();
  12255. }
  12256. }
  12257. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  12258. let mOnPreparedListener: OnPreparedListener = {
  12259. onPrepared: async () => {
  12260. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  12261. try {
  12262. //保存碰一碰分享的当前的歌曲
  12263. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  12264. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  12265. await this.initLyric(lyricPath);
  12266. const preparedDuration = this.mIjkMediaPlayer.getDuration();
  12267. if (preparedDuration > 0) {
  12268. this.duration = preparedDuration;
  12269. this.durationTime = Math.floor(preparedDuration / 1000);
  12270. this.durationStringTime = secondToTime(this.durationTime);
  12271. }
  12272. setTimeout(() => {
  12273. this.avSessionController.initAvSession(false);
  12274. if (this.duration > 0) {
  12275. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  12276. }
  12277. this.setAvSessionListener();
  12278. this.updateSessionPlayState(true)
  12279. this.setCurrentPlayMode()
  12280. }, 500)
  12281. if(startOffset&&startOffset>0){//cue分轨播放
  12282. this.seekTo(startOffset + "");
  12283. this.saveLastPlayList()
  12284. return
  12285. }
  12286. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12287. let timeoutPlay = 0
  12288. if (StrUtil.isNotEmpty(this.videoUrl) &&
  12289. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  12290. timeoutPlay = 1000
  12291. }
  12292. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  12293. if (this.modeType === 0) { //文件夹
  12294. let parentPath = FileUtil.getParentPath(this.videoUrl)
  12295. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  12296. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  12297. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  12298. } else if (this.modeType === 1) { //媒体库
  12299. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  12300. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  12301. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  12302. } else if (this.modeType === 2) { //艺术家
  12303. if (this.currentSong?.artist) {
  12304. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  12305. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  12306. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  12307. }
  12308. } else if (this.modeType === 3) { //专辑
  12309. if (this.currentSong?.album) {
  12310. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  12311. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  12312. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  12313. }
  12314. }
  12315. this.duration = this.mIjkMediaPlayer.getDuration()
  12316. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  12317. if (this.mIjkMediaPlayer != null) {
  12318. let jumpTopTimeMs = this.jumpTopTime*1000;
  12319. if (jumpTopTimeMs <= this.duration) {
  12320. // 调用 seekTo 方法,跳到指定时间
  12321. if(PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY,true)){
  12322. console.log('onecold jumpTopTime = '+jumpTopTimeMs);
  12323. const position:number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  12324. console.log('onecold position = '+position);
  12325. if (position > jumpTopTimeMs) {
  12326. jumpTopTimeMs = position
  12327. }
  12328. }
  12329. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12330. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  12331. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  12332. }
  12333. }, timeoutPlay)
  12334. } else {
  12335. // 提示用户无法跳过
  12336. ToastUtil.showToast('跳过时间超过视频时长');
  12337. }
  12338. }
  12339. } else {
  12340. this.jumpTopTime = 0
  12341. this.jumpEndTime = 0
  12342. // console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  12343. // console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  12344. // console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  12345. // PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  12346. //记忆播放(每一首都会记忆播放)
  12347. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  12348. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12349. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  12350. this.restorePlaybackPosition() //读取播放记忆功能
  12351. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  12352. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  12353. this.restorePlaybackPosition() //读取播放记忆功能
  12354. }
  12355. this.isFirstStartPlay = false
  12356. }, timeoutPlay)
  12357. } else {
  12358. this.isFirstStartPlay = false
  12359. }
  12360. }
  12361. this.saveLastPlayList()
  12362. } catch (error) {
  12363. let err: BusinessError = error as BusinessError;
  12364. console.error('onecold failed with err: ' + JSON.stringify(err));
  12365. }
  12366. }
  12367. }
  12368. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  12369. let mOnTimedTextListener: OnTimedTextListener = {
  12370. onTimedText: () => {
  12371. }
  12372. }
  12373. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  12374. let mOnCompletionListener: OnCompletionListener = {
  12375. onCompletion: () => {
  12376. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  12377. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  12378. // 异步调用playNext
  12379. this.playNext().catch(() => {
  12380. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  12381. });
  12382. } else if (this.playType == 1) { //1:单片重复播放
  12383. this.CONTROL_PlayStatus = PlayStatus.INIT
  12384. that.startPlayOrResumePlay();
  12385. } else if (this.playType == 2) { //2:正常播放,单曲播完
  12386. that.showRePlay();
  12387. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  12388. that.progressValue = this.PROGRESS_MAX_VALUE;
  12389. that.slideEnable = false;
  12390. that.stop();
  12391. // ToastUtil.showToast('开始重新播放')
  12392. } else if (this.playType == 3) { //3:随机播放
  12393. // 异步调用randomPlay
  12394. this.randomPlay().catch(() => {
  12395. Logger.error('heanup OnCompletionListener randomPlay', `随机播放失败`);
  12396. });
  12397. }
  12398. }
  12399. }
  12400. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  12401. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  12402. onBufferingUpdate: (percent: number) => {
  12403. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  12404. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  12405. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  12406. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  12407. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  12408. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  12409. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  12410. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  12411. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  12412. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  12413. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  12414. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  12415. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  12416. let Looping = this.mIjkMediaPlayer.isLooping()
  12417. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  12418. }
  12419. }
  12420. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  12421. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  12422. onSeekComplete: () => {
  12423. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  12424. console.info('onecold startPlayOrResumePlay 10643')
  12425. that.startPlayOrResumePlay();
  12426. }
  12427. }
  12428. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  12429. let mOnInfoListener: OnInfoListener = {
  12430. onInfo: (what: number, extra: number) => {
  12431. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  12432. that.hideLoadIng();
  12433. }
  12434. }
  12435. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  12436. let mOnErrorListener: OnErrorListener = {
  12437. onError: (what: number, extra: number) => {
  12438. this.stopProgressTask();
  12439. LogUtils.getInstance().LOGI("heanup OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  12440. LogUtils.getInstance().LOGI('heanup 播放错误,歌曲详情:' + JSON.stringify(this.currentSong))
  12441. // 检查是否为WebDAV播放错误
  12442. let isWebDavError = false;
  12443. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.currentSong.filePath) {
  12444. try {
  12445. const globalContext = GlobalContext.getContext();
  12446. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  12447. if (webDavAuthInfo) {
  12448. isWebDavError = true;
  12449. }
  12450. } catch (error) {
  12451. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  12452. }
  12453. }
  12454. if (isWebDavError) {
  12455. Logger.error(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  12456. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  12457. // this.currentWebDavAuthInfo = null;
  12458. Logger.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  12459. // 根据错误代码提供更具体的错误信息
  12460. let errorMessage = "WebDAV播放失败";
  12461. if (what === -1) { // 网络错误
  12462. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  12463. } else if (what === -1004) { // HTTP 404
  12464. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  12465. } else if (what === -1001) { // 超时
  12466. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  12467. } else if (what === -1003) { // 无法解析主机
  12468. errorMessage = "无法连接到WebDAV服务器";
  12469. }
  12470. ToastUtil.showToast(errorMessage);
  12471. } else {
  12472. if (StrUtil.isNotEmpty(this.videoUrl) &&
  12473. !this.videoUrl.startsWith('http://') &&
  12474. !this.videoUrl.startsWith('https://') &&
  12475. !FileUtil.accessSync(this.videoUrl)) {
  12476. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  12477. }
  12478. }
  12479. that.hideLoadIng();
  12480. }
  12481. }
  12482. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  12483. this.mIjkMediaPlayer.setMessageListener();
  12484. this.mIjkMediaPlayer.prepareAsync();
  12485. this.mIjkMediaPlayer.start();
  12486. }
  12487. //保存最后播放的那首歌和已经对应的播放列表
  12488. saveLastPlayList() {
  12489. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  12490. PreferencesUtil.putSync('LastMusicList', this.songList)
  12491. }
  12492. // 清空播放记录
  12493. clearVideoHistory() {
  12494. this.table.clearPlayHistory((success: boolean, error?: string) => {
  12495. if (success) {
  12496. this.historyList = [];
  12497. this.updateListData(this.historyList)
  12498. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  12499. ToastUtil.showToast('清空播放记录成功')
  12500. } else {
  12501. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  12502. }
  12503. });
  12504. }
  12505. public async setAvSessionListener() {
  12506. if (!this.avSessionController) {
  12507. return;
  12508. }
  12509. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  12510. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  12511. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  12512. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  12513. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  12514. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  12515. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  12516. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  12517. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  12518. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  12519. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  12520. }
  12521. setLoopMode() {
  12522. let itype = this.playType + 1
  12523. if (itype >= 4) {
  12524. this.playType = 0
  12525. ToastUtil.showToast('连续播放')
  12526. } else if (itype === 1) {
  12527. this.playType = 1
  12528. ToastUtil.showToast('单曲循环')
  12529. } else if (itype === 2) {
  12530. this.playType = 2
  12531. ToastUtil.showToast('单曲播完')
  12532. } else if (itype === 3) {
  12533. this.playType = 3
  12534. ToastUtil.showToast('随机播放')
  12535. } else if (itype === 0) {
  12536. this.playType = 0
  12537. ToastUtil.showToast('连续播放')
  12538. }
  12539. PreferencesUtil.putSync('musicPlayType', this.playType)
  12540. this.setCurrentPlayMode()
  12541. }
  12542. private sessionSetLoopModeCallback = (mode: number) => {
  12543. if (this.mIjkMediaPlayer != null) {
  12544. ToastUtil.showToast('当前播放模式:' + mode)
  12545. Logger.info('onecold 当前播放模式= ' + mode)
  12546. let hmPlayMode = mode + 1
  12547. if (hmPlayMode >= 4) {
  12548. hmPlayMode = 0
  12549. }
  12550. if (hmPlayMode === 1) {
  12551. this.playType = 1
  12552. ToastUtil.showToast('单曲循环')
  12553. } else if (hmPlayMode === 0) {
  12554. this.playType = 2
  12555. ToastUtil.showToast('单曲播完')
  12556. } else if (hmPlayMode === 3) {
  12557. this.playType = 3
  12558. ToastUtil.showToast('随机播放')
  12559. } else if (hmPlayMode === 2) {
  12560. this.playType = 0
  12561. ToastUtil.showToast('连续播放')
  12562. }
  12563. PreferencesUtil.putSync('musicPlayType', this.playType)
  12564. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  12565. let playBackState: avSession.AVPlaybackState = {
  12566. loopMode: hmPlayMode,
  12567. };
  12568. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  12569. console.info(`set setLoopMode AVPlaybackState successfully`);
  12570. }).catch((err: BusinessError) => {
  12571. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  12572. });
  12573. }
  12574. }
  12575. setCurrentPlayMode() {
  12576. if (!this.avSessionController) {
  12577. return;
  12578. }
  12579. let mLoopMode = 0
  12580. switch (this.playType) {
  12581. case 0:
  12582. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  12583. break;
  12584. case 1:
  12585. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  12586. break;
  12587. case 2:
  12588. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  12589. break;
  12590. case 3:
  12591. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  12592. break;
  12593. }
  12594. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  12595. let playBState: avSession.AVPlaybackState = {
  12596. loopMode: mLoopMode,
  12597. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  12598. };
  12599. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  12600. console.info(`set setLoopMode AVPlaybackState successfully`);
  12601. }).catch((err: BusinessError) => {
  12602. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  12603. });
  12604. }
  12605. private sessionToggleFavoriteCallback = (assetId: string) => {
  12606. if (this.mIjkMediaPlayer != null && this.currentSong) {
  12607. console.info(`on toggleFavorite `);
  12608. // 应用收到收藏命令,进行收藏处理。
  12609. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  12610. this.doFav(this.currentSong)
  12611. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  12612. let playbackState: avSession.AVPlaybackState = {
  12613. isFavorite: !this.isFac,
  12614. };
  12615. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  12616. console.info(`SetAVPlaybackState successfully`);
  12617. }).catch((err: BusinessError) => {
  12618. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  12619. });
  12620. }
  12621. }
  12622. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  12623. device: avSession.OutputDeviceInfo) => {
  12624. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  12625. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  12626. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  12627. await this.startCasting();
  12628. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  12629. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  12630. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  12631. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  12632. if (device) {
  12633. this.endCasting();
  12634. }
  12635. }
  12636. };
  12637. private async startCasting() {
  12638. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  12639. this.setPlaybackStateChangeListener();
  12640. this.pause();
  12641. this.initQueueItem();
  12642. this.prepare();
  12643. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  12644. refToIsCasting?.set(true);
  12645. this.castSeek = true;
  12646. this.isCastPlaying = true;
  12647. }
  12648. async changeCasting() {
  12649. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  12650. this.initQueueItem();
  12651. this.prepare();
  12652. this.setPlaybackStateChangeListener();
  12653. this.isCastPlaying = true;
  12654. this.castSeek = true;
  12655. }
  12656. public endCasting() {
  12657. this.avSessionController.getAvSession()?.stopCasting();
  12658. this.stopCast();
  12659. this.isCastPlaying = false;
  12660. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  12661. refToIsCasting?.set(false);
  12662. this.pause();
  12663. this.setIsPlaying(false);
  12664. // if (this.curIndex === this.curSource.index) {
  12665. // this.play
  12666. // this.seek(this.currentTime * 1000);
  12667. // this.setIsPlaying(true);
  12668. // } else {
  12669. // this.pauseVideo();
  12670. // this.setIsPlaying(false);
  12671. // }
  12672. }
  12673. public setIsPlaying(isPlayer: boolean) {
  12674. this.isPlaying = isPlayer;
  12675. // 发送播放状态变化事件给歌单详情页面
  12676. try {
  12677. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  12678. const currentFilePath = this.currentSong?.filePath || ''
  12679. const eventData: emitter.EventData = {
  12680. data: {
  12681. isPlaying: this.isPlaying,
  12682. curIndex: this.curIndex,
  12683. currentFilePath: currentFilePath
  12684. }
  12685. };
  12686. emitter.emit(eventPlaybackStatus, eventData)
  12687. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  12688. } catch (error) {
  12689. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  12690. }
  12691. }
  12692. private setPlaybackStateChangeListener(): void {
  12693. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  12694. this.castController?.on('endOfStream', this.reloadCasting);
  12695. this.castController?.on('playNext', this.playNextCallback);
  12696. this.castController?.on('playPrevious', this.playPreviousCallback);
  12697. }
  12698. private updateSessionPlayState(isPlay: boolean): void {
  12699. // if(!this.isBgPlayOpen)
  12700. // return
  12701. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  12702. this.setAVSessionPlayState({
  12703. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  12704. position: {
  12705. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  12706. updateTime: new Date().getTime()
  12707. }
  12708. });
  12709. }
  12710. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  12711. this.avSessionController.setAvSessionPlayState(playbackState)
  12712. }
  12713. private positionChange(position: number) {
  12714. this.currentTime2 = position / 1000;
  12715. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  12716. }
  12717. private playDurationChange(duration: number) {
  12718. this.duration = duration;
  12719. this.durationTime = Math.floor(this.duration / 1000);
  12720. this.durationStringTime = secondToTime((this.durationTime));
  12721. }
  12722. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  12723. const duration = playbackState?.extras?.duration;
  12724. if (typeof duration === 'number') {
  12725. this.playDurationChange(duration as number);
  12726. }
  12727. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  12728. this.positionChange(playbackState?.position?.elapsedTime);
  12729. }
  12730. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  12731. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  12732. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  12733. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  12734. this.isCastPlaying = false;
  12735. }
  12736. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  12737. this.isCastPlaying = true;
  12738. }
  12739. };
  12740. private reloadCasting = async () => {
  12741. let item = this.songList[this.curIndex];
  12742. let uri = fileUri.getUriFromPath(item.filePath);
  12743. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  12744. // description.startPosition = 0;
  12745. this.castItem = {
  12746. itemId: this.curIndex,
  12747. description: {
  12748. assetId: item.filePath,
  12749. title: item.name,
  12750. artist: '',
  12751. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  12752. // mediaUri: item.filePath,
  12753. fdSrc: {
  12754. fd: file.fd
  12755. },
  12756. // 该字段大写,音频'AUDIO',视频'VIDEO'
  12757. mediaType: 'VIDEO',
  12758. mediaSize: item.videoSize,
  12759. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  12760. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  12761. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  12762. duration: this.duration,
  12763. // albumCoverUri: 'https://www.example.jpeg',
  12764. // albumTitle: '《ExampleAlbum》',
  12765. appName: this.appName,
  12766. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  12767. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  12768. }
  12769. };
  12770. this.prepare();
  12771. this.isCastPlaying = true;
  12772. };
  12773. public playNextCallback = (): void => {
  12774. this.playNext().catch(() => {
  12775. Logger.error('heanup playNextCallback', `播放下一首失败`);
  12776. });
  12777. };
  12778. public playPreviousCallback = (): void => {
  12779. this.playPrevious().catch(() => {
  12780. Logger.error('heanup playNextCallback', `播放上一首失败`);
  12781. });
  12782. };
  12783. async prepare() {
  12784. await this.castController?.prepare(this.castItem);
  12785. await this.castController?.start(this.castItem);
  12786. }
  12787. public initQueueItem() {
  12788. let item = this.songList[this.curIndex];
  12789. let time = this.currentTime;
  12790. let uri = fileUri.getUriFromPath(item.filePath);
  12791. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  12792. this.castItem = {
  12793. itemId: this.curIndex,
  12794. description: {
  12795. assetId: item.filePath,
  12796. title: item.name,
  12797. artist: '',
  12798. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  12799. fdSrc: {
  12800. fd: file.fd
  12801. },
  12802. // 该字段大写,音频'AUDIO',视频'VIDEO'
  12803. mediaType: 'AUDIO',
  12804. mediaSize: item.videoSize,
  12805. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  12806. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  12807. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  12808. duration: this.duration,
  12809. // albumCoverUri: 'https://www.example.jpeg',
  12810. // albumTitle: '《ExampleAlbum》',
  12811. appName: this.appName,
  12812. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  12813. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  12814. }
  12815. };
  12816. }
  12817. async stopCast() {
  12818. try {
  12819. this.castController?.off('playbackStateChange');
  12820. this.castController?.off('endOfStream');
  12821. this.castController?.off('playNext');
  12822. this.castController?.off('playPrevious');
  12823. this.castController?.off('error');
  12824. } catch (error) {
  12825. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  12826. }
  12827. }
  12828. private sessionPlayCallback = (): void => {
  12829. this.playOrPause()
  12830. };
  12831. private sessionPauseCallback = (): void => {
  12832. this.pause()
  12833. };
  12834. private playOrPause() {
  12835. if (!this.debounce()) {
  12836. return;
  12837. }
  12838. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  12839. this.pause();
  12840. } else {
  12841. console.info('onecold startPlayOrResumePlay 11064')
  12842. this.startPlayOrResumePlay();
  12843. this.playChange()
  12844. }
  12845. }
  12846. private sessionPlayNextCallback = (): void => {
  12847. this.playNext().catch(() => {
  12848. Logger.error('heanup sessionPlayPreviousCallback', `播放下 一首失败`);
  12849. });
  12850. };
  12851. private sessionPlayPreviousCallback = (): void => {
  12852. this.playPrevious().catch(() => {
  12853. Logger.error('heanup sessionPlayPreviousCallback', `播放上一首失败`);
  12854. });
  12855. };
  12856. private sessionStopCallback = (): void => {
  12857. this.stop()
  12858. };
  12859. private sessionFastForwardCallback = (time?: number) => {
  12860. if (!time) {
  12861. return;
  12862. }
  12863. if (this.mIjkMediaPlayer != null) {
  12864. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12865. let seeTime = curPosition + time * 1000;
  12866. // 限制 seekValue 在合法范围内
  12867. if (seeTime < 0) {
  12868. seeTime = 0;
  12869. } else if (seeTime > this.duration) {
  12870. seeTime = this.duration;
  12871. }
  12872. Logger.info('onecold seeTime= ' + seeTime)
  12873. this.setSeekToActionProgress(seeTime)
  12874. this.seekTo(seeTime + "")
  12875. }
  12876. };
  12877. /**
  12878. * Gesture method onActionUpdate.
  12879. *
  12880. * @param event Gesture event.手势拖动设置快进和后退
  12881. */
  12882. private setSeekToActionProgress(position: number) {
  12883. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  12884. let duration = this.mIjkMediaPlayer.getDuration();
  12885. let pos = 0;
  12886. if (duration > 0) {
  12887. this.slideEnable = true;
  12888. let curPercent = position / duration;
  12889. pos = curPercent * 100;
  12890. if (pos > this.PROGRESS_MAX_VALUE) {
  12891. this.progressValue = this.PROGRESS_MAX_VALUE
  12892. } else {
  12893. this.progressValue = pos;
  12894. }
  12895. }
  12896. // LogUtils.getInstance()
  12897. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  12898. this.totalTime = this.stringForTime(duration);
  12899. if (position > duration) {
  12900. position = duration;
  12901. }
  12902. this.isCurrentTime = true;
  12903. this.currentTime = this.stringForTime(position);
  12904. this.isCurrentTime = false
  12905. }
  12906. private sessionRewindCallback = (time?: number) => {
  12907. if (!time) {
  12908. return;
  12909. }
  12910. if (this.mIjkMediaPlayer != null) {
  12911. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12912. let seeTime = curPosition - time * 1000;
  12913. // 限制 seekValue 在合法范围内
  12914. if (seeTime < 0) {
  12915. seeTime = 0;
  12916. } else if (seeTime > this.duration) {
  12917. seeTime = this.duration;
  12918. }
  12919. Logger.info('onecold seeTime= ' + seeTime)
  12920. this.setSeekToActionProgress(seeTime)
  12921. this.seekTo(seeTime + "")
  12922. }
  12923. };
  12924. private sessionSeekCallback = (seekTime: number) => {
  12925. if (this.mIjkMediaPlayer != null) {
  12926. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12927. this.seekTo(seekTime + "")
  12928. }
  12929. };
  12930. private async getFileSize(filePath: string): Promise<number> {
  12931. try {
  12932. const stat = await fs.stat(filePath);
  12933. return stat.size;
  12934. } catch (err) {
  12935. console.error('Failed to get file size: ' + err.message);
  12936. return 0;
  12937. }
  12938. }
  12939. private pause() {
  12940. if (this.mIjkMediaPlayer.isPlaying()) {
  12941. this.savePlaybackPosition();
  12942. this.mIjkMediaPlayer.pause();
  12943. this.setProgress();
  12944. this.mDestroyPage = true;
  12945. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  12946. this.updateSessionPlayState(false)
  12947. this.playChange()
  12948. if (this.pipController) {
  12949. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  12950. PiPWindow.PiPControlStatus.PAUSE);
  12951. }
  12952. }
  12953. }
  12954. private stop() {
  12955. this.savePlaybackPosition();
  12956. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12957. this.mIjkMediaPlayer.stop();
  12958. this.mIjkMediaPlayer.release();
  12959. this.stopProgressTask();
  12960. this.updateSessionPlayState(false)
  12961. this.playChange()
  12962. this.watchStatus();
  12963. }
  12964. //保持记忆播放功能
  12965. private savePlaybackPosition() {
  12966. if (this.mIjkMediaPlayer != null) {
  12967. const position = this.mIjkMediaPlayer.getCurrentPosition();
  12968. // ToastUtil.showToast('保存记忆播放 = ' + position)
  12969. const duration = this.mIjkMediaPlayer.getDuration();
  12970. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  12971. // 如果播放位置接近视频末尾,则保存 position 为 0
  12972. const playbackPosition = (duration - position < threshold) ? 0 : position;
  12973. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  12974. }
  12975. }
  12976. //获取记忆播放功能
  12977. private restorePlaybackPosition() {
  12978. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  12979. // ToastUtil.showToast('position = ' + position)
  12980. if (this.mIjkMediaPlayer != null && position > 0) {
  12981. // ToastUtil.showToast('seekTo = ' + position)
  12982. this.seekTo(position + "");
  12983. }
  12984. }
  12985. private seekTo(value: string) {
  12986. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  12987. ToastUtil.showToast('wma格式不支持拖动快进。')
  12988. return
  12989. }
  12990. this.isSeekTo = true
  12991. this.mIjkMediaPlayer.seekTo(value);
  12992. console.info('onecold startPlayOrResumePlay 11227')
  12993. // this.startPlayOrResumePlay()
  12994. // 在这里恢复计时器状态
  12995. this.setProgress()
  12996. this.isSeekTo = false
  12997. }
  12998. // 添加到下一首播放
  12999. private addToNextPlay(song: VideoItem) {
  13000. if (!this.debounce()) {
  13001. return;
  13002. }
  13003. if (this.currentSong) {
  13004. if (this.currentSong === song) {
  13005. ToastUtil.showToast('当前已经在播放这首歌了!')
  13006. return
  13007. }
  13008. }
  13009. // 如果未开始播放或队列为空
  13010. if (this.curIndex === -1 || this.songList.length === 0) {
  13011. this.songList = [song];
  13012. this.curIndex = 0;
  13013. this.doPlay(song)
  13014. return;
  13015. }
  13016. // 插入到当前索引+1的位置
  13017. const insertPos = this.curIndex + 1;
  13018. this.songList.splice(insertPos, 0, song);
  13019. this.songList = [...this.songList]; // 触发状态更新
  13020. this.sonDataSource.pushArrayData(this.songList)
  13021. ToastUtil.showToast('已添加至下一首播放')
  13022. }
  13023. //后退10s,可再设置设置默认几秒
  13024. backForward() {
  13025. if(this.mIjkMediaPlayer){
  13026. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  13027. let value = pos - Number(this.fastForwardSeconds) * 1000;
  13028. this.seekTo(value+"");
  13029. }
  13030. }
  13031. //快进10s,可再设置设置默认几秒
  13032. fastForward() {
  13033. if(this.mIjkMediaPlayer){
  13034. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  13035. let value = pos + Number(this.fastForwardSeconds) * 1000;
  13036. this.seekTo(value+"");
  13037. }
  13038. }
  13039. //下一个
  13040. private async playNext() {
  13041. if (!this.debounce()) {
  13042. return;
  13043. }
  13044. if (this.playType == 3) { //3:随机播放
  13045. await this.randomPlay()
  13046. return;
  13047. }
  13048. if (ArrayUtil.isNotEmpty(this.songList)) {
  13049. if (this.curIndex == this.songList.length - 1) {
  13050. this.curIndex = 0;
  13051. } else {
  13052. this.curIndex++;
  13053. }
  13054. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13055. this.stop();
  13056. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  13057. this.currentSong = this.songList[this.curIndex];
  13058. Logger.info('heanup playNext', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  13059. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13060. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13061. context: this.context,
  13062. autoParseMusicName: this.autoParseMusicName
  13063. });
  13064. this.artist = this.songList[this.curIndex].artist
  13065. this.name = this.songList[this.curIndex].name
  13066. //this.cover = this.songList[this.curIndex].pixelMapPath
  13067. this.changeImageAnimation()
  13068. }
  13069. }
  13070. changeImageAnimation() {
  13071. if(this.openSkipSongAnimate){
  13072. // 第一步:淡出动画
  13073. this.getUIContext()?.animateTo({
  13074. duration: 500,
  13075. curve: Curve.EaseOut,
  13076. }, () => {
  13077. this.opacityValueImage = 0.1;
  13078. if(this.isCoverRectangle){
  13079. this.scaleValueImage = 0.88
  13080. }
  13081. });
  13082. // 第二步:切换图片后淡入
  13083. setTimeout(() => {
  13084. this.cover = this.songList[this.curIndex].pixelMapPath
  13085. this.getUIContext()?.animateTo({
  13086. duration: 500,
  13087. curve: Curve.EaseIn,
  13088. }, () => {
  13089. this.opacityValueImage = 1;
  13090. this.scaleValueImage = 1 // 图标恢复到原始大小
  13091. this.startPlayOrResumePlay()
  13092. });
  13093. }, 500);
  13094. }else{
  13095. this.cover = this.songList[this.curIndex].pixelMapPath
  13096. this.startPlayOrResumePlay()
  13097. }
  13098. }
  13099. // 存储已播放的歌曲索引
  13100. private playedIndices: Set<number> = new Set();
  13101. //随机播放
  13102. private async randomPlay() {
  13103. // if (!this.debounce()) {
  13104. // return;
  13105. // }
  13106. if (ArrayUtil.isNotEmpty(this.songList)) {
  13107. if (this.songList.length > 3) {
  13108. // 如果所有歌曲都播放过一次,清空已播放索引集合
  13109. if (this.playedIndices.size === this.songList.length) {
  13110. this.playedIndices.clear();
  13111. }
  13112. // 随机选择一个未播放的歌曲索引
  13113. let newIndex: number;
  13114. // 添加超时机制防止无限循环
  13115. let attempt = 0;
  13116. const maxAttempts = 100; // 根据需求调整
  13117. do {
  13118. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  13119. attempt++;
  13120. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  13121. if (attempt >= maxAttempts) {
  13122. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  13123. newIndex = Math.floor(Math.random() * this.songList.length);
  13124. }
  13125. this.curIndex = newIndex;
  13126. this.playedIndices.add(newIndex);
  13127. } else {
  13128. // 当歌曲数量小于或等于3时,直接播放下一首
  13129. if (this.curIndex == this.songList.length - 1) {
  13130. this.curIndex = 0;
  13131. } else {
  13132. this.curIndex++;
  13133. }
  13134. }
  13135. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13136. this.stop();
  13137. this.currentSong = this.songList[this.curIndex];
  13138. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13139. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13140. context: this.context,
  13141. autoParseMusicName: this.autoParseMusicName
  13142. });
  13143. this.name = this.songList[this.curIndex].name;
  13144. this.artist = this.songList[this.curIndex].artist
  13145. // this.cover = this.songList[this.curIndex].pixelMapPath
  13146. this.changeImageAnimation()
  13147. }
  13148. }
  13149. private async playIndex(index: number) {
  13150. if (!this.debounce()) {
  13151. return;
  13152. }
  13153. if (ArrayUtil.isNotEmpty(this.songList)) {
  13154. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13155. this.stop();
  13156. this.curIndex = index;
  13157. this.currentSong = this.songList[index];
  13158. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13159. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13160. context: this.context,
  13161. autoParseMusicName: this.autoParseMusicName
  13162. });
  13163. this.name = this.currentSong.name
  13164. this.artist = this.currentSong.artist
  13165. this.changeImageAnimation()
  13166. }
  13167. }
  13168. //上一个
  13169. private async playPrevious() {
  13170. if (!this.debounce()) {
  13171. return;
  13172. }
  13173. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  13174. this.randomModePlayFromHistory()
  13175. return;
  13176. }
  13177. if (this.curIndex == 0) {
  13178. this.curIndex = this.songList.length - 1;
  13179. } else {
  13180. this.curIndex--;
  13181. }
  13182. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13183. this.stop();
  13184. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  13185. this.currentSong = this.songList[this.curIndex];
  13186. Logger.info('heanup playPrevious', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  13187. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13188. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13189. context: this.context,
  13190. autoParseMusicName: this.autoParseMusicName
  13191. });
  13192. this.name = this.songList[this.curIndex].name
  13193. this.artist = this.songList[this.curIndex].artist
  13194. this.changeImageAnimation()
  13195. }
  13196. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  13197. private async randomModePlayFromHistory() {
  13198. if (this.historyList.length >= 2) {
  13199. // 播放历史记录的第二首
  13200. const prevSong = this.historyList[1];
  13201. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  13202. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13203. this.stop();
  13204. // 直接使用历史记录中的歌曲信息,历史记录中的数据应该是完整的
  13205. this.currentSong = prevSong;
  13206. Logger.info('heanup randomModePlayFromHistory', `直接使用历史歌曲信息: ${prevSong.name}, type: ${prevSong.type}`);
  13207. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13208. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13209. context: this.context,
  13210. autoParseMusicName: this.autoParseMusicName
  13211. });
  13212. this.cover = prevSong.pixelMapPath
  13213. this.artist = prevSong.artist
  13214. this.name = prevSong.name;
  13215. console.info('onecold startPlayOrResumePlay 11434')
  13216. this.startPlayOrResumePlay();
  13217. } else {
  13218. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  13219. if (this.curIndex === 0) {
  13220. this.curIndex = this.songList.length - 1;
  13221. } else {
  13222. this.curIndex--;
  13223. }
  13224. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13225. this.stop();
  13226. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  13227. this.currentSong = this.songList[this.curIndex];
  13228. Logger.info('heanup randomModePlayFromHistory', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  13229. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13230. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13231. context: this.context,
  13232. autoParseMusicName: this.autoParseMusicName
  13233. });
  13234. this.artist = this.songList[this.curIndex].artist
  13235. this.name = this.songList[this.curIndex].name;
  13236. this.changeImageAnimation()
  13237. }
  13238. }
  13239. debounce() {
  13240. const delay = 600;
  13241. let cur = new Date().getTime();
  13242. if (cur - this.last > delay) {
  13243. this.last = cur;
  13244. return true;
  13245. }
  13246. return false;
  13247. }
  13248. /**
  13249. * Sets whether the screen is a constant based on the playback status.
  13250. */
  13251. watchStatus() {
  13252. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  13253. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  13254. this.windowClass.setWindowKeepScreenOn(true);
  13255. } else {
  13256. this.windowClass.setWindowKeepScreenOn(false);
  13257. }
  13258. }
  13259. /**
  13260. * Volume gesture method onActionStart.
  13261. *
  13262. * @param event Gesture event.
  13263. */
  13264. private customDialogComponentIdMM: number = 0
  13265. @Builder
  13266. customDialogComponentMM() {
  13267. Column() {
  13268. Row() {
  13269. Blank()
  13270. Text('验证密码')
  13271. .fontSize(22)
  13272. .fontColor($r('app.color.pri_bg'))
  13273. .margin({ top: 18 })
  13274. Blank()
  13275. Image($r('app.media.close'))
  13276. .fillColor(Color.White)
  13277. .margin({ top: 18, right: 18 })
  13278. .width(20)
  13279. .onClick(() => {
  13280. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  13281. })
  13282. }
  13283. .width('100%') // 使Row占据整个宽度
  13284. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  13285. Verify({
  13286. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  13287. });
  13288. }.height('60%')
  13289. .backgroundColor($r('app.color.index_background'))
  13290. .justifyContent(FlexAlign.SpaceBetween)
  13291. }
  13292. private handleVerifyCompleted(isSuccess: boolean) {
  13293. if (isSuccess) {
  13294. console.log('验证成功');
  13295. // 在这里处理验证成功后的逻辑
  13296. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  13297. this.currentPath = this.lockPath
  13298. this.getSortedFiles(this.currentPath)
  13299. } else {
  13300. // console.log('验证失败');
  13301. ToastUtil.showToast('验证失败')
  13302. }
  13303. }
  13304. private showVerifyDialog() {
  13305. promptAction.openCustomDialog({
  13306. transition: TransitionEffect.asymmetric(
  13307. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  13308. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  13309. ,
  13310. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  13311. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  13312. ),
  13313. builder: () => {
  13314. this.customDialogComponentMM()
  13315. },
  13316. isModal: true,
  13317. autoCancel: true,
  13318. maskColor: Color.Transparent,
  13319. alignment: DialogAlignment.Bottom,
  13320. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  13321. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  13322. console.log("dialog onWillDismiss")
  13323. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  13324. dismissDialogAction.dismiss()
  13325. }
  13326. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  13327. dismissDialogAction.dismiss()
  13328. }
  13329. }
  13330. }).then((dialogId: number) => {
  13331. this.customDialogComponentIdMM = dialogId
  13332. })
  13333. }
  13334. //左滑操作 移动文件 重命名 删除等操作
  13335. @Builder
  13336. DeleteButton(item: VideoItem, index: number, filePath: string) {
  13337. Row() {
  13338. //加入收藏
  13339. Button() {
  13340. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  13341. .fillColor(Color.White)
  13342. .width(20)
  13343. }
  13344. .width(40)
  13345. .height(40)
  13346. .type(ButtonType.Circle)
  13347. .backgroundColor(this.themeColor)
  13348. .margin(5)
  13349. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13350. .onClick(() => {
  13351. if (item) {
  13352. this.doFav(item)
  13353. }
  13354. })
  13355. //加入下一首播放
  13356. Button() {
  13357. Image($r('app.media.next_to_play'))
  13358. .fillColor(Color.White)
  13359. .width(20)
  13360. }
  13361. .width(40)
  13362. .height(40)
  13363. .type(ButtonType.Circle)
  13364. .backgroundColor(this.themeColor)
  13365. .margin(5)
  13366. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13367. .onClick(() => {
  13368. this.addToNextPlay(item);
  13369. })
  13370. //复制文件
  13371. Button() {
  13372. Image($r('app.media.copy'))
  13373. .fillColor(Color.White)
  13374. .width(20)
  13375. }
  13376. .width(40)
  13377. .height(40)
  13378. .type(ButtonType.Circle)
  13379. .backgroundColor(this.themeColor)
  13380. .margin(5)
  13381. .id(filePath + 'copy')
  13382. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13383. .onClick(() => {
  13384. this.showCopyDialog(false, item, index, filePath + 'copy');
  13385. })
  13386. //移动文件
  13387. Button() {
  13388. Image($r('app.media.cut'))
  13389. .fillColor(Color.White)
  13390. .width(20)
  13391. }
  13392. .width(40)
  13393. .height(40)
  13394. .type(ButtonType.Circle)
  13395. .backgroundColor(this.themeColor)
  13396. .margin(5)
  13397. .id(filePath)
  13398. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13399. .onClick(() => {
  13400. this.showCutDialog(false, item, index, filePath);
  13401. })
  13402. Button() {
  13403. Image($r('app.media.cut_current'))
  13404. .fillColor(Color.White)
  13405. .width(20)
  13406. }
  13407. .width(40)
  13408. .height(40)
  13409. .type(ButtonType.Circle)
  13410. .backgroundColor(this.themeColor)
  13411. .margin(5)
  13412. .id(filePath + 'current')
  13413. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  13414. (this.isHasDir ? Visibility.Visible : Visibility.None))
  13415. .onClick(() => {
  13416. this.showCutDialog(true, item, index, filePath + 'current');
  13417. })
  13418. //重命名
  13419. Button() {
  13420. Image($r('app.media.rename2'))
  13421. .fillColor(Color.White)
  13422. .width(20)
  13423. }
  13424. .width(40)
  13425. .height(40)
  13426. .type(ButtonType.Circle)
  13427. .backgroundColor(this.themeColor)
  13428. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  13429. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  13430. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  13431. .margin(5)
  13432. .onClick(() => {
  13433. this.showReNameDialog(item, index + '', filePath)
  13434. })
  13435. Button() {
  13436. Image($r('app.media.delete2'))
  13437. .fillColor(Color.White)
  13438. .width(20)
  13439. }
  13440. .width(40)
  13441. .height(40)
  13442. .type(ButtonType.Circle)
  13443. .backgroundColor(this.themeColor)
  13444. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  13445. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  13446. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  13447. .margin(5)
  13448. .onClick(() => {
  13449. this.selectedFiles.push(item)
  13450. this.showWarnIsDelete()
  13451. // this.showWarnIsDeleteFile(item, index + '', filePath)
  13452. })
  13453. Button() {
  13454. Image($r('app.media.share2'))
  13455. .fillColor(Color.White)
  13456. .width(20)
  13457. }
  13458. .width(40)
  13459. .height(40)
  13460. .type(ButtonType.Circle)
  13461. .backgroundColor(this.themeColor)
  13462. .margin(5)
  13463. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13464. .onClick(() => {
  13465. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  13466. })
  13467. }
  13468. }
  13469. /**
  13470. * 穿山甲banner广告
  13471. */
  13472. // private declare bannerAd: CSJNativeExpressAd;
  13473. // @State private status: string = "未加载"
  13474. // @State private isShowAd: boolean = false
  13475. // private declare mAdSlot: AdSlot;
  13476. // private mBiddingAdm = '' //服务端bidding才需要设置
  13477. // private expressLoadAdListener: NativeExpressAdListener = {
  13478. // /**
  13479. // * 加载失败的回调
  13480. // *
  13481. // * @param code
  13482. // * @param message
  13483. // */
  13484. // onError: (code: number, message: string) => {
  13485. // console.error("加载广告失败,code=" + code + ",message=" + message);
  13486. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  13487. // },
  13488. //
  13489. // /**
  13490. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  13491. // *
  13492. // * @param ads 返回的广告列表
  13493. // */
  13494. //
  13495. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  13496. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  13497. // if (ads && ads.length > 0) {
  13498. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  13499. // ad.setExpressInteractionListener({
  13500. // /**
  13501. // *广告的点击回调
  13502. // * @param type 广告的交互类型
  13503. // */
  13504. // onAdClicked: (type: number) => {
  13505. // console.log("BannerExpressAdPage==onAdClicked......");
  13506. // },
  13507. //
  13508. // /**
  13509. // * 广告的展示回调 每个广告仅回调一次
  13510. // * @param type 广告的交互类型
  13511. // */
  13512. // onAdShow: (type: number) => {
  13513. // console.log("BannerExpressAdPage==onAdShow......");
  13514. // },
  13515. //
  13516. // /**
  13517. // * 模板渲染失败
  13518. // */
  13519. // onRenderFail: (code: number, msg: string) => {
  13520. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  13521. // },
  13522. //
  13523. // /**
  13524. // * 模板渲染成功
  13525. // * @param width 返回view的宽 单位 vp
  13526. // * @param height 返回view的高 单位 vp
  13527. // */
  13528. // onRenderSuccess: (width: number, height: number) => {
  13529. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  13530. // this.bannerAd = ad;
  13531. // this.status = "广告加载完成待展示";
  13532. //
  13533. // this.showBannerAd()
  13534. // }
  13535. // })
  13536. // //渲染广告
  13537. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  13538. // this.setDislikeCallback(ad); //设置dislike
  13539. // ad.render(this.getUIContext())
  13540. // this.status = "广告加载中...";
  13541. // });
  13542. // }
  13543. // }
  13544. // }
  13545. //
  13546. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  13547. // ad.setDislikeCallback({
  13548. // /**
  13549. // * dislike show
  13550. // */
  13551. // onShow: () => {
  13552. // console.log("BannerExpressAdPage==dislike......show");
  13553. // },
  13554. //
  13555. // /**
  13556. // * @param position 选择的位置
  13557. // * @param value 选择的内容
  13558. // * @param enforceRemove 是否强制关闭广告
  13559. // */
  13560. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  13561. // this.isShowAd = false;
  13562. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  13563. // ",enforce=" + enforceRemove);
  13564. // },
  13565. //
  13566. // /**
  13567. // * 点击取消
  13568. // */
  13569. // onCancel: () => {
  13570. // console.log("BannerExpressAdPage==dislike......onCancel");
  13571. // }
  13572. //
  13573. // })
  13574. // }
  13575. /**
  13576. * 加载Banner广告
  13577. */
  13578. loadBannerAd(rit: string) {
  13579. // if (Utility.isNoble()) {
  13580. // return
  13581. // }
  13582. // if (!Utility.isPassInstallTime(2)) {
  13583. // return
  13584. // }
  13585. // this.isShowAd = false;
  13586. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  13587. // this.mAdSlot = new AdSlotBuilder()
  13588. // .setCodeId(rit)
  13589. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  13590. // .setAdCount(1)
  13591. // .setBidAdm(this.mBiddingAdm)
  13592. // .build()
  13593. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  13594. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  13595. // this.status = "广告加载中..."
  13596. }
  13597. /**
  13598. * 展示Banner广告
  13599. */
  13600. // showBannerAd() {
  13601. // if (!this.bannerAd) {
  13602. // return
  13603. // }
  13604. // this.isShowAd = true
  13605. // this.status = "已展示"
  13606. // }
  13607. /**
  13608. * 穿山甲广告代码结束
  13609. */
  13610. /**
  13611. * 处理歌单播放请求
  13612. */
  13613. private async handlePlaylistPlayRequest(playlistId: string, playlistName:
  13614. string, songFilePaths: string[], startIndex: number,isJump: boolean) {
  13615. try {
  13616. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 歌曲数量: ${songFilePaths.length}, 开始索引: ${startIndex}`)
  13617. // 检查是否为WebDAV播放请求
  13618. if (playlistId === 'webdav-playlist') {
  13619. Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
  13620. // 从全局内存读取videoItems数据
  13621. const videoItems = getWebdavVideoItems();
  13622. const currentPlayIndex = getWebdavCurrentPlayIndex();
  13623. Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
  13624. if (videoItems && videoItems.length > 0) {
  13625. // 验证webdav_account_id设置情况
  13626. const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
  13627. Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
  13628. if(isJump){
  13629. this.setShowPlayTrue()//显示播放页
  13630. }
  13631. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName)
  13632. return
  13633. } else {
  13634. return
  13635. }
  13636. }
  13637. if (playlistId === 'navidrome-playlist') {
  13638. Logger.info(`heanup 检测到Navidrome播放请求,从内存读取videoItems`);
  13639. const videoItems = getNavidromeVideoItems();
  13640. const currentPlayIndex = getNavidromeCurrentPlayIndex();
  13641. Logger.info(`heanup Navidrome歌曲列表长度: ${videoItems.length}`);
  13642. if (videoItems && videoItems.length > 0) {
  13643. if(isJump){
  13644. this.setShowPlayTrue()//显示播放页
  13645. }
  13646. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName);
  13647. return;
  13648. } else {
  13649. Logger.warn('heanup Navidrome播放请求缺少歌曲数据');
  13650. return;
  13651. }
  13652. }
  13653. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  13654. const songMap: Map<number, VideoItem> = new Map()
  13655. let completedQueries = 0
  13656. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  13657. // 遍历所有文件路径,使用索引记录位置
  13658. for (let i = 0; i < songFilePaths.length; i++) {
  13659. const filePath = songFilePaths[i]
  13660. const index = i
  13661. // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  13662. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  13663. const queryPromise = this.table.queryVideoByFilePath(filePath)
  13664. // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  13665. queryPromise.then((videoItem) => {
  13666. completedQueries++
  13667. // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  13668. if (videoItem) {
  13669. // 使用索引作为key保存到Map中,保持原始顺序
  13670. songMap.set(index, videoItem)
  13671. // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  13672. } else {
  13673. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  13674. }
  13675. // 检查是否所有歌曲都已加载完成
  13676. if (completedQueries === songFilePaths.length) {
  13677. // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  13678. // 按照索引顺序重建歌曲数组
  13679. const songs: VideoItem[] = []
  13680. for (let j = 0; j < songFilePaths.length; j++) {
  13681. const song = songMap.get(j)
  13682. if (song) {
  13683. songs.push(song)
  13684. // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  13685. }
  13686. }
  13687. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  13688. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  13689. }
  13690. }).catch((error: Error) => {
  13691. completedQueries++
  13692. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  13693. // 即使出错也要检查是否完成所有查询
  13694. if (completedQueries === songFilePaths.length) {
  13695. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  13696. // 按照索引顺序重建歌曲数组
  13697. const songs: VideoItem[] = []
  13698. for (let j = 0; j < songFilePaths.length; j++) {
  13699. const song = songMap.get(j)
  13700. if (song) {
  13701. songs.push(song)
  13702. }
  13703. }
  13704. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  13705. }
  13706. })
  13707. }
  13708. } catch (error) {
  13709. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  13710. ToastUtil.showToast('播放失败')
  13711. }
  13712. }
  13713. /**
  13714. * 完成歌单加载并开始播放
  13715. */
  13716. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string) {
  13717. if (songs.length === 0) {
  13718. Logger.error('heanup 没有找到任何可播放的歌曲')
  13719. ToastUtil.showToast('没有找到可播放的歌曲')
  13720. return
  13721. }
  13722. this.songList = songs
  13723. this.sonDataSource.pushArrayData(songs)
  13724. this.sonDataSource.notifyDataReload()
  13725. this.curIndex = startIndex
  13726. if (songs[startIndex]) {
  13727. // 确保当前播放的歌曲也更新到存储
  13728. AppStorage.setOrCreate('currentSong', songs[startIndex])
  13729. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  13730. this.doPlay(songs[startIndex], startIndex, true)
  13731. }
  13732. PreferencesUtil.putSync('LastMusicList', this.songList)
  13733. // ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  13734. }
  13735. }
  13736. //视频气泡窗口的布局
  13737. @Builder
  13738. function customPopupBuilder(dataBu: BubbleBean) {
  13739. List() {
  13740. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  13741. ListItem() {
  13742. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13743. Row() {
  13744. Column() {
  13745. Image(dataBu.imageRes[index])
  13746. .height(28)
  13747. .fillColor(dataBu.color)
  13748. .alignSelf(ItemAlign.Center)
  13749. }
  13750. .width(32)
  13751. Text(item)
  13752. .padding({
  13753. top: 10,
  13754. bottom: 10,
  13755. right: 10,
  13756. left: 10
  13757. })
  13758. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  13759. .textAlign(TextAlign.Start)
  13760. .width("100%")
  13761. }
  13762. }
  13763. .backgroundColor($r('app.color.settings_background_main'))
  13764. .margin({ top: 6, bottom: 6 })
  13765. }
  13766. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  13767. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  13768. TransitionEffect.scale({ x: 0, y: 0 })))
  13769. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  13770. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  13771. .onClick(() => {
  13772. dataBu.onItemClick?.(index)
  13773. })
  13774. })
  13775. }
  13776. .scrollBar(BarState.Off)
  13777. .width(120)
  13778. .divider({
  13779. strokeWidth: 1,
  13780. color: "#22FFFFFF"
  13781. })
  13782. }
  13783. // Function to calculate a hash for the file list
  13784. function simpleHash(fileList: string[]): string {
  13785. let hash = 0;
  13786. const str = fileList.join(',');
  13787. for (let i = 0; i < str.length; i++) {
  13788. const char = str.charCodeAt(i);
  13789. hash = (hash << 5) - hash + char;
  13790. hash |= 0; // Convert to 32bit integer
  13791. }
  13792. return hash.toString();
  13793. }
  13794. interface MoreItem {
  13795. id: number;
  13796. image: Resource;
  13797. title: string;
  13798. }
  13799. //视频气泡窗口的布局
  13800. @Builder
  13801. function cutPopupBuilder(dataBu: BubbleBean) {
  13802. Column() {
  13803. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  13804. .padding({
  13805. top: 10,
  13806. bottom: 10,
  13807. right: 10,
  13808. left: 10
  13809. })
  13810. .textAlign(TextAlign.Start)
  13811. .width(160)
  13812. .fontWeight(666)
  13813. .fontSize(16)
  13814. List() {
  13815. ForEach(dataBu.data, (item: string, index: number) => {
  13816. ListItem() {
  13817. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13818. Row() {
  13819. Column() {
  13820. Image($r('app.media.music_group'))
  13821. .height(28)
  13822. .fillColor(dataBu.color)
  13823. .alignSelf(ItemAlign.Center)
  13824. }
  13825. .width(32)
  13826. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  13827. .padding({
  13828. top: 10,
  13829. bottom: 10,
  13830. right: 10,
  13831. left: 10
  13832. })
  13833. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  13834. .fontSize(15)
  13835. }
  13836. }
  13837. .backgroundColor(Color.Transparent)
  13838. .margin({ top: 7, bottom: 7 })
  13839. }
  13840. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  13841. .animation({ duration: 500 }),
  13842. TransitionEffect.scale({ x: 0, y: 0 })))
  13843. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  13844. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  13845. .onClick(() => {
  13846. dataBu.onItemClick?.(index)
  13847. })
  13848. })
  13849. }
  13850. .scrollBar(BarState.Off)
  13851. .width(150)
  13852. .divider({
  13853. strokeWidth: 1,
  13854. color: "#22FFFFFF"
  13855. })
  13856. }
  13857. .height(300)
  13858. .padding({
  13859. bottom: 30
  13860. })
  13861. }
  13862. function getFileDirName(filePath: string,rootPath:string): string{
  13863. if(filePath===rootPath){
  13864. return '首页'
  13865. }
  13866. let result = FileUtil.getFileName(filePath)
  13867. if(StrUtil.isEmpty(result))
  13868. return ''
  13869. if(result.startsWith('.'))
  13870. result = result.replace(/\./g, '')
  13871. return result
  13872. }
  13873. //只扫描当前目录下文件(不扫描子文件夹)的方法
  13874. @Concurrent
  13875. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  13876. const table: MediaTable = new MediaTable(context);
  13877. try {
  13878. // 直接获取当前目录下的文件列表
  13879. const files = FileUtil.listFileSync(dirPath);
  13880. await Promise.all(files.map(async (file) => {
  13881. const fPath = `${dirPath}/${file}`;
  13882. // 跳过目录,只处理文件
  13883. if (FileUtil.isDirectory(fPath)) {
  13884. return;
  13885. }
  13886. // 跳过特定格式文件
  13887. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  13888. return;
  13889. }
  13890. // 检查是否为媒体文件
  13891. if (Utility.isMeidaByExtension(fPath)) {
  13892. let mType = CommonConstants.TYPE_LOCAL;
  13893. if (fPath.includes(lockPath)) {
  13894. mType = CommonConstants.TYPE_LOCK;
  13895. }
  13896. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  13897. context, fPath, mType, true
  13898. );
  13899. table.insert(mediaItem, (id: number) => {
  13900. // 插入回调函数
  13901. }, cover_api);
  13902. }
  13903. }));
  13904. } catch (error) {
  13905. console.error(' 扫描当前目录失败:', error);
  13906. }
  13907. }
  13908. //内嵌标签后更新库
  13909. @Concurrent
  13910. async function updateInfoDb(
  13911. context: Context,
  13912. filePath: string,
  13913. titleStr: string,
  13914. artistStr: string,
  13915. albumStr: string,
  13916. lyricConStr: string,
  13917. yearStr: string,
  13918. genreStr: string,
  13919. trackStr: string,
  13920. albumArtistStr: string,
  13921. composerStr: string,
  13922. lyricistStr: string,
  13923. commentStr: string,
  13924. discStr: string,
  13925. ): Promise<boolean> {
  13926. const table: MediaTable = new MediaTable(context);
  13927. await new Promise<void>((resolve, reject) => {
  13928. table.getRdbStore(context, (err:Error) => {
  13929. err ? reject(err) : resolve();
  13930. });
  13931. });
  13932. return await new Promise<boolean>((resolve) => {
  13933. table.updateMediaInfo(filePath, titleStr, artistStr, albumStr, lyricConStr,
  13934. yearStr, genreStr, trackStr, albumArtistStr, composerStr, lyricistStr, commentStr, discStr,
  13935. (success: boolean, error?: string) => {
  13936. if (success) {
  13937. console.log("onecold 编辑信息成功,数据库已同步");
  13938. } else {
  13939. console.error("onecold 编辑信息数据库失败原因: " + error);
  13940. }
  13941. resolve(success);
  13942. });
  13943. });
  13944. }