LocalMusic.ets 377 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146
  1. import TitleBar from './TitleBar'
  2. import { curves, display, PiPWindow, promptAction, router, SymbolGlyphModifier, window } from '@kit.ArkUI';
  3. import { VideoItem } from '../viewmodel/VideoItem';
  4. import {
  5. AppUtil,
  6. ArrayUtil,
  7. Base64Util,
  8. DateUtil,
  9. DeviceUtil,
  10. DisplayUtil,
  11. FileUtil,
  12. ImageUtil,
  13. LogUtil,
  14. MD5,
  15. PreferencesUtil,
  16. RandomUtil,
  17. StrUtil,
  18. ToastUtil
  19. } from '@pura/harmony-utils';
  20. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  21. import { CommonConstants } from '../common/constants/CommonConstants';
  22. import Logger from '../common/util/Logger';
  23. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  24. import { Utility } from '../common/util/Utility';
  25. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  26. import { BubbleBean } from '../viewmodel/BubbleBean';
  27. import { PopupPosition, XPopup } from '@chinalike/popup';
  28. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  29. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  30. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  31. import { MessageEvents, util, worker, ErrorEvent } from '@kit.ArkTS';
  32. import { Verify } from './Verify';
  33. import { RotatingCover } from './RotatingCover';
  34. import { PlayConstants } from '../common/constants/PlayConstants';
  35. import { effectKit } from '@kit.ArkGraphics2D';
  36. import { ColorConversion } from '../common/util/ColorConversion';
  37. import { LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  38. import { AvSessionController } from '../controller/AvSessionController';
  39. import {
  40. // DeviceChangeReason,
  41. IjkMediaPlayer,
  42. InterruptEvent,
  43. InterruptHintType,
  44. LogUtils,
  45. OnBufferingUpdateListener,
  46. OnCompletionListener,
  47. OnErrorListener,
  48. OnInfoListener,
  49. OnPreparedListener,
  50. OnSeekCompleteListener,
  51. OnTimedTextListener,
  52. OnVideoSizeChangedListener
  53. } from '@ohos/ijkplayer';
  54. import { PlayStatus } from '../common/PlayStatus';
  55. import fs from '@ohos.file.fs';
  56. import { image } from '@kit.ImageKit';
  57. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  58. import * as chardet from '@changwei/chardet';
  59. import { UniversalDetector } from '@ohos/juniversalchardet';
  60. import { SettingPage } from '../pages/SettingPage';
  61. import { secondToTime } from '../common/util/CommUtils';
  62. import { CommonConstants2 } from '../common/util/CommonConstants2';
  63. import { hilog } from '@kit.PerformanceAnalysisKit';
  64. import { LazyDataSource } from '../common/util/LazyDataSource';
  65. import MediaTable from '../common/util/MediaTable';
  66. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  67. import ImageUtils from '../common/util/ImageUtils';
  68. import { ringtone } from '@kit.RingtoneKit';
  69. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  70. import { resourceManager } from '@kit.LocalizationKit';
  71. import { deviceInfo } from '@kit.BasicServicesKit';
  72. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  73. import { LrcParser } from '@sgaolei/lrc_parser';
  74. import app from '@system.app';
  75. import { TextNodeController } from './PipLyricTextBuilder';
  76. import { IndexerView } from './IndexerView';
  77. import { KeyCode } from '@kit.InputKit';
  78. import { KnockController } from '../controller/KnockController';
  79. // import { FFmpeg, FFProgressMessageParser } from '@sj/ffmpeg';
  80. const TAG = 'LocalMusic';
  81. const DEFAULT_INDEX =
  82. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  83. 'X', 'Y', 'Z']
  84. //排序类型
  85. function getTypeOrder(type: number) {
  86. switch (type) {
  87. case CommonConstants.TYPE_IS_DIR:
  88. return 1; // First
  89. case CommonConstants.TYPE_IS_CSJAD:
  90. return 2; // Middle
  91. case CommonConstants.TYPE_LOCAL:
  92. return 3; // Last
  93. default:
  94. return 4; // Unknown types, if any, go last
  95. }
  96. }
  97. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  98. // 定义接口
  99. interface HiCarAspectRatio {
  100. ratio: number;
  101. name: string;
  102. }
  103. interface GeneratedObjectLiteralInterface_1 {
  104. assetId: string;
  105. title: string;
  106. artist: string;
  107. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  108. mediaUri: string;
  109. // 该字段大写,音频'AUDIO',视频'VIDEO'
  110. mediaType: string;
  111. mediaSize: number;
  112. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  113. startPosition: number;
  114. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  115. duration: number;
  116. albumCoverUri: string;
  117. albumTitle: string;
  118. appName: string;
  119. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  120. drmScheme: string;
  121. }
  122. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  123. const ITEM_HEIGHT: number = 58; // 列表项中高度
  124. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  125. //功能强大的音乐播放器
  126. @Preview
  127. @Component
  128. export struct LocalMusic {
  129. @State opacityValueImage: number = 1;
  130. @State isAnimating: boolean = false;
  131. @State tipPopup:boolean = false
  132. @Consume mType: number;
  133. @StorageProp('themeColor') themeColor: string =
  134. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  135. themeMode: number = 0;
  136. @State titleName: string = '首页'
  137. @State textStr: string = ''
  138. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  139. // private download_path: string = '';
  140. @Consume rootPath: string //音频根目录
  141. @Consume currentPath: string
  142. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  143. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  144. @State lockPath: string = ''
  145. @State favPath: string = ''
  146. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  147. @State historyPath: string = ''
  148. @State historyList: Array<VideoItem> = []
  149. @Consume isHistory: boolean
  150. static readonly HISTORY_MUSIC: string = 'music_historyList';
  151. private table: MediaTable = new MediaTable(getContext(this))
  152. @State isZero: boolean = false
  153. @State fileList: Array<string> = []
  154. @State dirList: Array<VideoItem> = []
  155. @Consume videoLocalList: Array<VideoItem>
  156. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  157. @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  158. @State artistList: Array<VideoItem> = []; //艺术家文件
  159. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  160. @State albumList: Array<VideoItem> = []; //专辑文件
  161. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  162. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  163. @State imageOpacities: number[] = [];
  164. @Consume isCanBack: boolean
  165. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  166. @State showSingleLyric: boolean = false
  167. @State sortType: number = 4 //默认排序方式
  168. @State isShowSimi: boolean = false //是否显示私密音频
  169. @State isShowFAV: boolean = true //是否显示我的收藏
  170. @State isShowTitleBar: boolean = true //是否显示分类导航条
  171. @State isShowAllBar: boolean = true //是否显示播放全部条
  172. @State isShowHistory: boolean = true //是否显示最近播放
  173. @State isCustomizeBg: boolean = false //自定义背景界面
  174. @State isGridMusic: boolean = false //是否网格布局
  175. @State isCircleBtn: boolean = false //是否圆形播放按钮
  176. @State twoFingerType: number = 3 //双支放大缩小的类型
  177. @State isScrollHide: boolean = false //是否滚动隐藏
  178. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  179. @State isStartAutoPlay: boolean = false //启动后自动播放
  180. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  181. @State isShowHeader: boolean = true
  182. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  183. @State isShowSingleLineLyric: boolean = false //是否显示播放页返回键
  184. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  185. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  186. @State isSwipe: boolean = false //listItem的左滑开关
  187. @State customizeBgPath: string | undefined = '';
  188. @State isDarkMode: boolean = false
  189. @State lyricTextWeight: number = 400
  190. @State lyricTextWeightPip: number = 400
  191. @State currentSwiperIndex: number = 0
  192. @State blurValue: number = 0 //背景模糊
  193. @State bgBrightness: number = 0 //背景亮度
  194. private listScroller: ListScroller = new ListScroller()
  195. private playListScroller: Scroller = new Scroller()
  196. @StorageProp('isLandscape') isLandscape: boolean = false;
  197. @StorageProp('topRectHeight') topRectHeight: number = px2vp(AppUtil.getStatusBarHeight());
  198. @StorageProp('windowWidth') windowWidth: number = 0;
  199. @StorageProp('windowHeight') windowHeight: number = 0;
  200. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  201. private UNKONWN:string = '';
  202. private listArea: Area = {
  203. width: 0,
  204. height: 0,
  205. position: {},
  206. globalPosition: {}
  207. }
  208. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  209. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  210. onColorModeChange() {
  211. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  212. if (this.isCustomizeBg) {
  213. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  214. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  215. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  216. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  217. } else {
  218. if (!this.isDarkMode) {
  219. this.titleBarModel.setTitleBarBackground(this.themeColor)
  220. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  221. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  222. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  223. } else {
  224. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  225. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  226. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  227. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  228. }
  229. }
  230. }
  231. onModeChange() {
  232. this.isFavMusic = false
  233. if (this.modeType === 2 || this.modeType === 3) {
  234. this.titleBarModel.setRightIcon(null)
  235. } else {
  236. this.titleBarModel.setRightIcon(($r('app.media.add')))
  237. }
  238. LogUtil.info('onecold onModeChange = ' + this.modeType)
  239. switch (this.modeType) {
  240. case 0:
  241. this.getSortedFiles(this.currentPath)
  242. break
  243. case 1:
  244. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  245. this.updateListData(this.mediaKuList)
  246. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  247. break
  248. case 2:
  249. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  250. this.updateListData(this.artistList)
  251. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  252. break
  253. case 3:
  254. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  255. this.updateListData(this.albumList)
  256. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  257. break
  258. }
  259. }
  260. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  261. // @StorageLink('isPlay') isPlay: boolean = false;
  262. @StorageLink('isShowPlay') isShowPlay: boolean = false;
  263. @StorageLink('songList') songList: Array<VideoItem> = [];
  264. @State translateY: number = 0;
  265. @State isShowSheet: boolean = false;
  266. @State isShowSheetView: boolean = false;
  267. @State isShowTimeCloseView: boolean = false;
  268. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  269. @StorageLink('currIndex') curIndex: number = 0;
  270. @Consume isShowDrawer: boolean;
  271. @Consume offsetX: number;
  272. @State isFac: boolean = false;
  273. @State favList: Array<VideoItem> = []
  274. @Consume isFavMusic: boolean
  275. @State isClickedPLayAll: boolean = false;
  276. private scrollerForlist: ListScroller = new ListScroller();
  277. private knockController: KnockController | undefined = undefined;
  278. imagesF: ImageFrameInfo[] = [
  279. { src: $r("app.media.app_loading0") },
  280. { src: $r("app.media.app_loading1") },
  281. { src: $r("app.media.app_loading2") },
  282. { src: $r("app.media.app_loading3") },
  283. ]
  284. @State animationState: AnimationStatus = AnimationStatus.Initial
  285. // 缓存机制
  286. private cache: Map<string, Array<VideoItem>> = new Map();
  287. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  288. // 持久化缓存
  289. private async saveCacheToStorage() {
  290. const cacheArray = Array.from(this.cache.entries());
  291. const stringCacheArray = Array.from(this.stringCache.entries());
  292. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  293. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  294. }
  295. // 载入缓存
  296. private async loadCacheFromStorage() {
  297. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  298. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  299. if (cacheString) {
  300. const cacheArray: [string, Array<VideoItem>][] = JSON.parse(cacheString);
  301. this.cache = new Map(cacheArray);
  302. }
  303. if (stringCacheString) {
  304. const stringCacheArray: [string, string][] = JSON.parse(stringCacheString);
  305. this.stringCache = new Map(stringCacheArray);
  306. }
  307. }
  308. // 查找缓存
  309. private findCache(key: string): Array<VideoItem> | undefined {
  310. return this.cache.get(key);
  311. }
  312. // 查找字符串缓存
  313. private findStringCache(key: string): string | undefined {
  314. return this.stringCache.get(key);
  315. }
  316. // 添加缓存
  317. private addCache(key: string, value: Array<VideoItem>) {
  318. this.cache.set(key, value);
  319. }
  320. // 添加字符串缓存
  321. private addStringCache(key: string, value: string) {
  322. this.stringCache.set(key, value);
  323. }
  324. // 删除缓存
  325. private deleteCache(key: string) {
  326. this.cache.delete(key);
  327. this.saveCacheToStorage()
  328. }
  329. // 删除字符串缓存
  330. private deleteStringCache(key: string) {
  331. this.stringCache.delete(key);
  332. }
  333. // 多选机制
  334. @State selectedFiles: Array<VideoItem> = [];
  335. @State isMultiSelect: boolean = false;
  336. @State isAllSelected: boolean = false;
  337. @State appName: string = ''
  338. @State isHasDir: boolean = false
  339. @State packName: string = ''
  340. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  341. @State titleBarModel: TitleBar.Model = new TitleBar.Model()
  342. .setTitleTextStyle(FontStyle.Normal)
  343. .setTitleBarStyle(TitleBar.BarStyle.TRANSPARENT)
  344. .setLeftIcon($r('app.media.menu'))
  345. .setLeftIconWidth(26)
  346. .setLeftIconHeight(26)
  347. .setTitleName('首页')
  348. .setTitleFontSize(18)
  349. .setTitleFontColor(Color.White)
  350. .setTitleBarBackground(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  351. .setTitleBarBottomLineColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  352. .setLeftTitleStateNormalStyleColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  353. .setRightIcon($r('app.media.add'))
  354. .setOnRightClickListener(() => {
  355. this.showSheelDialog()
  356. })
  357. // .setOnTitleClickListener(() => {
  358. // this.showPupDialog()
  359. // })
  360. .setOnLeftClickListener(() => {
  361. this.doSwipBack()
  362. })
  363. doSwipBack() {
  364. if (this.modeType !== 0 && this.isCanBack) {
  365. this.onModeChange()
  366. this.isCanBack = false
  367. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  368. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  369. setTimeout(() => {
  370. if (this.modeType == 2) {
  371. if (this.isGridMusic) {
  372. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  373. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  374. } else {
  375. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  376. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  377. }
  378. } else if (this.modeType == 3) {
  379. if (this.isGridMusic) {
  380. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  381. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  382. } else {
  383. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  384. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  385. }
  386. }
  387. }, 200)
  388. return
  389. }
  390. if (this.isHistory || this.isFavMusic) {
  391. this.isHistory = false
  392. this.getSortedFiles(this.currentPath)
  393. return
  394. }
  395. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  396. animateTo({ duration: 555 }, () => {
  397. // 动画闭包内控制Image组件的出现和消失
  398. this.isShowDrawer = !this.isShowDrawer
  399. this.offsetX = 0
  400. })
  401. return
  402. }
  403. //返回上一级歌单的滚动位置
  404. setTimeout(() => {
  405. if (this.modeType == 0) {
  406. if (this.isGridMusic) {
  407. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  408. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  409. } else {
  410. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  411. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  412. }
  413. }
  414. }, 300)
  415. this.currentPath = Utility.getParentDirectory(this.currentPath)
  416. Logger.info('this.currentPath2 = ' + this.currentPath)
  417. this.getSortedFiles(this.currentPath)
  418. }
  419. // 组件生命周期
  420. aboutToAppear() {
  421. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  422. this.tipPopup = !this.tipPopup
  423. PreferencesUtil.putSync('isFirstTiped',false)
  424. }
  425. this.initSetting()
  426. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  427. this.topRectHeight = px2vp(AppUtil.getStatusBarHeight());
  428. Utility.getAppName(getContext(this)).then((appName: string) => {
  429. this.appName = appName
  430. })
  431. this.packName = AppUtil.getBundleName()
  432. this.loadCacheFromStorage(); // 加载缓存
  433. this.mkDownLoadDir()
  434. let eventMusic: emitter.InnerEvent = { eventId: 2 }
  435. // 监听广播事件(打开其他应用处理)
  436. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  437. this.saveVideoDatas([eventData.data?.message], true)
  438. });
  439. //侧滑广播接收时间
  440. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: 888 }
  441. // 监听广播事件(打开其他应用处理)
  442. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  443. animateTo({ duration: 555 }, () => {
  444. this.doSwipBack()
  445. })
  446. });
  447. //ScanFilePage广播接收时间
  448. let eventScanUpdate: emitter.InnerEvent = { eventId: 101 }
  449. // 监听ScanFilePage广播事件(更新数据库)
  450. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  451. this.doUpdateData()
  452. });
  453. let eventSetting: emitter.InnerEvent = { eventId: 333 }
  454. // 监听广播事件(通用设置配置更新)
  455. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  456. this.doChangeSetting()
  457. });
  458. let event: Callback<InterruptEvent> = (event) => {
  459. LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  460. this.savePlaybackPosition()
  461. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  462. this.pause();
  463. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  464. this.startPlayOrResumePlay();
  465. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  466. this.stop();
  467. }
  468. }
  469. this.mIjkMediaPlayer.on('audioInterrupt', event);
  470. // 音频设备断连回调处理
  471. // let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  472. // LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  473. // if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  474. // this.pause();
  475. // }
  476. // }
  477. // this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  478. this.makeWorker()
  479. //折叠屏的屏幕显示模式变化
  480. display.on('foldDisplayModeChange', (data) => {
  481. this.doChangeBarHeight()
  482. });
  483. display.on('foldStatusChange', (data) => {
  484. Logger.info('onecold foldStatusChange ')
  485. });
  486. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  487. // 读取 themeMode 并同步 currentColorMode
  488. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  489. this.applyThemeMode(this.themeMode)
  490. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  491. AppStorage.setOrCreate('themeColor', themeColor);
  492. this.themeColor = themeColor;
  493. this.doChangeSetting()
  494. this.windowClass.on('windowSizeChange', (size) => {
  495. LogUtil.info('onecold windowSizeChange')
  496. this.doChangeBarHeight()
  497. let viewWidth = px2vp(size.width);
  498. let viewHeight = px2vp(size.height);
  499. if(this.isPhoneLan()){
  500. this.is_auto_hide_progress = false
  501. setTimeout(() => {
  502. this.is_auto_hide_progress = true
  503. }, 6000)
  504. }else{
  505. this.startAutoHide()
  506. }
  507. });
  508. this.eventHub.on('onStateChange', (fg: boolean) => {
  509. if (fg && this.curState === 'STARTED') {
  510. this.stopPip();
  511. }
  512. });
  513. }
  514. startAutoHide() {
  515. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  516. console.info('onecold startAutoHide')
  517. this.is_auto_hide_progress = false
  518. setTimeout(() => {
  519. this.is_auto_hide_progress = true
  520. }, 6000)
  521. }
  522. }
  523. applyThemeMode(mode: number) {
  524. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  525. if (mode === 1) {
  526. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  527. } else if (mode === 2) {
  528. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  529. }
  530. AppStorage.setOrCreate('currentColorMode', colorMode)
  531. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  532. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  533. AppStorage.setOrCreate('themeMode', mode)
  534. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  535. // 只有强制浅色/深色时才主动设置
  536. const context = getContext(this) as common.UIAbilityContext
  537. context.getApplicationContext().setColorMode(colorMode)
  538. }
  539. initSetting() {
  540. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  541. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  542. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  543. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, true)
  544. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  545. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  546. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  547. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  548. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  549. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  550. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  551. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  552. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  553. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 3)
  554. this.isCoverTop = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP, false)
  555. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  556. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  557. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  558. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  559. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  560. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  561. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  562. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  563. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  564. //如果是hicar连接状态,这些都是false
  565. if(this.isHiCarStatus){
  566. this.isShowTitleBar = false//不显示导航栏
  567. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//大屏幕不可以Grid
  568. {
  569. this.isShowHeader = false//二级菜单不显示头部
  570. this.isGridMusic= false//用list不用网格
  571. this.isCoverTopBig = false
  572. }
  573. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  574. }
  575. if (this.isSavePlayMode) {
  576. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  577. }
  578. if (this.isCustomizeBg) {
  579. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  580. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  581. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  582. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  583. } else {
  584. if (!this.isDarkMode) {
  585. this.titleBarModel.setTitleBarBackground(this.themeColor)
  586. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  587. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  588. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  589. } else {
  590. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  591. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  592. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  593. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  594. }
  595. }
  596. }
  597. doChangeSetting() {
  598. this.initSetting()
  599. this.deleteCache(this.currentPath)
  600. if (this.modeType === 0) {
  601. this.getSortedFiles(this.currentPath)
  602. }
  603. }
  604. doChangeBarHeight() {
  605. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  606. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  607. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  608. this.setBarHeightNormal()
  609. }
  610. }
  611. onPageShow() {
  612. this.knockController?.immersiveListening();
  613. app.setImageCacheCount(100);
  614. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  615. app.setImageRawDataCacheSize(104857600);
  616. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  617. }
  618. //开启线程查看各个数据库
  619. makeWorker() {
  620. setTimeout(() => {
  621. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  622. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  623. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  624. // workerInstance.postMessage({
  625. // code: 1,
  626. // data1: this.context,
  627. // data2: this.rootPath,
  628. // data3: this.lockPath,
  629. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  630. // });
  631. PreferencesUtil.putSync('isFirstApp', false)
  632. } else {
  633. workerInstance.postMessage({ code: 2, data: this.context });
  634. workerInstance.postMessage({ code: 3, data: this.context });
  635. workerInstance.postMessage({ code: 4, data: this.context });
  636. this.getHistoryList(false)
  637. }
  638. }, 1000)
  639. workerInstance.onmessage = (e: MessageEvents): void => {
  640. switch (e.data.code) {
  641. case 101: //第一次扫描文件夹入库
  642. ToastUtil.showToast('刷新同步数据库成功!')
  643. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  644. this.doUpdateData()
  645. break;
  646. case 102: //查询媒体库列表
  647. this.mediaKuList = e.data.data
  648. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  649. Utility.doSortListAscending(this.mediaKuList)
  650. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  651. if (this.modeType === 1) {
  652. this.updateListData(this.mediaKuList)
  653. }
  654. break;
  655. case 103: //收到查询艺术家列表
  656. this.artistMap = e.data.data1;
  657. this.artistList = e.data.data2;
  658. break;
  659. case 104: //收到查询专辑列表
  660. this.albumMap = e.data.data1;
  661. this.albumList = e.data.data2
  662. //查询完毕在启动是否自动播放
  663. if (this.isStartAutoPlay) {
  664. this.startPlayOrResumePlay()
  665. }
  666. break;
  667. }
  668. };
  669. // 在调用terminate后,执行onexit
  670. workerInstance.onexit = (code) => {
  671. console.log("main thread terminate");
  672. }
  673. //若Worker处于已销毁或正在销毁等非运行状态时,调用其功能接口,会抛出相应的错误。
  674. // 使用Worker模块时,需要在主线程中注册onerror接口,否则当worker线程出现异常时会发生jscrash问题。
  675. workerInstance.onerror = (err: ErrorEvent) => {
  676. console.log("onerror" + err.message);
  677. }
  678. // let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
  679. //碰一碰分享的监听
  680. this.knockController = KnockController.getInstance(this.context);
  681. this.knockController?.immersiveListening();
  682. }
  683. onPageHide(): void {
  684. this.knockController?.immersiveDisableListening();
  685. }
  686. @State isFirstStartPlay: boolean = false
  687. //获取download_path
  688. async mkDownLoadDir() {
  689. const documentViewPicker = new picker.DocumentViewPicker()
  690. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  691. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  692. // this.rootPath = this.download_path
  693. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  694. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  695. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  696. Logger.info('onecold rootPath = ' + this.rootPath)
  697. Logger.info('onecold lockPath = ' + this.lockPath)
  698. if (!FileUtil.accessSync(this.lockPath)) {
  699. FileUtil.mkdirSync(this.lockPath)
  700. }
  701. if (!FileUtil.accessSync(this.favPath)) {
  702. FileUtil.mkdirSync(this.favPath)
  703. }
  704. if (!FileUtil.accessSync(this.historyPath)) {
  705. FileUtil.mkdirSync(this.historyPath)
  706. }
  707. this.getSortedFiles(this.rootPath).then(() => {
  708. this.isFavMusic = false
  709. //穿山甲
  710. // this.loadBannerAd(CSJUtil.getBannerID())
  711. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  712. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  713. if (ArrayUtil.isEmpty(this.songList)) {
  714. this.songList = this.getCurFileList()
  715. } else {
  716. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  717. }
  718. if (ArrayUtil.isNotEmpty(this.songList)) {
  719. this.isFirstStartPlay = true
  720. this.sonDataSource.pushArrayData(this.songList)
  721. if (this.currentSong === undefined) {
  722. this.isFirstStartPlay = false
  723. this.currentSong = this.songList[0]
  724. }
  725. this.videoUrl = this.currentSong.filePath
  726. this.name = this.currentSong.name
  727. this.cover = this.currentSong.pixelMapPath
  728. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  729. } else {
  730. this.name = '空空如也'
  731. }
  732. })
  733. this.getFavList(false)
  734. }
  735. getFavList(isFavRefresh: boolean) {
  736. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  737. this.favList = result
  738. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  739. this.videoLocalList = this.favList
  740. this.updateListData(this.videoLocalList)
  741. }
  742. })
  743. }
  744. getHistoryList(isRefresh: boolean) {
  745. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  746. this.historyList = result
  747. // for (let i = 0; i < this.historyList.length; i++) {
  748. //
  749. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  750. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  751. // }
  752. if (isRefresh) {
  753. this.videoLocalList = this.historyList
  754. this.updateListData(this.videoLocalList, true)
  755. }
  756. })
  757. }
  758. // 组件消失生命周期
  759. aboutToDisappear() {
  760. console.info('LifeCycleComponent aboutToDisappear');
  761. this.knockController?.immersiveDisableListening();
  762. this.curIndex = 0
  763. emitter.off(2);
  764. emitter.off(101);
  765. emitter.off(888);
  766. emitter.off(333);
  767. this.mDestroyPage = true;
  768. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  769. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  770. this.stop();
  771. }
  772. this.mIjkMediaPlayer.off('audioInterrupt');
  773. if (workerInstance) {
  774. workerInstance.terminate();
  775. }
  776. this.stopPip();
  777. this.destroyPipController()
  778. }
  779. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean) {
  780. this.isFavMusic = false
  781. if (isWorkerPost) {
  782. workerInstance.postMessage({ code: 2, data: this.context }); //刷新媒体库列表
  783. }
  784. if (this.modeType !== 0) {
  785. return
  786. }
  787. this.isCanBack = false
  788. this.currentPath = curPath
  789. this.titleBarModel.setTitleName(Utility.getFileDirName(this.currentPath, this.rootPath))
  790. if (curPath === this.rootPath) {
  791. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  792. } else {
  793. this.currentTitleName = Utility.getFileDirName(this.currentPath, this.rootPath)
  794. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  795. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  796. }
  797. }
  798. // Get the current file list and calculate its hash
  799. this.fileList = FileUtil.listFileSync(curPath);
  800. const currentHash = simpleHash(this.fileList);
  801. // Check cache
  802. const cachedValue = this.findCache(curPath);
  803. Logger.info('onecold cachedValue = ' + cachedValue)
  804. const cachedHash = this.findStringCache(curPath + '_hash');
  805. const cachedDirList = this.findCache(curPath + "_dirList");
  806. if (cachedValue !== undefined) {
  807. // this.videoLocalList = cachedValue;
  808. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  809. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  810. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  811. }
  812. this.updateListData(cachedValue)
  813. }
  814. if (cachedDirList !== undefined) {
  815. this.dirList = cachedDirList
  816. }
  817. //通过当前hash值和缓存hash判断list有没有变化
  818. if (cachedValue && cachedHash === currentHash) {
  819. return;
  820. }
  821. this.fileList = FileUtil.listFileSync(curPath)
  822. let directories: Array<VideoItem> = [];
  823. let files: Array<VideoItem> = [];
  824. for (let i = 0; i < this.fileList.length; i++) {
  825. console.info(`The name of file: ${this.fileList[i]}`);
  826. let path = curPath + '/' + this.fileList[i]
  827. if (FileUtil.isDirectory(path)) {
  828. let item: VideoItem =
  829. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  830. '')
  831. if (this.isShowDir(item.name)) {
  832. directories.push(item);
  833. }
  834. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  835. // Utility.doSortListAscending(directories)
  836. } else {
  837. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  838. let item: VideoItem =
  839. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  840. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  841. files.push(item);
  842. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  843. // this.doSortListAscending(files)
  844. }
  845. }
  846. }
  847. }
  848. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  849. if (this.currentPath !== this.lockPath) {
  850. files = result;
  851. }
  852. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  853. Utility.doSortListAscending(files)
  854. if (this.currentPath === this.rootPath) {
  855. this.dirList = directories
  856. this.addCache(curPath + "_dirList", this.dirList);
  857. }
  858. //插入广告先注释掉
  859. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  860. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  861. // directories.push(adItem)
  862. // }
  863. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  864. this.videoLocalList = directories.concat(files);
  865. this.updateListData(this.videoLocalList)
  866. if (ArrayUtil.isNotEmpty(files)) {
  867. if (this.currentPath != this.rootPath) {
  868. if (files) {
  869. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  870. }
  871. }
  872. // 缓存结果
  873. this.addCache(curPath, this.videoLocalList);
  874. await this.saveCacheToStorage(); // 保存缓存至本地存储
  875. this.addStringCache(curPath + '_hash', currentHash);
  876. }
  877. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  878. // for (let i = 0; i < this.videoLocalList.length; i++) {
  879. //
  880. // console.info(`onecold gengxin 1: ${this.videoLocalList[i].pixelMapPath}`);
  881. //
  882. // }
  883. // this.setButtonStatus()
  884. if (isOpen) {
  885. if (destPath === undefined) {
  886. // 处理 destPath 为 undefined 的情况
  887. return
  888. }
  889. if (destPath.endsWith('.lrc')) {
  890. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  891. if (StrUtil.isNotEmpty(this.videoUrl)) {
  892. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  893. this.initLyric(lyricPath);
  894. }
  895. return
  896. }
  897. let item2 = new VideoItem(Utility.getMediaNameByUri(destPath), destPath, destPath, 0, 0, '')
  898. this.doPlay(item2)
  899. this.isShowPlay = true
  900. }
  901. });
  902. }
  903. //扫描文件夹入库
  904. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  905. const files = FileUtil.listFileSync(curPath);
  906. let mediaItems: VideoItem[] = [];
  907. Logger.info('onecold scanDirectory start ')
  908. for (const file of files) {
  909. const fPath = `${curPath}/${file}`;
  910. if (fPath === this.lockPath) {
  911. Logger.info(`Skipping locked path: ${fPath}`);
  912. continue;
  913. }
  914. if (FileUtil.isDirectory(fPath)) {
  915. // Recursively scan subdirectories
  916. const subDirItems = await this.scanDirectory(fPath);
  917. mediaItems = mediaItems.concat(subDirItems);
  918. } else {
  919. Logger.info('onecold scanDirectory filePath = ' + fPath)
  920. // Process media files
  921. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  922. let mediaItem: VideoItem =
  923. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, true);
  924. mediaItems.push(mediaItem);
  925. this.table.insert(mediaItem, (id: number) => {
  926. });
  927. }
  928. }
  929. }
  930. return mediaItems;
  931. }
  932. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  933. animateTo({ duration: 888 }, () => {
  934. this.opacityItem = 0;
  935. });
  936. setTimeout(() => {
  937. this.videoLocalList = mList;
  938. if (!noSort) {
  939. if (this.modeType === 0 || this.modeType === 1) {
  940. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  941. this.doSortType(this.sortType)
  942. }
  943. }
  944. this.dataSource.pushArrayData(this.videoLocalList)
  945. animateTo({ duration: 888 }, () => {
  946. this.opacityItem = 1;
  947. });
  948. this.setButtonStatus()
  949. }, 200);
  950. }
  951. //排序模式和多选模式
  952. showPupDialog() {
  953. if (this.modeType === 2 || this.modeType === 3) {
  954. this.titleBarModel.setRightIcon(null)
  955. } else {
  956. this.titleBarModel.setRightIcon(($r('app.media.add')))
  957. }
  958. let dataBean = new BubbleBean()
  959. dataBean.data = ["首页", "媒体库", "艺术家", "专辑", "同步数据"]
  960. dataBean.color = this.themeColor
  961. dataBean.modeType = this.modeType
  962. dataBean.imageRes =
  963. [$r('app.media.home_press'), $r('app.media.kp_music'), $r('app.media.music_menu'), $r('app.media.llq'),
  964. $r('app.media.refresh')]
  965. let pup: XPopup;
  966. if (this.isDarkMode) {
  967. pup = XPopup.Builder()
  968. .setPopupPosition(PopupPosition.BOTTOM)
  969. .atView('pup_positon_music')
  970. .setBackgroundColor(Color.Black)
  971. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  972. .show()
  973. } else {
  974. pup = XPopup.Builder()
  975. .setPopupPosition(PopupPosition.BOTTOM)
  976. .atView('pup_positon_music')
  977. .setBackgroundColor(Color.White)
  978. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  979. .show()
  980. }
  981. dataBean.onItemClick = (i) => {
  982. XPopup.dismissTop()
  983. switch (i) {
  984. case 0: //首页
  985. this.modeType = 0
  986. this.getSortedFiles(this.currentPath)
  987. break
  988. case 1:
  989. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  990. this.modeType = 1
  991. this.updateListData(this.mediaKuList)
  992. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  993. break
  994. case 2:
  995. this.modeType = 2
  996. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  997. this.updateListData(this.artistList)
  998. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  999. break
  1000. case 3:
  1001. this.modeType = 3
  1002. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1003. this.updateListData(this.albumList)
  1004. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  1005. break
  1006. case 4: //同步数据
  1007. this.asyncCurrentPathData()
  1008. break
  1009. }
  1010. }
  1011. }
  1012. getCurFileList(): Array<VideoItem> {
  1013. let files: Array<VideoItem> = [];
  1014. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1015. for (let i = 0; i < this.videoLocalList.length; i++) {
  1016. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  1017. files.push(this.videoLocalList[i]);
  1018. }
  1019. }
  1020. }
  1021. return files
  1022. }
  1023. setButtonStatus() {
  1024. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1025. this.isZero = false
  1026. } else {
  1027. this.isZero = true
  1028. }
  1029. if (this.currentPath !== this.rootPath &&
  1030. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  1031. this.isHasDir = true //不为空,说明有子文件夹
  1032. } else {
  1033. this.isHasDir = false
  1034. }
  1035. }
  1036. showRankDialog() {
  1037. if (this.modeType === 2 || this.modeType === 3) {
  1038. //动作面板
  1039. DialogHelper.showBottomSheetDialog({
  1040. title: "请选择排序模式",
  1041. maskColor: Color.Transparent,
  1042. // sheets: ["按名称升序", "按名称降序"],
  1043. sheets: [
  1044. { value: '按名称升序', fontColor: $r('app.color.text_color') },
  1045. { value: '按名称降序', fontColor: $r('app.color.text_color') },
  1046. ],
  1047. backgroundColor: $r('app.color.bg_card'),
  1048. height: '30%',
  1049. transition: AnimationHelper.transitionInDown(555),
  1050. onAction: (index) => {
  1051. switch (index) {
  1052. case 0:
  1053. Utility.doSortListAscending(this.videoLocalList)
  1054. break;
  1055. case 1:
  1056. Utility.doSortListDescending(this.videoLocalList)
  1057. break;
  1058. }
  1059. this.updateListData(this.videoLocalList)
  1060. }
  1061. })
  1062. return
  1063. }
  1064. //动作面板
  1065. DialogHelper.showBottomSheetDialog({
  1066. title: "请选择排序模式",
  1067. maskColor: Color.Transparent,
  1068. height: '75%',
  1069. // sheets: ["按艺术家升序", "按艺术家降序", "按专辑升序", "按专辑降序", "按名称升序", "按名称降序", "按添加时间升序","按添加时间降序"],
  1070. sheets: [
  1071. { value: "按艺术家升序", fontColor: $r('app.color.text_color') },
  1072. { value: "按艺术家降序", fontColor: $r('app.color.text_color') },
  1073. { value: "按专辑升序", fontColor: $r('app.color.text_color') },
  1074. { value: "按专辑降序", fontColor: $r('app.color.text_color') },
  1075. { value: "按名称升序", fontColor: $r('app.color.text_color') },
  1076. { value: "按名称降序", fontColor: $r('app.color.text_color') },
  1077. { value: "按添加时间升序", fontColor: $r('app.color.text_color') },
  1078. { value: "按添加时间降序", fontColor: $r('app.color.text_color') },
  1079. ],
  1080. backgroundColor: $r('app.color.bg_card'),
  1081. transition: AnimationHelper.transitionInDown(555),
  1082. onAction: (index) => {
  1083. this.doSortType(index)
  1084. PreferencesUtil.put(SettingPage.SORT_TYPE, index)
  1085. this.updateListData(this.videoLocalList, true)
  1086. }
  1087. })
  1088. }
  1089. doSortType(index: number) {
  1090. switch (index) {
  1091. case 0:
  1092. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1093. // 类型排序优先级
  1094. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1095. if (typeOrder !== 0) {
  1096. return typeOrder;
  1097. }
  1098. // 处理艺术家可能为undefined的字符串比较
  1099. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1100. const artistB = b.artist?.trim() || '';
  1101. return artistA.localeCompare(artistB);
  1102. });
  1103. break;
  1104. case 1:
  1105. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1106. // 类型排序优先级
  1107. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1108. if (typeOrder !== 0) {
  1109. return typeOrder;
  1110. }
  1111. // 处理艺术家可能为undefined的字符串比较
  1112. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1113. const artistB = b.artist?.trim() || '';
  1114. return artistB.localeCompare(artistA);
  1115. });
  1116. break;
  1117. case 2:
  1118. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1119. // 类型排序优先级
  1120. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1121. if (typeOrder !== 0) {
  1122. return typeOrder;
  1123. }
  1124. // 处理专辑可能为undefined的字符串比较
  1125. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1126. const albumB = b.album?.trim() || '';
  1127. return albumA.localeCompare(albumB);
  1128. });
  1129. break;
  1130. case 3:
  1131. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1132. // 类型排序优先级
  1133. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1134. if (typeOrder !== 0) {
  1135. return typeOrder;
  1136. }
  1137. // 处理专辑可能为undefined的字符串比较
  1138. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1139. const albumB = b.album?.trim() || '';
  1140. return albumB.localeCompare(albumA);
  1141. });
  1142. break;
  1143. case 4:
  1144. Utility.doSortListAscending(this.videoLocalList)
  1145. break;
  1146. case 5:
  1147. Utility.doSortListDescending(this.videoLocalList)
  1148. break;
  1149. case 6:
  1150. this.videoLocalList.sort((a, b) => {
  1151. // First, sort by type
  1152. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1153. if (typeOrder !== 0) {
  1154. return typeOrder;
  1155. }
  1156. // If types are the same, sort by cTime in ascending order
  1157. return a.cTime.localeCompare(b.cTime);
  1158. });
  1159. break;
  1160. case 7:
  1161. this.videoLocalList.sort((a, b) => {
  1162. // First, sort by type
  1163. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1164. if (typeOrder !== 0) {
  1165. return typeOrder;
  1166. }
  1167. // If types are the same, sort by cTime in descending order
  1168. return b.cTime.localeCompare(a.cTime);
  1169. });
  1170. break;
  1171. }
  1172. }
  1173. showSheelDialog() {
  1174. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  1175. // this.showTips()
  1176. // return
  1177. // }
  1178. this.showAddDialog()
  1179. }
  1180. showAddDialog() {
  1181. if (this.modeType === 2 || this.modeType === 3) {
  1182. return
  1183. }
  1184. DialogHelper.showActionSheetDialog({
  1185. title: "请选择添加方式(建议歌词文件一起导入)",
  1186. // sheets: ["新建歌单", "手动导入", "自动导入"],
  1187. sheets: [
  1188. { value: "新建歌单", fontColor: $r('app.color.text_color') },
  1189. { value: "手动导入", fontColor: $r('app.color.text_color') },
  1190. { value: "自动导入", fontColor: $r('app.color.text_color') },
  1191. { value: "全选导入", fontColor: $r('app.color.text_color') },
  1192. ],
  1193. maskColor: Color.Transparent,
  1194. backgroundColor: $r('app.color.bg_card'),
  1195. transition: AnimationHelper.transitionInDown(555),
  1196. onAction: (index) => {
  1197. switch (index) {
  1198. case 0:
  1199. if (this.modeType === 0) {
  1200. this.showMkDialog()
  1201. } else {
  1202. ToastUtil.showToast('请切换到首页才能新建歌单!')
  1203. }
  1204. break;
  1205. case 1:
  1206. this.callFilePickerSelectFile()
  1207. break;
  1208. case 2:
  1209. this.showTips()
  1210. break;
  1211. case 3:
  1212. this.goSelectMusic()
  1213. break;
  1214. }
  1215. }
  1216. })
  1217. }
  1218. //拉起音频
  1219. goSelectMusic() {
  1220. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  1221. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  1222. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  1223. ) {
  1224. ToastUtil.showToast('暂时不支持该设备')
  1225. return
  1226. }
  1227. try {
  1228. let documentSelectOptions = new picker.DocumentSelectOptions();
  1229. documentSelectOptions.authMode = true
  1230. documentSelectOptions.multiAuthMode = true
  1231. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  1232. let documentPicker = new picker.DocumentViewPicker(this.context);
  1233. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  1234. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  1235. this.saveVideoDatas(documentSelectResult)
  1236. }
  1237. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  1238. JSON.stringify(documentSelectResult));
  1239. }).catch((err: BusinessError) => {
  1240. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  1241. });
  1242. } catch (error) {
  1243. let err: BusinessError = error as BusinessError;
  1244. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1245. }
  1246. }
  1247. async showTips() {
  1248. DialogHelper.showTipsDialog({
  1249. title: '使用提示:自动导入教程',
  1250. content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  1251. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  1252. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  1253. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  1254. onAction: (action) => {
  1255. if (action == DialogAction.TWO) {
  1256. PreferencesUtil.putSync('isFirstMusic', false)
  1257. router.pushUrl({
  1258. url: 'pages/ScanFilePage'
  1259. });
  1260. }
  1261. }
  1262. })
  1263. }
  1264. showMkDialog() {
  1265. DialogHelper.showTextInputDialog({
  1266. title: '新建歌单',
  1267. maskColor: Color.Transparent,
  1268. text: '',
  1269. transition: AnimationHelper.transitionInDown(666),
  1270. onChange: (text) => {
  1271. console.error("onChange: " + text);
  1272. },
  1273. onAction: (action, dialogId, content) => {
  1274. // ToastUtil.showToast('content = ' +content)
  1275. if (action == DialogAction.TWO) {
  1276. const newName = content
  1277. const newPath = this.currentPath + '/' + newName
  1278. FileUtil.mkdir(newPath, true).then(() => {
  1279. this.cache.delete(this.currentPath); // 删除目标路径缓存
  1280. this.getSortedFiles(this.currentPath)
  1281. }).catch((error: BusinessError) => {
  1282. console.error(error.message);
  1283. });
  1284. }
  1285. }
  1286. })
  1287. }
  1288. @State progress: number = 0;
  1289. async saveVideoDatas(uris: string[], isOpen?: boolean) {
  1290. if (ArrayUtil.isEmpty(uris)) {
  1291. return;
  1292. }
  1293. let newUris: string[] = [];
  1294. this.progress = 0
  1295. DialogHelper.showLoadingProgress({
  1296. progress: this.progress,
  1297. backCancel: false,
  1298. autoCancel: false,
  1299. loadColor: this.themeColor,
  1300. fontColor: this.themeColor
  1301. });
  1302. // 计算所有文件的总大小
  1303. let totalSize = 0;
  1304. for (let uri of uris) {
  1305. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  1306. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  1307. await fileIo.close(sourceFile.fd);
  1308. }
  1309. let totalRead = 0;
  1310. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  1311. Logger.info(TAG, 'destPath uri: ' + destPath);
  1312. for (let i = 0; i < uris.length; i++) {
  1313. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  1314. Logger.info(TAG, 'filePath uri: ' + filePath);
  1315. newUris.push(filePath);
  1316. try {
  1317. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  1318. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  1319. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  1320. const buffer = new ArrayBuffer(buffSize);
  1321. let len = await fileIo.read(sourceFile.fd, buffer);
  1322. while (len > 0) {
  1323. await fileIo.write(destFile.fd, buffer.slice(0, len));
  1324. totalRead += len;
  1325. // 计算总进度
  1326. this.progress = Math.floor((totalRead / totalSize) * 100);
  1327. DialogHelper.updateLoading('正在导入', this.progress);
  1328. len = await fileIo.read(sourceFile.fd, buffer);
  1329. }
  1330. await fileIo.close(sourceFile.fd);
  1331. await fileIo.close(destFile.fd);
  1332. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  1333. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  1334. let mediaItem: VideoItem =
  1335. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, true);
  1336. this.table.insert(mediaItem, (id: number) => {
  1337. // 删除目标路径缓存
  1338. this.cache.delete(this.currentPath);
  1339. this.getSortedFiles(this.currentPath, true, destPath, isOpen)
  1340. });
  1341. }
  1342. }
  1343. } catch (error) {
  1344. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  1345. }
  1346. }
  1347. DialogHelper.closeLoading()
  1348. this.isZero = false
  1349. // setTimeout(() => {
  1350. // // 删除目标路径缓存
  1351. // this.cache.delete(this.currentPath);
  1352. // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
  1353. // }, 500);
  1354. Logger.info(TAG, 'scan select video result:' + newUris)
  1355. }
  1356. //拉起音频
  1357. // goSelectMusic(){
  1358. //
  1359. // try {
  1360. // let audioSelectOptions = new picker.AudioSelectOptions();
  1361. // let audioPicker = new picker.AudioViewPicker(this.context);
  1362. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  1363. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  1364. // this.saveVideoDatas(audioSelectResult)
  1365. // }
  1366. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  1367. // }).catch((err: BusinessError) => {
  1368. //
  1369. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  1370. // });
  1371. // } catch (error) {
  1372. // let err: BusinessError = error as BusinessError;
  1373. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1374. // }
  1375. //
  1376. //
  1377. //
  1378. // }
  1379. goSelectImage(item: VideoItem) {
  1380. if (!item) {
  1381. return
  1382. }
  1383. let selectUris: Array<string> = [];
  1384. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  1385. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  1386. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; // 过滤选择媒体文件类型为IMAGE
  1387. photoSelectOptions.maxSelectNumber = 1; // 选择媒体文件的最大数目
  1388. photoPicker.select(photoSelectOptions).then(async (photoSelectResult: photoAccessHelper.PhotoSelectResult) => {
  1389. //用一个全局变量存储返回的uri
  1390. selectUris = photoSelectResult.photoUris;
  1391. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  1392. //使用fs.openSync接口,通过uri打开这个文件得到fd
  1393. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  1394. console.info('file fd: ' + file.fd);
  1395. let name = await MD5.digestSync(this.videoUrl)
  1396. let imagePath = this.context.filesDir + FileUtil.separator + name
  1397. imagePath = fileUri.getUriFromPath(imagePath)
  1398. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  1399. fileIo.copyFileSync(file.fd, file2.fd)
  1400. fileIo.closeSync(file);
  1401. fileIo.closeSync(file2);
  1402. if (item.filePath == this.currentSong?.filePath) {
  1403. this.cover = imagePath
  1404. }
  1405. if (item) {
  1406. item.pixelMapPath = imagePath
  1407. }
  1408. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  1409. if (success) {
  1410. this.doUpdateData()
  1411. console.log(" onecold 更新音乐封面成功,数据库已同步");
  1412. } else {
  1413. console.error(" onecold 更新音乐封面数据库失败原因: " + error);
  1414. }
  1415. });
  1416. LogUtil.debug("onecold this.cover =" + this.cover)
  1417. }).catch((err: BusinessError) => {
  1418. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  1419. })
  1420. }
  1421. // 拉起picker选择文件管理器
  1422. async callFilePickerSelectFile(): Promise<void> {
  1423. try {
  1424. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  1425. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  1426. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  1427. } else {
  1428. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  1429. }
  1430. let documentPicker = new picker.DocumentViewPicker();
  1431. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  1432. Logger.info(TAG,
  1433. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  1434. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  1435. this.saveVideoDatas(DocumentSelectResult)
  1436. }
  1437. }).catch((err: BusinessError) => {
  1438. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  1439. });
  1440. } catch (err) {
  1441. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  1442. }
  1443. }
  1444. showWarnIsDeleteFile(item: VideoItem, index: string, filePath: string) {
  1445. //操作确认类弹出框
  1446. DialogHelper.showAlertDialog({
  1447. maskColor: Color.Transparent,
  1448. content: "确定要删除这个文件吗?",
  1449. backgroundColor: Color.Grey,
  1450. transition: AnimationHelper.transitionInUp(555),
  1451. onAction: (action) => {
  1452. if (action == DialogAction.ONE) {
  1453. // ToastUtil.showToast(`您点击了取消按钮`);
  1454. } else if (action == DialogAction.TWO) {
  1455. // ToastUtil.showToast(`您点击了确认按钮`);
  1456. this.doDelete(item, index + '', filePath)
  1457. }
  1458. }
  1459. })
  1460. }
  1461. //删除单个索引index的视频
  1462. doDelete(item: VideoItem, index: string, filePath: string) {
  1463. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1464. Logger.info(TAG, 'delete filePath = ' + filePath);
  1465. if (item.type === CommonConstants.TYPE_IS_DIR) {
  1466. //旧文件删除
  1467. this.table.deleteDataForParentPath(item.filePath, () => {
  1468. FileUtil.rmdir(filePath).then(() => {
  1469. this.videoLocalList.splice(Number(index), 1)
  1470. this.deleteCache(this.currentPath)
  1471. this.getSortedFiles(this.currentPath, true)
  1472. }).catch((error: BusinessError) => {
  1473. console.error(error.message);
  1474. });
  1475. });
  1476. } else {
  1477. this.table.deleteData(item, () => {
  1478. FileUtil.unlink(filePath)
  1479. .catch((error: BusinessError) => {
  1480. console.error(error.message);
  1481. // 可以根据 error.code 判断是否为"文件不存在",如需特殊处理
  1482. })
  1483. .finally(() => {
  1484. this.videoLocalList.splice(Number(index), 1)
  1485. this.deleteCache(this.currentPath)
  1486. this.getSortedFiles(this.currentPath, true)
  1487. });
  1488. });
  1489. }
  1490. }
  1491. }
  1492. //重命名的对话框
  1493. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  1494. DialogHelper.showTextInputDialog({
  1495. title: '重命名',
  1496. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  1497. maskColor: Color.Transparent,
  1498. backgroundColor: Color.Grey,
  1499. transition: AnimationHelper.transitionInDown(666),
  1500. onChange: (text) => {
  1501. console.error("onChange: " + text);
  1502. },
  1503. onAction: (action, dialogId, content) => {
  1504. // ToastUtil.showToast('content = ' +content)
  1505. if (action == DialogAction.TWO) {
  1506. const newName = content
  1507. const newPath = this.currentPath + '/' + newName
  1508. console.log("onecold item = " + item.type);
  1509. this.doReName(index, newName, filePath, newPath, item)
  1510. }
  1511. }
  1512. })
  1513. }
  1514. //剪切 移动到另个文件夹的对话框
  1515. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1516. Logger.info('onecold showCutDialog')
  1517. let mList: Array<string> = []
  1518. let rPath = this.rootPath
  1519. if (isCurrent) {
  1520. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1521. rPath = this.currentPath
  1522. } else {
  1523. mList = Utility.getNameList(this.dirList);
  1524. rPath = this.rootPath
  1525. }
  1526. let dataBean = new BubbleBean()
  1527. dataBean.data = mList
  1528. dataBean.color = this.themeColor
  1529. dataBean.onItemClick = (i) => {
  1530. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1531. Logger.info('newPath = ' + newPath)
  1532. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  1533. ToastUtil.showToast('移动成功')
  1534. this.table.deleteData(item, () => {
  1535. });
  1536. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1537. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1538. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1539. CommonConstants.TYPE_LOCAL, true);
  1540. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1541. this.table.insert(newItem, (id: number) => {
  1542. //加入数据库
  1543. });
  1544. }
  1545. this.cache.delete(this.currentPath); // 删除原路径缓存
  1546. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1547. this.getSortedFiles(this.currentPath, true)
  1548. }).catch((error: BusinessError) => {
  1549. console.error(error.message);
  1550. });
  1551. XPopup.dismissTop()
  1552. }
  1553. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1554. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1555. popupPosition = PopupPosition.TOP
  1556. }
  1557. if (index <= 3) {
  1558. popupPosition = PopupPosition.BOTTOM
  1559. }
  1560. let pup: XPopup
  1561. if (this.isDarkMode) {
  1562. pup = XPopup.Builder()
  1563. .setPopupPosition(popupPosition)
  1564. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  1565. .setBackgroundColor(Color.Black)
  1566. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1567. .show()
  1568. } else {
  1569. pup = XPopup.Builder()
  1570. .setPopupPosition(popupPosition)
  1571. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  1572. .setBackgroundColor(Color.White)
  1573. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1574. .show()
  1575. }
  1576. }
  1577. //复制 到另个文件夹的对话框
  1578. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1579. Logger.info('onecoldv showCopyDialog')
  1580. let mList: Array<string> = []
  1581. let rPath = this.rootPath
  1582. if (isCurrent) {
  1583. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1584. rPath = this.currentPath
  1585. } else {
  1586. mList = Utility.getNameList(this.dirList);
  1587. rPath = this.rootPath
  1588. }
  1589. let dataBean = new BubbleBean()
  1590. dataBean.data = mList
  1591. dataBean.isCopy = true
  1592. dataBean.color = this.themeColor
  1593. dataBean.onItemClick = (i) => {
  1594. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1595. Logger.info('newPath = ' + newPath)
  1596. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  1597. ToastUtil.showToast('复制成功')
  1598. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1599. this.getSortedFiles(this.currentPath)
  1600. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1601. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1602. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1603. CommonConstants.TYPE_LOCAL, true);
  1604. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1605. this.table.insert(newItem, (id: number) => {
  1606. //加入数据库
  1607. });
  1608. }
  1609. }).catch((error: BusinessError) => {
  1610. console.error(error.message);
  1611. });
  1612. XPopup.dismissTop()
  1613. }
  1614. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1615. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1616. popupPosition = PopupPosition.TOP
  1617. }
  1618. if (index <= 3) {
  1619. popupPosition = PopupPosition.BOTTOM
  1620. }
  1621. let pup: XPopup
  1622. if (this.isDarkMode) {
  1623. pup = XPopup.Builder()
  1624. .setPopupPosition(popupPosition)
  1625. .atView(id)
  1626. .setMaxHeight('60%')
  1627. .setBackgroundColor(Color.Black)
  1628. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1629. .show();
  1630. } else {
  1631. pup = XPopup.Builder()
  1632. .setPopupPosition(popupPosition)
  1633. .atView(id)
  1634. .setMaxHeight('60%')
  1635. .setBackgroundColor(Color.White)
  1636. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1637. .show();
  1638. }
  1639. }
  1640. //重命名索引index的视频
  1641. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  1642. FileUtil.rename(oldPath, newPath).then(async () => {
  1643. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1644. if (info.type === CommonConstants.TYPE_IS_DIR) {
  1645. //如果是文件夹先删除源数据,再添加新数据
  1646. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  1647. if (success) {
  1648. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  1649. } else {
  1650. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  1651. }
  1652. });
  1653. this.scanDirectory(newPath)
  1654. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  1655. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  1656. if (success) {
  1657. console.log(" onecold 重命名成功,数据库已同步");
  1658. } else {
  1659. console.error(" onecold 重命名数据库失败原因: " + error);
  1660. }
  1661. });
  1662. }
  1663. let mediaItem: VideoItem =
  1664. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, true);
  1665. this.videoLocalList[index] = mediaItem;
  1666. }
  1667. this.cache.delete(this.currentPath)
  1668. this.getSortedFiles(this.currentPath, true)
  1669. }).catch((error: BusinessError) => {
  1670. console.error(error.message);
  1671. });
  1672. }
  1673. build() {
  1674. Scroll() {
  1675. Column() {
  1676. if (!this.isShowCoverHeader()) {
  1677. Column() {
  1678. Line().width('100%').height('100%')
  1679. }
  1680. .height(this.topRectHeight)
  1681. .backgroundColor(this.isCustomizeBg ? Color.Transparent :
  1682. (this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor))
  1683. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  1684. TitleBar({ model: $titleBarModel })
  1685. .id('pup_positon_music')
  1686. }
  1687. Stack() {
  1688. Column() {
  1689. XComponent({
  1690. id: 'xcomponentId',
  1691. type: 'surface',
  1692. libraryname: 'ijkplayer_napi',
  1693. controller: this.xcomponentController
  1694. })
  1695. .onLoad((event?: object) => {
  1696. if (!!event) {
  1697. this.initDelayPlay(event);
  1698. }
  1699. })
  1700. .onKeyEvent((event?: KeyEvent) => {
  1701. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  1702. if (!event || event.type !== KeyType.Down) {
  1703. return;
  1704. }
  1705. //空格键 Space key controls pause/play
  1706. if (event.keyCode === KeyCode.KEYCODE_SPACE) {
  1707. this.playOrPause()
  1708. }
  1709. // Right-click to fast forward
  1710. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  1711. this.sessionFastForwardCallback(15);
  1712. }
  1713. // Left-click to rewind
  1714. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  1715. this.sessionRewindCallback(15);
  1716. }
  1717. })
  1718. .onDestroy(() => {
  1719. })
  1720. .width('100%')// .width(this.videoWidth)
  1721. .aspectRatio(this.videoAspectRatio)
  1722. }
  1723. .aspectRatio(this.videoAspectRatio)
  1724. .justifyContent(FlexAlign.Center)
  1725. .backgroundColor(Color.Transparent)
  1726. .visibility(Visibility.Hidden)
  1727. .height(CommonConstants.FULL_PERCENT)
  1728. .width(CommonConstants.FULL_PERCENT)
  1729. Stack() {
  1730. Row() {
  1731. Blank()
  1732. .layoutWeight(1)
  1733. IndexerView(
  1734. {
  1735. indexArray: DEFAULT_INDEX,
  1736. selectedIndex: this.selectedIndex,
  1737. textSize: 12,
  1738. selectedColor: "#ff419ee5",
  1739. normalColor: "#ffa0a0a0",
  1740. floatSelectedTextColor: "#ffffff",
  1741. floatSelectedViewColor: "#ff419ee5",
  1742. onIndexChanged: (index) => {
  1743. this.listScroller.scrollToIndex(index)
  1744. }
  1745. })
  1746. .width(24)
  1747. .height("50%")
  1748. }.visibility(Visibility.None)
  1749. Column() {
  1750. if (!this.isShowCoverHeader()) {
  1751. this.tabTitle()
  1752. }
  1753. if (this.isGridMusic) {
  1754. this.getGridView()
  1755. } else {
  1756. this.getListView()
  1757. }
  1758. if (this.modeType == 0) {
  1759. Column() {
  1760. Button('同步数据', { type: ButtonType.Capsule, stateEffect: true })
  1761. .width(130)
  1762. .height(50)
  1763. .margin({ top: 100, bottom: 40 })
  1764. .backgroundColor(this.themeColor)
  1765. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  1766. .onClick(() => {
  1767. this.asyncCurrentPathData()
  1768. })
  1769. }
  1770. .height(100)
  1771. .position({ top: 260 })
  1772. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  1773. .animation({ duration: 500 }),
  1774. TransitionEffect.scale({ x: 0, y: 0 })))
  1775. .justifyContent(FlexAlign.Center)
  1776. .opacity(this.isZero ? 1 : 0)
  1777. .visibility(this.isZero && !this.isFavMusic && !this.isHistory
  1778. && this.modeType === 0 ? Visibility.Visible : Visibility.None)
  1779. .animation({
  1780. duration: 500,
  1781. curve: 'ease-in-out' // 可选动画曲线
  1782. })
  1783. .width('100%')
  1784. }
  1785. }
  1786. .layoutWeight(1)
  1787. .height('100%')
  1788. }
  1789. .layoutWeight(1)
  1790. .height('100%')
  1791. Row() {
  1792. Button(this.isAllSelected ? '全不选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  1793. .width('35%')
  1794. .height(60)
  1795. .margin({ top: 10, bottom: 10, right: 6 })
  1796. .backgroundColor(this.themeColor)
  1797. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1798. .onClick(() => {
  1799. if (this.isAllSelected) {
  1800. // 全不选
  1801. this.selectedFiles = [];
  1802. } else {
  1803. // 全选
  1804. this.selectedFiles = [...this.getCurFileList()];
  1805. }
  1806. this.isAllSelected = !this.isAllSelected;
  1807. })
  1808. Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  1809. .width('35%')
  1810. .height(60)
  1811. .id('music_cut')
  1812. .margin({ top: 10, bottom: 10, right: 6 })
  1813. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1814. .backgroundColor(this.themeColor)
  1815. .onClick(() => {
  1816. this.showCutDialogForMultipleFiles(false, 'music_cut')
  1817. })
  1818. Button('移动', { type: ButtonType.Circle, stateEffect: true })
  1819. .width('35%')
  1820. .height(60)
  1821. .id('music_cut_current')
  1822. .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  1823. .margin({ top: 10, bottom: 10, right: 6 })
  1824. .backgroundColor(this.themeColor)
  1825. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1826. .onClick(() => {
  1827. this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  1828. })
  1829. Button('复制', { type: ButtonType.Circle, stateEffect: true })
  1830. .width('35%')
  1831. .height(60)
  1832. .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  1833. .margin({ top: 10, bottom: 10, right: 6 })
  1834. .backgroundColor(this.themeColor)
  1835. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1836. .onClick(() => {
  1837. this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  1838. })
  1839. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  1840. .width('35%')
  1841. .height(60)
  1842. .margin({ top: 10, bottom: 10, right: 6 })
  1843. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  1844. .backgroundColor(this.themeColor)
  1845. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1846. .onClick(() => {
  1847. this.showWarnIsDelete()
  1848. })
  1849. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  1850. .width('35%')
  1851. .height(60)
  1852. .margin({ top: 10, bottom: 10, right: 6 })
  1853. .backgroundColor(this.themeColor)
  1854. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1855. .onClick(() => {
  1856. this.selectedFiles = [];
  1857. this.isAllSelected = false
  1858. this.isMultiSelect = false
  1859. })
  1860. }
  1861. .width('100%')
  1862. .justifyContent(FlexAlign.Center)
  1863. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  1864. .opacity(this.isMultiSelect ? 1 : 0)
  1865. .animation({
  1866. duration: 666,
  1867. curve: 'ease-in-out' // 可选动画曲线
  1868. })
  1869. .position(this.isShowCoverHeader() ? { bottom: 78 }
  1870. : { bottom: this.isPhoneLan() ? 130 : 168 }) // 将 Row 固定在底部
  1871. }
  1872. .width('100%')
  1873. .height('100%')
  1874. .alignContent(Alignment.Top)
  1875. Column() {
  1876. this.PlayController()
  1877. }
  1878. .hitTestBehavior(HitTestMode.Transparent)
  1879. .position({ bottom: 0 }) // 将 Row 固定在底部
  1880. .opacity(this.barBottomOpacity)
  1881. }
  1882. .width('100%')
  1883. .height('100%')
  1884. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  1885. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  1886. .backgroundImagePosition(Alignment.Center)
  1887. .backdropBlur(this.blurValue)
  1888. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  1889. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  1890. }
  1891. }
  1892. asyncCurrentPathData() {
  1893. if (this.modeType == 0) {
  1894. workerInstance.postMessage({
  1895. code: 1,
  1896. data1: this.context,
  1897. data2: this.currentPath,
  1898. data3: this.lockPath,
  1899. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1900. });
  1901. }
  1902. }
  1903. // 处理文件选择的函数
  1904. handleFileSelection(item: VideoItem, checked: boolean) {
  1905. if (checked) {
  1906. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  1907. this.selectedFiles.push(item);
  1908. }
  1909. } else {
  1910. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  1911. if (index > -1) {
  1912. this.selectedFiles.splice(index, 1);
  1913. }
  1914. }
  1915. }
  1916. showWarnIsDelete() {
  1917. //操作确认类弹出框
  1918. DialogHelper.showAlertDialog({
  1919. content: "确定要删除这些文件吗?",
  1920. transition: AnimationHelper.transitionInUp(666),
  1921. maskColor: Color.Transparent,
  1922. backgroundColor: Color.Grey,
  1923. onAction: (action) => {
  1924. if (action == DialogAction.ONE) {
  1925. // ToastUtil.showToast(`您点击了取消按钮`);
  1926. } else if (action == DialogAction.TWO) {
  1927. // ToastUtil.showToast(`您点击了确认按钮`);
  1928. this.deleteMultipleFiles()
  1929. }
  1930. }
  1931. })
  1932. }
  1933. //多选删除文件
  1934. deleteMultipleFiles() {
  1935. if (ArrayUtil.isNotEmpty(this.selectedFiles)) {
  1936. this.selectedFiles.forEach((item) => {
  1937. Logger.info(TAG, 'delete filePath = ' + item.filePath);
  1938. if (item.type === CommonConstants.TYPE_IS_DIR) {
  1939. this.table.deleteDataForParentPath(item.filePath, () => {
  1940. FileUtil.rmdir(item.filePath).then(() => {
  1941. this.videoLocalList = this.videoLocalList.filter(v => v !== item);
  1942. this.selectedFiles = [];
  1943. this.isMultiSelect = false
  1944. this.isAllSelected = false
  1945. this.cache.delete(this.currentPath);
  1946. this.getSortedFiles(this.currentPath, true);
  1947. }).catch((error: Error) => {
  1948. console.error(error.message);
  1949. });
  1950. });
  1951. } else {
  1952. this.table.deleteData(item, () => {
  1953. FileUtil.unlink(item.filePath).catch((error: Error) => {
  1954. console.error(error.message);
  1955. }).finally(() => {
  1956. this.videoLocalList = this.videoLocalList.filter(v => v !== item);
  1957. this.selectedFiles = [];
  1958. this.isMultiSelect = false
  1959. this.isAllSelected = false
  1960. this.cache.delete(this.currentPath);
  1961. this.getSortedFiles(this.currentPath, true);
  1962. });
  1963. });
  1964. }
  1965. });
  1966. }
  1967. }
  1968. //多选移动文件
  1969. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  1970. Logger.info('onecold showCutDialogForMultipleFiles')
  1971. let mList: Array<string> = []
  1972. let rPath = this.rootPath
  1973. if (isCurrent) {
  1974. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1975. rPath = this.currentPath
  1976. } else {
  1977. mList = Utility.getNameList(this.dirList);
  1978. rPath = this.rootPath
  1979. }
  1980. let dataBean = new BubbleBean();
  1981. dataBean.data = mList;
  1982. dataBean.color = this.themeColor
  1983. dataBean.onItemClick = (i) => {
  1984. const newDirPath = rPath + '/' + mList[i];
  1985. // Logger.info('newDirPath = ' + newDirPath)
  1986. this.selectedFiles.forEach((item) => {
  1987. const newPath = newDirPath + '/' + item.fileName;
  1988. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  1989. ToastUtil.showToast('移动成功');
  1990. this.table.deleteData(item, () => {
  1991. this.cache.delete(this.currentPath); // 删除原路径缓存
  1992. this.cache.delete(newDirPath); // 删除目标路径缓存
  1993. this.getSortedFiles(this.currentPath, true);
  1994. });
  1995. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1996. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1997. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1998. CommonConstants.TYPE_LOCAL, true);
  1999. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2000. this.table.insert(newItem, (id: number) => {
  2001. //加入数据库
  2002. });
  2003. }
  2004. }).catch((error: Error) => {
  2005. console.error(error.message);
  2006. });
  2007. });
  2008. this.isMultiSelect = false
  2009. this.selectedFiles = [];
  2010. this.isAllSelected = false
  2011. XPopup.dismissTop();
  2012. };
  2013. let pup: XPopup
  2014. if (this.isDarkMode) {
  2015. pup = XPopup.Builder()
  2016. .setPopupPosition(PopupPosition.TOP)
  2017. .atView(viewId)
  2018. .setBackgroundColor(Color.Black)
  2019. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2020. .show();
  2021. } else {
  2022. pup = XPopup.Builder()
  2023. .setPopupPosition(PopupPosition.TOP)
  2024. .atView(viewId)
  2025. .setBackgroundColor(Color.White)
  2026. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2027. .show();
  2028. }
  2029. }
  2030. doFav(item: VideoItem) {
  2031. LogUtil.info('onecold doFav isFav=' + item.isFav)
  2032. let isFav = 0
  2033. if (Utility.getIsFav(this.favList, item)) {
  2034. isFav = 0
  2035. } else {
  2036. isFav = 1
  2037. }
  2038. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  2039. if (result) {
  2040. if (isFav === 1) {
  2041. ToastUtil.showToast('收藏成功');
  2042. } else {
  2043. ToastUtil.showToast('取消收藏成功');
  2044. }
  2045. this.deleteCache(this.currentPath)
  2046. this.getFavList(false)
  2047. if (this.modeType === 0 && !this.isFavMusic) {
  2048. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  2049. this.getSortedFiles(this.currentPath)
  2050. }
  2051. workerInstance.postMessage({ code: 2, data: this.context });
  2052. workerInstance.postMessage({ code: 3, data: this.context });
  2053. workerInstance.postMessage({ code: 4, data: this.context });
  2054. }
  2055. })
  2056. }
  2057. //多选复制文件
  2058. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  2059. console.log('onecold showCopyDialogForMultipleFiles');
  2060. let mList: Array<string> = []
  2061. let rPath = this.rootPath
  2062. if (isCurrent) {
  2063. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2064. rPath = this.currentPath
  2065. } else {
  2066. mList = Utility.getNameList(this.dirList);
  2067. rPath = this.rootPath
  2068. }
  2069. let dataBean = new BubbleBean();
  2070. dataBean.data = mList;
  2071. dataBean.isCopy = true
  2072. dataBean.color = this.themeColor
  2073. dataBean.onItemClick = (i) => {
  2074. const newDirPath = rPath + '/' + mList[i];
  2075. // Logger.info('newDirPath = ' + newDirPath)
  2076. this.selectedFiles.forEach((item) => {
  2077. const newPath = newDirPath + '/' + item.fileName;
  2078. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2079. ToastUtil.showToast('复制成功');
  2080. this.cache.delete(newDirPath); // 删除目标路径缓存
  2081. this.getSortedFiles(this.currentPath);
  2082. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2083. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2084. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2085. CommonConstants.TYPE_LOCAL, true);
  2086. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2087. this.table.insert(newItem, (id: number) => {
  2088. //加入数据库
  2089. });
  2090. }
  2091. }).catch((error: Error) => {
  2092. console.error(error.message);
  2093. });
  2094. });
  2095. this.isMultiSelect = false
  2096. this.selectedFiles = [];
  2097. this.isAllSelected = false
  2098. XPopup.dismissTop();
  2099. };
  2100. let pup: XPopup
  2101. if (this.isDarkMode) {
  2102. pup = XPopup.Builder()
  2103. .setPopupPosition(PopupPosition.TOP)
  2104. .atView(viewId)
  2105. .setBackgroundColor(Color.Black)
  2106. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2107. .show();
  2108. } else {
  2109. pup = XPopup.Builder()
  2110. .setPopupPosition(PopupPosition.TOP)
  2111. .atView(viewId)
  2112. .setBackgroundColor(Color.White)
  2113. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2114. .show();
  2115. }
  2116. }
  2117. @Builder
  2118. private DirItem(item: VideoItem, index?: number) {
  2119. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2120. Row() {
  2121. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  2122. $r('app.media.music_group'))
  2123. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2124. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2125. .fillColor(this.themeColor)// .fontSize(33)
  2126. .alt($r('app.media.music_group'))
  2127. .borderRadius('100%')
  2128. .clip(true)
  2129. .margin({ left: 20, top: 8, bottom: 8 })
  2130. Column() {
  2131. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  2132. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2133. .maxLines(1)// .width('88%')
  2134. .animation({
  2135. duration: 555,
  2136. curve: 'ease-in-out',
  2137. })
  2138. .transition({
  2139. type: TransitionType.Insert,
  2140. opacity: 0,
  2141. translate: { x: 160 }
  2142. })
  2143. .margin({ left: 10, right: 20 })
  2144. .fontColor($r('app.color.text_color'))
  2145. Row() {
  2146. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  2147. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2148. .padding({ top: 8 })
  2149. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  2150. .fontColor($r('app.color.text_color'))
  2151. .margin({ left: 10 })
  2152. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  2153. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2154. .padding({ top: 8 })
  2155. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2156. .fontColor($r('app.color.text_color'))
  2157. .margin({ left: 10 })
  2158. Blank()
  2159. }
  2160. }
  2161. .height('100%')
  2162. .layoutWeight(1)
  2163. .justifyContent(FlexAlign.Center)
  2164. .alignItems(HorizontalAlign.Start)
  2165. Blank()
  2166. Image($r('app.media.arrow_right'))
  2167. .height(25)
  2168. .margin({ right: 10 })
  2169. .alignSelf(ItemAlign.Center)
  2170. .id(item.filePath)
  2171. }
  2172. }
  2173. .backgroundColor(Color.Transparent)
  2174. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2175. .width('100%')
  2176. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  2177. .opacity(this.opacityItem) // 绑定透明度
  2178. }
  2179. isShowDir(dirName: string) {
  2180. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  2181. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  2182. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  2183. if (dirName === undefined) {
  2184. return true
  2185. }
  2186. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  2187. return this.isShowSimi
  2188. }
  2189. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  2190. return this.isShowFAV
  2191. }
  2192. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  2193. return this.isShowHistory
  2194. }
  2195. return true
  2196. }
  2197. @State opacityItem: number = 1; // 控制透明度的状态变量
  2198. @Builder
  2199. private MusicItem(item: VideoItem, index?: number) {
  2200. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2201. Row() {
  2202. Stack() {
  2203. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  2204. .fillColor(this.themeColor)
  2205. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2206. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2207. .alt($r('app.media.music_red'))
  2208. .borderRadius('100%')
  2209. .clip(true)
  2210. .opacity(this.opacityItem)// 绑定透明度
  2211. .margin({ left: 20 })
  2212. }
  2213. Column() {
  2214. Column() {
  2215. Text(item.name)
  2216. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2217. .maxLines(1)
  2218. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  2219. .animation({
  2220. duration: 555,
  2221. curve: 'Linear',
  2222. })
  2223. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2224. $r('app.color.text_color'))
  2225. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2226. .bindPopup(this.longItemFilePath === item.filePath, {
  2227. builder: this.MenuBuilder(item,index,item.filePath),
  2228. placement: Placement.Top,
  2229. // autoCancel: true,
  2230. mask: {color:'#33000000'},
  2231. // popupColor: Color.Yellow,
  2232. enableArrow: false,//是否显示箭头
  2233. showInSubWindow: false,
  2234. onStateChange: (e) => {
  2235. if (!e.isVisible) {
  2236. this.longItemFilePath = ''
  2237. this.tempLyricContent = ''
  2238. }
  2239. }
  2240. })
  2241. .gesture(LongPressGesture()
  2242. .onAction(async () => {
  2243. //如果是专辑和艺术家的首页,不能长按
  2244. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2245. return
  2246. //如果是我的收藏 最近播放等也不能长按
  2247. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2248. item.name === LocalMusic.STR_HISTORY_MUSIC
  2249. )
  2250. return
  2251. this.longItemFilePath = item.filePath
  2252. this.tempLyricContent = await this.getLyricContent(item)
  2253. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2254. })
  2255. .onActionEnd((event: GestureEvent) => {
  2256. })
  2257. )
  2258. Row() {
  2259. Column(){
  2260. Text(item.md5Str?.includes('Lossless')?
  2261. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  2262. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  2263. .padding({ top: 3,right:6,left:6,bottom:3 })
  2264. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2265. $r('app.color.text_color'))
  2266. .fontWeight(500)
  2267. .borderRadius(12)
  2268. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2269. .backgroundColor('#FFC107')
  2270. }
  2271. .padding({ top: 8 })
  2272. Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
  2273. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2274. .padding({ top: 8 })
  2275. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2276. $r('app.color.text_color'))
  2277. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2278. Blank()
  2279. Text(item.size)
  2280. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2281. .padding({ top: 8 })
  2282. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  2283. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2284. $r('app.color.text_color'))
  2285. .margin({ left: 10 })
  2286. }
  2287. .gesture(LongPressGesture()
  2288. .onAction(async () => {
  2289. //如果是专辑和艺术家的首页,不能长按
  2290. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2291. return
  2292. //如果是我的收藏 最近播放等也不能长按
  2293. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2294. item.name === LocalMusic.STR_HISTORY_MUSIC
  2295. )
  2296. return
  2297. this.longItemFilePath = item.filePath
  2298. this.tempLyricContent = await this.getLyricContent(item)
  2299. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2300. })
  2301. .onActionEnd((event: GestureEvent) => {
  2302. })
  2303. )
  2304. }
  2305. .height('100%')
  2306. .width('100%')
  2307. .justifyContent(FlexAlign.Center)
  2308. .alignItems(HorizontalAlign.Start)
  2309. }
  2310. .height('100%')
  2311. .margin({ left: 5 })
  2312. .layoutWeight(1)
  2313. Column() {
  2314. Checkbox({ name: 'checkbox' + index })
  2315. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  2316. .selectedColor(this.themeColor)
  2317. .shape(CheckBoxShape.CIRCLE)
  2318. .opacity(this.isMultiSelect ? 1 : 0)
  2319. .animation({
  2320. duration: 666,
  2321. curve: 'Smooth' // 可选动画曲线
  2322. })
  2323. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2324. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  2325. .margin({ left: 20, top: 8, bottom: 8 })
  2326. .width(22)
  2327. .height(22)
  2328. ImageAnimator()
  2329. .images(this.imagesF)// 动画数组
  2330. .duration(1000)// 持续
  2331. .state(this.animationState)// 动画状态
  2332. .fillMode(FillMode.Forwards)
  2333. .width(18)
  2334. .margin({ right: 20, top: 8, bottom: 8 })
  2335. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  2336. Visibility.None)
  2337. .height(18)
  2338. .iterations(-1) // 播放次数
  2339. }
  2340. }
  2341. }
  2342. .backgroundColor(Color.Transparent)
  2343. .width('100%')
  2344. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2345. }
  2346. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  2347. @Builder
  2348. tabTitle() {
  2349. Column() {
  2350. // 使用 Stack 布局来实现绝对定位效果
  2351. Stack() {
  2352. // 背景动画容器
  2353. Row() {
  2354. ForEach(this.tabs, (i: string, index) => {
  2355. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2356. Flex()
  2357. .backgroundColor(this.isDarkMode ? $r('app.color.tab_item_bg') : this.themeColor)
  2358. .borderRadius(20)
  2359. .padding(10)
  2360. .margin(6)
  2361. .width('100%')
  2362. .height('100%')
  2363. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2364. .visibility(this.modeType === index ? Visibility.Visible : Visibility.None)
  2365. .opacity(this.modeType === index ? 1 : 0)
  2366. .animation({
  2367. duration: 666,
  2368. playMode: PlayMode.Normal,
  2369. curve: 'ease-in-out'
  2370. });
  2371. }
  2372. .layoutWeight(1)
  2373. .margin({
  2374. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5,
  2375. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5, bottom: 1
  2376. });
  2377. });
  2378. }
  2379. .width('100%')
  2380. .height(50);
  2381. // 导航栏容器
  2382. Row() {
  2383. ForEach(this.tabs, (item: string, index) => {
  2384. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2385. Text(item)
  2386. .fontSize(16)
  2387. .fontColor(this.modeType === index ? Color.White : $r('app.color.text_color'))
  2388. .padding(15)
  2389. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2390. .onClick(() => {
  2391. this.modeType = index;
  2392. this.onModeChange();
  2393. });
  2394. }
  2395. .layoutWeight(1)
  2396. .stateStyles({
  2397. pressed: { opacity: 0.6 } // 按压反馈
  2398. });
  2399. });
  2400. }
  2401. .width('100%')
  2402. .height(this.topBarHeight)
  2403. .opacity(this.barOpacity)
  2404. .backgroundColor(Color.Transparent);
  2405. }
  2406. .width('100%')
  2407. .height(this.topBarHeight)
  2408. .opacity(this.barOpacity)
  2409. Line()
  2410. .width('100%')
  2411. .height(1)
  2412. .backgroundColor($r('app.color.index_background'))
  2413. .opacity(this.barOpacity)
  2414. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  2415. }
  2416. .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  2417. }
  2418. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  2419. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  2420. isShowCoverHeader() {
  2421. if (!this.isShowHeader) {
  2422. return false
  2423. }
  2424. if (this.modeType == 0) {
  2425. if (this.isHistory || this.isFavMusic) {
  2426. return true
  2427. }
  2428. if (this.currentPath != this.rootPath) {
  2429. return true
  2430. }
  2431. }
  2432. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  2433. }
  2434. @Builder
  2435. coverHeader() {
  2436. if (this.isShowCoverHeader()) {
  2437. Column() {
  2438. Stack() {
  2439. // 居中标题
  2440. Text('')
  2441. .fontSize(18)
  2442. .fontColor(Color.White)
  2443. .align(Alignment.Center)
  2444. // 左右按钮
  2445. Row() {
  2446. Image($r('app.media.left_back_white'))
  2447. .width(28)
  2448. .height(28)
  2449. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2450. .margin({ left: 12, right: 8 })
  2451. .onClick(() => {
  2452. animateTo({ duration: 555 }, () => {
  2453. this.doSwipBack()
  2454. })
  2455. })
  2456. Blank().flexGrow(1)
  2457. if (this.modeType == 0 && !this.isHistory && !this.isFavMusic) {
  2458. Image($r('app.media.add'))
  2459. .width(25)
  2460. .height(25)
  2461. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2462. .margin({ left: 8, right: 15 })
  2463. .onClick(() => {
  2464. this.showAddDialog()
  2465. })
  2466. }
  2467. }
  2468. .height(48)
  2469. .width('100%')
  2470. .alignItems(VerticalAlign.Center)
  2471. }
  2472. .height(48)
  2473. .width('100%')
  2474. Row() {
  2475. Column() {
  2476. Image(this.currentTitleCover)
  2477. .height(100)
  2478. .width(100)
  2479. .alt(this.imageLabel)
  2480. .borderRadius(8)
  2481. .clickEffect({ level: ClickEffectLevel.HEAVY })
  2482. }
  2483. .alignItems(HorizontalAlign.Start)
  2484. .margin({ left: 30, top: 3, bottom: 15 })
  2485. Column() {
  2486. Column() {
  2487. Text(this.currentTitleName)
  2488. .fontSize(16)
  2489. .maxLines(1)
  2490. .fontWeight(FontWeight.Bold)
  2491. .fontColor($r('app.color.text_color'))
  2492. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2493. if (this.modeType == 3 && ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2494. Text(`艺术家:${this.videoLocalList[0].artist}`)
  2495. .fontSize(14)
  2496. .padding({ top: 8 })
  2497. .maxLines(1)
  2498. .fontWeight(FontWeight.Bold)
  2499. .fontColor($r('app.color.text_color'))
  2500. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2501. if(this.videoLocalList[0].genre){
  2502. Text(`风格:${this.videoLocalList[0].genre}`)
  2503. .fontSize(14)
  2504. .padding({ top: 8 })
  2505. .maxLines(1)
  2506. .visibility(StrUtil.isEmpty(this.videoLocalList[0].genre)||
  2507. this.videoLocalList[0].genre.includes(this.UNKONWN)
  2508. ?Visibility.None:Visibility.Visible)
  2509. .fontWeight(FontWeight.Bold)
  2510. .fontColor($r('app.color.text_color'))
  2511. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2512. }
  2513. if(this.videoLocalList[0].year){
  2514. Text(`发行时间:${this.videoLocalList[0].year}`)
  2515. .fontSize(14)
  2516. .padding({ top: 8 })
  2517. .maxLines(1)
  2518. .visibility(StrUtil.isEmpty(this.videoLocalList[0].year)||
  2519. this.videoLocalList[0].year.includes(this.UNKONWN)
  2520. ?Visibility.None:Visibility.Visible)
  2521. .fontWeight(FontWeight.Bold)
  2522. .fontColor($r('app.color.text_color'))
  2523. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2524. }
  2525. }
  2526. if(this.modeType != 3){
  2527. Row() {
  2528. Text(`共${this.videoLocalList.length}首歌`)
  2529. .fontSize(13)
  2530. .fontWeight(FontWeight.Bold)
  2531. .padding({ top: 8 })
  2532. .fontColor($r('app.color.text_color'))
  2533. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2534. Blank()
  2535. }
  2536. }
  2537. }
  2538. .height('100%')
  2539. .width('100%')
  2540. .justifyContent(FlexAlign.Center)
  2541. .alignItems(HorizontalAlign.Start)
  2542. }
  2543. .height('100%')
  2544. .layoutWeight(1)
  2545. .margin({ left: 20 })
  2546. }
  2547. this.listViewTitle()
  2548. }
  2549. .backgroundImage(this.getCoverTitleBg())
  2550. .height(250)
  2551. .width('100%')
  2552. .backgroundImageSize({ height: '100%', width: '100%' })
  2553. .backgroundBlurStyle(this.isCustomizeBg ? BlurStyle.NONE : BlurStyle.BACKGROUND_ULTRA_THICK)
  2554. .padding({ top: this.topRectHeight, bottom: this.bottomBarHeight + 48 })
  2555. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  2556. .justifyContent(FlexAlign.SpaceBetween)
  2557. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.7, y: 0.7 }).animation({ duration: 500 }),
  2558. TransitionEffect.scale({ x: 0, y: 0 })))
  2559. } else {
  2560. this.listViewTitle()
  2561. }
  2562. }
  2563. getCoverTitleBg(): ResourceStr | image.PixelMap {
  2564. if (this.isCustomizeBg) {
  2565. return ('rgba(255,255,255,0.2)')
  2566. }
  2567. if (this.isDarkMode) {
  2568. return $r('app.color.user_center_card_background')
  2569. }
  2570. return this.currentTitleCover
  2571. }
  2572. @Builder
  2573. listViewTitle() {
  2574. Column() {
  2575. Row({ space: 8 }) {
  2576. Row({ space: 8 }) {
  2577. Image($r("app.media.hm_playlist"))
  2578. .width(25)
  2579. .margin({ left: 8 })
  2580. .fillColor(this.themeColor)
  2581. Text(`共找到${this.artistList.length}位艺术家`)
  2582. .fontColor($r('app.color.text_color'))
  2583. .fontSize(14)
  2584. .opacity(this.opacityItem)
  2585. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  2586. Text(`共找到${this.albumList.length}张专辑`)
  2587. .fontColor($r('app.color.text_color'))
  2588. .opacity(this.opacityItem)
  2589. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2590. .fontSize(14)
  2591. }
  2592. .layoutWeight(1)
  2593. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  2594. Row() {
  2595. TextInput({
  2596. placeholder: this.modeType === 2 ? '输入艺术家名称...' : '输入专辑名称...',
  2597. text: this.searchText
  2598. })
  2599. .height(35)
  2600. .onChange((value: string) => {
  2601. this.onSearchInput(value);
  2602. })
  2603. .layoutWeight(1)
  2604. Text(`取消`)
  2605. .margin({ left: 10, right: 10 })
  2606. .fontColor($r('app.color.text_color'))
  2607. .fontSize(16)
  2608. .onClick(() => {
  2609. this.isSearchMode = false
  2610. this.searchText = ''
  2611. if (this.modeType === 2) {
  2612. this.updateListData(this.artistList)
  2613. } else {
  2614. this.updateListData(this.albumList)
  2615. }
  2616. })
  2617. }
  2618. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  2619. .animation({
  2620. duration: 666,
  2621. curve: 'ease-in-out' // 可选动画曲线
  2622. })
  2623. Blank()
  2624. Image($r("app.media.search"))
  2625. .width(25)
  2626. .visibility(this.modeType === 2 || this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2627. .animation({
  2628. duration: 666,
  2629. curve: 'ease-in-out' // 可选动画曲线
  2630. })// .opacity(this.opacityItem)
  2631. .fillColor(this.themeColor)
  2632. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2633. .onClick(() => {
  2634. this.isSearchMode = true
  2635. })
  2636. Image($r("app.media.top_rank"))
  2637. .width(25)// .opacity(this.opacityItem)
  2638. .fillColor(this.themeColor)
  2639. .animation({
  2640. duration: 666,
  2641. curve: 'ease-in-out' // 可选动画曲线
  2642. })
  2643. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2644. .onClick(() => {
  2645. this.showRankDialog()
  2646. })
  2647. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  2648. .width(25)
  2649. .animation({
  2650. duration: 666,
  2651. curve: 'ease-in-out' // 可选动画曲线
  2652. })
  2653. .fillColor(this.themeColor)
  2654. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2655. .onClick(() => {
  2656. this.isGridMusic = !this.isGridMusic
  2657. })
  2658. }
  2659. .visibility(((this.modeType === 2 || this.modeType === 3) && !this.isCanBack) ? Visibility.Visible :
  2660. Visibility.None)
  2661. .width('100%')
  2662. .padding(10)
  2663. .height(50)
  2664. .border({
  2665. width: { bottom: 1 },
  2666. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  2667. })
  2668. Row({ space: 8 }) {
  2669. Row({ space: 8 }) {
  2670. Image($r("app.media.hm_play"))
  2671. .width(25)
  2672. .margin({ left: 8 })
  2673. .fillColor(this.themeColor)
  2674. Text(`播放全部`)
  2675. .fontColor($r('app.color.text_color'))
  2676. .fontSize(14)
  2677. .animation({
  2678. duration: 666,
  2679. curve: 'ease-in-out' // 可选动画曲线
  2680. })
  2681. Text(`(${Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length}首)`)
  2682. .fontColor($r('app.color.text_color'))
  2683. .fontSize(14)
  2684. .opacity(this.opacityItem)
  2685. .animation({
  2686. duration: 666,
  2687. curve: 'ease-in-out' // 可选动画曲线
  2688. })
  2689. }
  2690. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2691. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  2692. .animation({
  2693. duration: 666,
  2694. curve: 'ease-in-out' // 可选动画曲线
  2695. })
  2696. // .backgroundColor(this.isClickedPLayAll ? $r('app.color.button_click') : Color.Transparent)
  2697. .onTouch((event: TouchEvent) => {
  2698. if (event.type === TouchType.Down) {
  2699. this.isClickedPLayAll = true;
  2700. } else if (event.type === TouchType.Up || event.type === TouchType.Cancel) {
  2701. this.isClickedPLayAll = false;
  2702. }
  2703. })
  2704. .onClick(() => {
  2705. // ToastUtil.showToast('当前的手机的折叠状态 ='+DisplayUtil.getFoldStatus())
  2706. if (this.modeType === 0) {
  2707. if (ArrayUtil.isNotEmpty(this.getCurFileList())) {
  2708. this.doPlay(this.getCurFileList()[0])
  2709. }
  2710. } else {
  2711. if (ArrayUtil.isNotEmpty(this.mediaKuList)) {
  2712. this.doPlay(this.mediaKuList[0])
  2713. }
  2714. }
  2715. })
  2716. Row() {
  2717. TextInput({ placeholder: '输入名称...', text: this.searchText })
  2718. .height(35)
  2719. .onChange((value: string) => {
  2720. this.onSearchInput(value);
  2721. })
  2722. .layoutWeight(1)
  2723. Text(`取消`)
  2724. .margin({ left: 10, right: 10 })
  2725. .fontColor($r('app.color.text_color'))
  2726. .fontSize(16)
  2727. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2728. .onClick(() => {
  2729. this.isSearchMode = false
  2730. this.searchText = ''
  2731. this.updateListData(this.mediaKuList)
  2732. })
  2733. }
  2734. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  2735. .animation({
  2736. duration: 666,
  2737. curve: 'ease-in-out' // 可选动画曲线
  2738. })
  2739. Blank()
  2740. Image($r("app.media.search"))
  2741. .width(25)// .visibility(this.modeType===1?Visibility.Visible:Visibility.None)
  2742. .animation({
  2743. duration: 666,
  2744. curve: 'ease-in-out' // 可选动画曲线
  2745. })// .opacity(this.opacityItem)
  2746. .fillColor(this.themeColor)
  2747. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2748. .onClick(() => {
  2749. this.isSearchMode = true
  2750. })
  2751. Image($r("app.media.refresh"))
  2752. .fillColor(this.themeColor)
  2753. .width(25)
  2754. .visibility(this.isHistory || this.isCanBack || this.isSearchMode ? Visibility.None : Visibility.Visible)
  2755. .animation({
  2756. duration: 666,
  2757. curve: 'ease-in-out' // 可选动画曲线
  2758. })
  2759. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2760. .onClick(() => {
  2761. if (this.isFavMusic) {
  2762. this.getFavList(true)
  2763. } else {
  2764. if(this.modeType == 0){
  2765. this.asyncCurrentPathData()
  2766. }else if(this.modeType ==1){
  2767. workerInstance.postMessage({ code: 2, data: this.context });
  2768. }
  2769. }
  2770. })
  2771. Image($r("app.media.top_rank"))
  2772. .width(25)
  2773. .visibility(this.isHistory || this.isSearchMode ? Visibility.None :
  2774. Visibility.Visible)// .opacity(this.opacityItem)
  2775. .animation({
  2776. duration: 666,
  2777. curve: 'ease-in-out' // 可选动画曲线
  2778. })
  2779. .fillColor(this.themeColor)
  2780. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2781. .onClick(() => {
  2782. this.showRankDialog()
  2783. })
  2784. Image(this.isMultiSelect ? $r("app.media.cancel_multi") : $r("app.media.top_flower"))
  2785. .width(24)
  2786. .visibility(this.isHistory || this.isSearchMode ? Visibility.None : Visibility.Visible)
  2787. .animation({
  2788. duration: 666,
  2789. curve: 'ease-in-out' // 可选动画曲线
  2790. })
  2791. .fillColor(this.themeColor)
  2792. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2793. .onClick(() => {
  2794. this.isMultiSelect = !this.isMultiSelect
  2795. })
  2796. SymbolGlyph($r('sys.symbol.trash'))
  2797. .fontColor([this.themeColor])
  2798. .fontSize(25)
  2799. .effectStrategy(1)
  2800. .visibility(this.isHistory ? Visibility.Visible : Visibility.None)
  2801. .animation({
  2802. duration: 666,
  2803. curve: 'ease-in-out' // 可选动画曲线
  2804. })
  2805. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2806. .onClick(() => {
  2807. this.clearVideoHistory() //清空播放记录
  2808. })
  2809. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  2810. .width(24)
  2811. .animation({
  2812. duration: 666,
  2813. curve: 'ease-in-out' // 可选动画曲线
  2814. })
  2815. .fillColor(this.themeColor)
  2816. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2817. .bindPopup($$this.tipPopup, {
  2818. builder: this.popupBuilder,
  2819. placement: Placement.Bottom,
  2820. maskColor: 0x33000000,
  2821. enableArrow: true,
  2822. onStateChange: (e) => {
  2823. if (!e.isVisible) {
  2824. this.tipPopup = false;
  2825. }
  2826. }
  2827. })
  2828. .onClick(() => {
  2829. this.isGridMusic = !this.isGridMusic
  2830. })
  2831. }
  2832. .width('100%')
  2833. .padding(10)
  2834. .height(50)
  2835. .visibility(this.modeType === 0 || this.modeType === 1 || this.isCanBack ? Visibility.Visible : Visibility.None)
  2836. .border({
  2837. width: { bottom: 1 },
  2838. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  2839. })
  2840. }
  2841. .visibility(this.isShowAllBar ? Visibility.Visible : Visibility.None)
  2842. }
  2843. // 第二步:popup构造器定义弹框内容
  2844. @Builder popupBuilder() {
  2845. Column({ space: 2 }) {
  2846. Text('友情提示:双指缩放可以放大缩小列表')
  2847. .fontSize(12)
  2848. .fontWeight(FontWeight.Regular)
  2849. .fontColor($r('app.color.text_color'))
  2850. }
  2851. .justifyContent(FlexAlign.SpaceAround)
  2852. .width(220)
  2853. .height(55)
  2854. .padding(15)
  2855. }
  2856. //搜索功能的实现
  2857. @State searchText: string = ''; // 用户输入内容
  2858. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  2859. @State isSearchMode: boolean = false
  2860. // 实时搜索逻辑(带防抖)
  2861. private onSearchInput(value: string) {
  2862. this.searchText = value.trim();
  2863. let mSearchList: Array<VideoItem> = []
  2864. switch (this.modeType) {
  2865. case 0:
  2866. mSearchList = this.videoLocalList
  2867. break;
  2868. case 1:
  2869. mSearchList = this.mediaKuList
  2870. break;
  2871. case 2:
  2872. mSearchList = this.artistList
  2873. break;
  2874. case 3:
  2875. mSearchList = this.albumList
  2876. break;
  2877. }
  2878. // 新增条件判断:空输入时显示所有数据
  2879. if (this.searchText === '') {
  2880. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  2881. } else {
  2882. this.filteredList = mSearchList.filter((item: VideoItem) => {
  2883. return item.name.toLowerCase().includes(this.searchText.toLowerCase());
  2884. });
  2885. }
  2886. this.updateListData(this.filteredList);
  2887. // this.isSearchMode = false; // 根据业务需求决定是否启用
  2888. }
  2889. @State dragItem: number = -1
  2890. @State scaleItem: number = -1
  2891. @State neighborItem: number = -1
  2892. @State neighborScale: number = -1
  2893. @State offsetY: number = 0
  2894. private dragRefOffset: number = 0
  2895. private ITEM_INTV: number = 78
  2896. scaleSelect(item: number): number {
  2897. if (this.scaleItem === item) {
  2898. return 1.05
  2899. } else if (this.neighborItem === item) {
  2900. return this.neighborScale
  2901. } else {
  2902. return 1
  2903. }
  2904. }
  2905. itemMove(index: number, newIndex: number): void {
  2906. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  2907. return;
  2908. }
  2909. let tmp = this.videoLocalList.splice(index, 1);
  2910. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  2911. this.dataSource.pushArrayData(this.videoLocalList)
  2912. }
  2913. // Grid布局的开始
  2914. private dragRefOffSetX: number = 0;
  2915. private dragRefOffSetY: number = 0;
  2916. private FIX_VP_X: number = 180;
  2917. private FIX_VP_Y: number = 84;
  2918. isDraggable(index: number): boolean {
  2919. return index >= 0;
  2920. }
  2921. getRowEnd(item: number) {
  2922. if (item.toString() === '0') {
  2923. return 1;
  2924. } else {
  2925. return 0;
  2926. }
  2927. }
  2928. // [Start itemMove_start]
  2929. // itemMoveGrid(index: number, newIndex: number): void {
  2930. // if (!this.isDraggable(newIndex)) {
  2931. // return;
  2932. // }
  2933. // let tmp = this.videoLocalList.splice(index, 1);
  2934. // this.videoLocalList.splice(newIndex, 0, tmp[0]);
  2935. // // this.bigItemIndex = this.videoLocalList.findIndex((item) => item === 0);
  2936. // }
  2937. isInLeft(index: number) {
  2938. return index % 2 == 0;
  2939. }
  2940. down(index: number): void {
  2941. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  2942. return;
  2943. }
  2944. this.offsetY -= this.FIX_VP_Y;
  2945. this.dragRefOffSetY += this.FIX_VP_Y;
  2946. this.itemMove(index, index + 1);
  2947. }
  2948. up(index: number): void {
  2949. if (!this.isDraggable(index - 2)) {
  2950. return;
  2951. }
  2952. this.offsetY += this.FIX_VP_Y;
  2953. this.dragRefOffSetY -= this.FIX_VP_Y;
  2954. this.itemMove(index, index - 1);
  2955. }
  2956. left(index: number): void {
  2957. if (this.isInLeft(index)) {
  2958. return;
  2959. }
  2960. if (!this.isDraggable(index - 1)) {
  2961. return;
  2962. }
  2963. this.offsetX += this.FIX_VP_X;
  2964. this.dragRefOffSetX -= this.FIX_VP_X;
  2965. this.itemMove(index, index - 1)
  2966. }
  2967. right(index: number): void {
  2968. if (!this.isInLeft(index)) {
  2969. return;
  2970. }
  2971. if (!this.isDraggable(index + 1)) {
  2972. return;
  2973. }
  2974. this.offsetX -= this.FIX_VP_X;
  2975. this.dragRefOffSetX += this.FIX_VP_X;
  2976. this.itemMove(index, index + 1)
  2977. }
  2978. private scroller: Scroller = new Scroller();
  2979. @State startIndex: number = 0
  2980. @State endIndex: number = 0
  2981. @State scaleValue: number = 1
  2982. @State pinchValue: number = 1
  2983. layoutOptionsForHeader: GridLayoutOptions = {
  2984. regularSize: [1, 1], // 只支持[1, 1]
  2985. irregularIndexes: [0], // 索引为0的GridItem占用一行
  2986. };
  2987. @Builder
  2988. getGridView() {
  2989. Grid(this.scroller, this.layoutOptionsForHeader) {
  2990. GridItem() {
  2991. if (this.isShowCoverHeader()) {
  2992. this.coverHeader()
  2993. } else {
  2994. this.listViewTitle()
  2995. }
  2996. }
  2997. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  2998. GridItem() {
  2999. Stack({ alignContent: Alignment.Center }) {
  3000. this.MusicItemGrid(item, index)
  3001. }
  3002. }
  3003. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  3004. TransitionEffect.scale({ x: 0, y: 0 })))
  3005. .clickEffect({ level: ClickEffectLevel.LIGHT })
  3006. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  3007. .zIndex(this.dragItem === index ? 1 : 0)
  3008. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  3009. .hitTestBehavior(this.isDraggable(this.videoLocalList.indexOf(item)) ? HitTestMode.Default : HitTestMode.None)
  3010. //长按拖动代码
  3011. .gesture(
  3012. GestureGroup(GestureMode.Sequence,
  3013. LongPressGesture({ repeat: true })
  3014. .onAction(() => {
  3015. this.getUIContext().animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3016. this.scaleItem = index;
  3017. })
  3018. })
  3019. .onActionEnd(() => {
  3020. this.getUIContext().animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3021. this.scaleItem = -1;
  3022. })
  3023. }),
  3024. PanGesture({ fingers: 1, direction: null, distance: 0 })
  3025. .onActionStart(() => {
  3026. this.dragItem = index;
  3027. this.dragRefOffSetX = 0;
  3028. this.dragRefOffSetY = 0;
  3029. })
  3030. .onActionUpdate((event: GestureEvent) => {
  3031. this.offsetX = event.offsetX - this.dragRefOffSetX;
  3032. this.offsetY = event.offsetY - this.dragRefOffSetY;
  3033. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3034. let index = this.videoLocalList.indexOf(item);
  3035. if (this.offsetY >= this.FIX_VP_Y / 2 && (this.offsetX <= 44 && this.offsetX >= -44)) {
  3036. this.down(index);
  3037. } else if (this.offsetY <= -this.FIX_VP_Y / 2 && (this.offsetX <= 44 && this.offsetX >= -44)) {
  3038. this.up(index);
  3039. } else if (this.offsetX >= this.FIX_VP_X / 2 && (this.offsetY <= 50 && this.offsetY >= -50)) {
  3040. this.right(index);
  3041. } else if (this.offsetX <= -this.FIX_VP_Y / 2 && (this.offsetY <= 50 && this.offsetY >= -50)) {
  3042. this.left(index);
  3043. }
  3044. })
  3045. // if (this.offsetY > this.FIX_VP_Y * 0.7) {
  3046. // this.scroller.scrollToIndex(index + 10, true,ScrollAlign.CENTER);
  3047. // }
  3048. })
  3049. .onActionEnd(() => {
  3050. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3051. this.dragItem = -1;
  3052. })
  3053. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150 }, () => {
  3054. this.scaleItem = -1;
  3055. })
  3056. })
  3057. )
  3058. .onCancel(() => {
  3059. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3060. this.dragItem = -1;
  3061. })
  3062. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150 }, () => {
  3063. this.scaleItem = -1;
  3064. })
  3065. })
  3066. )
  3067. // [End gesture_start]
  3068. // [EndExclude GridItem_start]
  3069. }, (item: VideoItem) => item.filePath)
  3070. }
  3071. .width(this.isShowHeader ? '100%' : '94%')
  3072. .height('100%')
  3073. .editMode(true)
  3074. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3075. .animation({ duration: 500, curve: Curve.Ease }))
  3076. // .margin({ bottom: this.isCoverOpacity() ? 80 : 175 })
  3077. .margin({
  3078. bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? this.topBarHeight+30 : this.topBarHeight+90)
  3079. : (this.isShowCoverHeader() ? this.topBarHeight+45 : this.topBarHeight+128)
  3080. })
  3081. .layoutWeight(1)
  3082. .scrollBar(BarState.Off)
  3083. .supportAnimation(true)
  3084. .cachedCount(3)
  3085. // .columnsTemplate('1fr '.repeat(this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM ? 2 : 5))
  3086. .columnsTemplate(
  3087. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  3088. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  3089. )
  3090. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  3091. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  3092. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  3093. .gesture(PinchGesture({ fingers: 2 })
  3094. .onActionEnd((event: GestureEvent) => {
  3095. this.setGridTwoFingers()
  3096. })
  3097. .onActionUpdate(e => {
  3098. this.scaleValue = this.pinchValue * e.scale
  3099. })
  3100. .onActionStart(e => {
  3101. }))
  3102. .enableScrollInteraction(true)
  3103. // 滚轴滑动,记录下滑动时的起始位置和终点位置
  3104. .onScrollIndex((start: number, end: number) => {
  3105. this.startIndex = start
  3106. this.endIndex = end
  3107. })
  3108. .onScrollFrameBegin((offset: number) => {
  3109. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  3110. // if (this.isPhoneLan()) {
  3111. // this.setBarHeightHide(offset)
  3112. // } else
  3113. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  3114. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  3115. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  3116. if (this.isScrollHide) {
  3117. this.setBarHeightHide2(offset)
  3118. } else {
  3119. this.setBarHeightNormal()
  3120. }
  3121. } else {
  3122. this.setBarHeightHide(offset)
  3123. }
  3124. return { offsetRemain: offset };
  3125. })
  3126. //允许拖拽音乐和视频到List或Grid上自动导入视频
  3127. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3128. .onDrop((event?: DragEvent) => {
  3129. try {
  3130. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3131. if (dragData !== undefined) {
  3132. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3133. if (records.length > 0) {
  3134. for (let i = 0; i < records.length; i++) {
  3135. let types = records[i].getTypes();
  3136. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3137. const fileUriUds =
  3138. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3139. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3140. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3141. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3142. this.targetFile = fileUriUds.oriUri;
  3143. this.saveVideoDatas([this.targetFile])
  3144. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3145. }
  3146. }
  3147. }
  3148. } else {
  3149. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3150. }
  3151. } else {
  3152. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3153. }
  3154. } catch (error) {
  3155. const err = error as BusinessError;
  3156. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3157. }
  3158. })
  3159. }
  3160. @State targetFile: string = '';
  3161. setGridTwoFingers() {
  3162. this.pinchValue = this.scaleValue;
  3163. Logger.info('this.pinchValue = ' + this.pinchValue);
  3164. if (this.pinchValue >= 1) {
  3165. this.twoFingerType++
  3166. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  3167. if (this.twoFingerType > 3) {
  3168. this.twoFingerType = 3
  3169. }
  3170. } else {
  3171. this.twoFingerType--
  3172. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  3173. if (this.twoFingerType < 1) {
  3174. this.twoFingerType = 3
  3175. this.isGridMusic = false
  3176. }
  3177. }
  3178. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  3179. this.pinchValue = 1;
  3180. this.scaleValue = 1;
  3181. }
  3182. @State longItemFilePath: string = ''
  3183. @State tempLyricContent: string = ''
  3184. @Builder
  3185. private MusicItemGrid(item: VideoItem, index: number) {
  3186. Button({ type: ButtonType.Normal, stateEffect: false }) {
  3187. Stack() {
  3188. Column() {
  3189. Image(StrUtil.isEmpty(item.pixelMapPath) ? Utility.getMusisBg2(index) : item.pixelMapPath)
  3190. .height(this.getGridHeight())
  3191. .width(this.getGridWight())
  3192. .alt($r('app.media.ic_avatar6'))
  3193. .clip(true)
  3194. .borderRadius({
  3195. topLeft: 12,
  3196. topRight: 12,
  3197. bottomLeft: 0,
  3198. bottomRight: 0
  3199. })
  3200. .draggable(false)
  3201. .opacity(this.opacityItem)// 绑定透明度
  3202. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3203. // .animation({ duration: 500, curve: Curve.Ease }))
  3204. .animation({
  3205. duration: 666,
  3206. curve: 'ease-in-out' // 可选动画曲线
  3207. })
  3208. .margin({
  3209. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3210. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3211. })
  3212. Column() {
  3213. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  3214. .fontSize(this.twoFingerType == 1 ? 14 : this.twoFingerType == 2 ? 16 : 18)
  3215. .maxLines(1)
  3216. .fontWeight(FontWeight.Bold)
  3217. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3218. .animation({
  3219. duration: 555,
  3220. curve: 'Linear',
  3221. })
  3222. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3223. $r('app.color.text_color'))
  3224. Column() {
  3225. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  3226. .fontSize(11)
  3227. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  3228. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3229. .fontColor($r('app.color.text_color'))
  3230. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  3231. .fontSize(11)
  3232. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  3233. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3234. .fontColor($r('app.color.text_color'))
  3235. Row(){
  3236. Column(){
  3237. Text(item.md5Str?.includes('Lossless')?
  3238. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  3239. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  3240. .padding({ top: 3,right:6,left:6,bottom:3 })
  3241. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3242. $r('app.color.text_color'))
  3243. .fontWeight(500)
  3244. .borderRadius(12)
  3245. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  3246. .backgroundColor('#FFC107')
  3247. }
  3248. .margin({ top: 2 ,right:6})
  3249. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  3250. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  3251. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  3252. .fontSize(11)
  3253. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  3254. .maxLines(1)
  3255. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3256. .margin({ top: 2 ,right:18})
  3257. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  3258. || item.type == CommonConstants.TYPE_IS_ALBUM
  3259. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3260. .fontWeight(FontWeight.Medium)
  3261. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3262. $r('app.color.text_color'))
  3263. }
  3264. }
  3265. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  3266. }
  3267. .bindPopup(this.longItemFilePath === item.filePath, {
  3268. builder: this.MenuBuilder(item, index, item.filePath),
  3269. placement: Placement.Top,
  3270. // autoCancel: true,
  3271. mask: { color: '#33000000' },
  3272. // popupColor: Color.Yellow,
  3273. enableArrow: false, //是否显示箭头
  3274. showInSubWindow: false,
  3275. onStateChange: (e) => {
  3276. if (!e.isVisible) {
  3277. this.longItemFilePath = ''
  3278. this.tempLyricContent = ''
  3279. }
  3280. }
  3281. })
  3282. .gesture(LongPressGesture()
  3283. .onAction(async () => {
  3284. //如果是专辑和艺术家的首页,不能长按
  3285. if ((this.modeType === 2 || this.modeType == 3) && !this.isCanBack) {
  3286. return
  3287. }
  3288. //如果是我的收藏 最近播放等也不能长按
  3289. if (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3290. item.name === LocalMusic.STR_HISTORY_MUSIC
  3291. ) {
  3292. return
  3293. }
  3294. this.longItemFilePath = item.filePath
  3295. this.tempLyricContent = await this.getLyricContent(item)
  3296. LogUtil.info('长按this.tempLyricContent = ' + this.tempLyricContent)
  3297. })
  3298. .onActionEnd((event: GestureEvent) => {
  3299. })
  3300. )
  3301. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 55 : 42)
  3302. .width(this.getGridWight())
  3303. .justifyContent(FlexAlign.Center)
  3304. .margin({
  3305. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3306. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3307. })
  3308. }
  3309. .width(this.getGridWight())
  3310. .borderRadius(12)
  3311. .backgroundImage(item.pixelMapPath)
  3312. .backgroundImageSize({ height: '100%', width: '100%' })
  3313. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  3314. .animation({ curve: Curve.Sharp, duration: 300 })
  3315. Checkbox({ name: 'checkbox' + index })
  3316. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  3317. .selectedColor(this.themeColor)
  3318. .shape(CheckBoxShape.CIRCLE)
  3319. .opacity(this.isMultiSelect ? 1 : 0)
  3320. .animation({
  3321. duration: 666,
  3322. curve: 'Smooth' // 可选动画曲线
  3323. })
  3324. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  3325. Visibility.None)
  3326. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  3327. .margin({ left: 20, top: 8, bottom: 8 })
  3328. .width(38)
  3329. .height(38)
  3330. }
  3331. }
  3332. .backgroundColor(Color.Transparent)
  3333. .width('100%')
  3334. .padding({ top: 15 })
  3335. .height(this.getGridAllHeight())
  3336. .onClick(() => {
  3337. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  3338. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3339. this.handleFileSelection(item, !isChecked);
  3340. } else {
  3341. this.doPlay(item, index)
  3342. }
  3343. })
  3344. }
  3345. getGridAllHeight() {
  3346. let heightG = 222
  3347. switch (this.twoFingerType) {
  3348. case 1:
  3349. heightG = 118
  3350. break;
  3351. case 2:
  3352. heightG = 168
  3353. break;
  3354. case 3:
  3355. heightG = 222
  3356. break;
  3357. }
  3358. return heightG
  3359. }
  3360. getGridHeight() {
  3361. let heightG = 150
  3362. switch (this.twoFingerType) {
  3363. case 1:
  3364. heightG = 55
  3365. break;
  3366. case 2:
  3367. heightG = 100
  3368. break;
  3369. case 3:
  3370. heightG = 150
  3371. break;
  3372. }
  3373. return heightG
  3374. }
  3375. getGridWight() {
  3376. let wightG = 158
  3377. switch (this.twoFingerType) {
  3378. case 1:
  3379. wightG = 80
  3380. break;
  3381. case 2:
  3382. wightG = 110
  3383. break;
  3384. case 3:
  3385. wightG = 158
  3386. break;
  3387. }
  3388. return wightG
  3389. }
  3390. @State isShowDetail:boolean = false
  3391. @Builder
  3392. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  3393. Scroll() {
  3394. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  3395. Menu() {
  3396. MenuItem({
  3397. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  3398. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  3399. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  3400. })
  3401. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3402. .onClick(() => {
  3403. if (item) {
  3404. this.doFav(item)
  3405. }
  3406. this.longItemFilePath = ''
  3407. })
  3408. MenuItem({
  3409. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  3410. content: '下一首播放'
  3411. })
  3412. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3413. .onClick(() => {
  3414. this.addToNextPlay(item);
  3415. this.longItemFilePath = ''
  3416. })
  3417. MenuItem({
  3418. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  3419. content: '编辑信息'
  3420. })
  3421. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  3422. height: this.isCoverOpacity() ? '95%' : '88%',
  3423. dragBar: true,
  3424. showClose: true,
  3425. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3426. title: { title: '编辑信息' }
  3427. })
  3428. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3429. .onClick(() => {
  3430. this.isShowEdit = !this.isShowEdit;
  3431. })
  3432. MenuItem({
  3433. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  3434. content: $r('app.string.rename')
  3435. })
  3436. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  3437. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3438. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  3439. .onClick(() => {
  3440. this.showReNameDialog(item, index + '', filePath)
  3441. this.longItemFilePath = ''
  3442. })
  3443. MenuItem({
  3444. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  3445. content: $r('app.string.delete')
  3446. })
  3447. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  3448. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3449. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  3450. .onClick(() => {
  3451. this.showWarnIsDeleteFile(item, index + '', filePath)
  3452. this.longItemFilePath = ''
  3453. })
  3454. MenuItem({
  3455. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  3456. content: $r('app.string.detail')
  3457. })
  3458. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  3459. height:this.isCoverOpacity()?'95%': '95%',
  3460. dragBar: true,
  3461. showClose: true,
  3462. blurStyle:BlurStyle.Thin,
  3463. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3464. backgroundColor:Color.Transparent,
  3465. title: { title: '详情信息' }
  3466. })
  3467. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3468. .onClick(() => {
  3469. this.isShowDetail = !this.isShowDetail
  3470. })
  3471. MenuItem({
  3472. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  3473. content: $r('app.string.share')
  3474. })
  3475. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3476. .onClick(() => {
  3477. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  3478. this.longItemFilePath = ''
  3479. })
  3480. }
  3481. .font({ size: 15, weight: FontWeight.Normal })
  3482. }
  3483. .width(180)
  3484. }
  3485. .height(item.type === CommonConstants.TYPE_IS_DIR ? 150 : 400)
  3486. }
  3487. private listMaxScrollOffsetY: number = 0
  3488. @State selectedIndex: number = -1
  3489. setlistTwoFingers() {
  3490. this.pinchValue = this.scaleValue;
  3491. Logger.info('this.pinchValue = ' + this.pinchValue);
  3492. if (this.pinchValue >= 1) {
  3493. this.twoFingerType++
  3494. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  3495. if (this.twoFingerType > 3) {
  3496. this.twoFingerType = 1
  3497. this.isGridMusic = true
  3498. }
  3499. } else {
  3500. this.twoFingerType--
  3501. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  3502. if (this.twoFingerType < 1) {
  3503. this.twoFingerType = 1
  3504. }
  3505. }
  3506. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  3507. this.pinchValue = 1;
  3508. this.scaleValue = 1;
  3509. }
  3510. @Builder
  3511. getListView() {
  3512. List({ scroller: this.listScroller }) {
  3513. ListItemGroup({ header: this.coverHeader() }) {
  3514. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3515. ListItem() {
  3516. Column() {
  3517. if (item.type === CommonConstants.TYPE_IS_DIR
  3518. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  3519. this.DirItem(item, index)
  3520. } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
  3521. } else {
  3522. this.MusicItem(item, index)
  3523. }
  3524. }
  3525. .shadow(this.scaleItem === index ? {
  3526. radius: 70,
  3527. color: '#15000000',
  3528. offsetX: 0,
  3529. offsetY: 0
  3530. } :
  3531. {
  3532. radius: 0,
  3533. color: '#15000000',
  3534. offsetX: 0,
  3535. offsetY: 0
  3536. })
  3537. .animation({ curve: Curve.Sharp, duration: 300 })
  3538. }
  3539. // .transition(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }))
  3540. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  3541. .animation({ duration: 500 }),
  3542. TransitionEffect.scale({ x: 0, y: 0 })))
  3543. .clickEffect({ level: ClickEffectLevel.LIGHT })
  3544. .swipeAction((
  3545. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  3546. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  3547. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath) } : {}) //左滑
  3548. .onClick(() => {
  3549. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  3550. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3551. this.handleFileSelection(item, !isChecked);
  3552. } else {
  3553. this.doPlay(item, index)
  3554. }
  3555. })
  3556. //拖动List关键代码开始
  3557. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  3558. .zIndex(this.dragItem === index ? 1 : 0)
  3559. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  3560. .gesture(
  3561. GestureGroup(GestureMode.Sequence,
  3562. LongPressGesture({ repeat: true })
  3563. .onAction((event?: GestureEvent) => {
  3564. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3565. this.scaleItem = index
  3566. })
  3567. })
  3568. .onActionEnd(() => {
  3569. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3570. this.scaleItem = -1
  3571. })
  3572. }),
  3573. PanGesture({ fingers: 1, direction: null, distance: 0 })
  3574. .onActionStart(() => {
  3575. this.dragItem = index // 记录当前拖动项索引
  3576. this.dragRefOffset = 0 // 重置偏移基准
  3577. })
  3578. .onActionUpdate((event: GestureEvent) => {
  3579. this.offsetY = event.offsetY - this.dragRefOffset;
  3580. this.neighborItem = -1;
  3581. let indexA = this.videoLocalList.indexOf(item);
  3582. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  3583. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  3584. let value: number = 0;
  3585. if (this.offsetY < 0) {
  3586. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  3587. this.neighborItem = indexA - 1;
  3588. this.neighborScale = 1 - value / 20;
  3589. } else if (this.offsetY > 0) {
  3590. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  3591. this.neighborItem = indexA + 1;
  3592. this.neighborScale = 1 - value / 20;
  3593. }
  3594. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  3595. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3596. this.offsetY -= this.ITEM_INTV;
  3597. this.dragRefOffset += this.ITEM_INTV;
  3598. this.itemMove(indexA, indexA + 1);
  3599. });
  3600. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  3601. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3602. this.offsetY += this.ITEM_INTV;
  3603. this.dragRefOffset -= this.ITEM_INTV;
  3604. this.itemMove(indexA, indexA - 1);
  3605. });
  3606. }
  3607. let curListOffset = this.listScroller.currentOffset()
  3608. // 获取手指信息
  3609. let fingerInfo = event.fingerList[0]
  3610. let clickPercentY =
  3611. (fingerInfo.globalY - Number(this.listArea.globalPosition.y)) / Number(this.listArea.height)
  3612. if (clickPercentY > 0.8 && !this.listScroller.isAtEnd()) {
  3613. let scrollVelocity = clickPercentY > 0.9 ? 4 : 2
  3614. if (this.listMaxScrollOffsetY - curListOffset.yOffset > scrollVelocity + 5) {
  3615. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset += scrollVelocity })
  3616. }
  3617. } else if (clickPercentY < 0.2 && curListOffset.yOffset >= 0) {
  3618. let scrollVelocity = clickPercentY < 0.1 ? 4 : 2
  3619. if (curListOffset.yOffset > scrollVelocity + 5) {
  3620. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset -= scrollVelocity })
  3621. }
  3622. }
  3623. })
  3624. .onActionEnd((event: GestureEvent) => {
  3625. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3626. this.dragItem = -1
  3627. this.neighborItem = -1
  3628. })
  3629. animateTo({
  3630. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  3631. }, () => {
  3632. this.scaleItem = -1
  3633. })
  3634. })
  3635. )
  3636. .onCancel(() => {
  3637. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3638. this.dragItem = -1
  3639. this.neighborItem = -1
  3640. })
  3641. animateTo({
  3642. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  3643. }, () => {
  3644. this.scaleItem = -1
  3645. })
  3646. })
  3647. ) //拖动List关键代码结束
  3648. }, (item: VideoItem) => item.filePath)
  3649. }
  3650. }
  3651. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  3652. .gesture(PinchGesture({ fingers: 2 })
  3653. .onActionEnd((event: GestureEvent) => {
  3654. this.setlistTwoFingers()
  3655. })
  3656. .onActionUpdate(e => {
  3657. this.scaleValue = this.pinchValue * e.scale
  3658. })
  3659. .onActionStart(e => {
  3660. }))
  3661. // .divider({ strokeWidth: 1, color: this.isDarkMode? '#333333':'#ffe9f0f0' })
  3662. .margin({
  3663. bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? this.topBarHeight+25 : this.topBarHeight+80)
  3664. : (this.isShowCoverHeader() ? this.topBarHeight+35 : this.isHiCarSmall()?this.topBarHeight+90:this.topBarHeight+125)
  3665. })
  3666. .cachedCount(6)
  3667. .borderRadius(20)
  3668. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  3669. TransitionEffect.scale({ x: 0, y: 0 })))
  3670. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3671. // .animation({ duration: 500, curve: Curve.Ease }))
  3672. .layoutWeight(1)
  3673. .onScrollIndex((start) => {
  3674. this.selectedIndex = start
  3675. })
  3676. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  3677. .lanes(
  3678. new BreakpointType<number>({
  3679. sm: 1,
  3680. md: 2,
  3681. lg: 2,
  3682. xl: 3,
  3683. xxl: 4
  3684. }).getValue(this.currentBreakpoint),
  3685. new BreakpointType<number>({
  3686. sm: 0,
  3687. md: 12,
  3688. lg: 12,
  3689. xl: 16,
  3690. xxl: 20
  3691. }).getValue(this.currentBreakpoint)
  3692. )
  3693. .onAreaChange((oldValue: Area, newValue: Area) => {
  3694. this.listArea = newValue
  3695. if (this.twoFingerType == 3) {
  3696. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  3697. } else if (this.twoFingerType == 2) {
  3698. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  3699. } else if (this.twoFingerType == 1) {
  3700. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  3701. }
  3702. })
  3703. .onScrollFrameBegin((offset: number) => {
  3704. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  3705. // if (this.isPhoneLan()) {
  3706. // this.setBarHeightHide(offset)
  3707. // } else
  3708. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  3709. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  3710. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  3711. if (this.isScrollHide) {
  3712. this.setBarHeightHide2(offset)
  3713. } else {
  3714. this.setBarHeightNormal()
  3715. }
  3716. } else {
  3717. this.setBarHeightHide(offset)
  3718. }
  3719. return { offsetRemain: offset };
  3720. })
  3721. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  3722. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3723. .onDrop((event?: DragEvent) => {
  3724. try {
  3725. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3726. if (dragData !== undefined) {
  3727. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3728. if (records.length > 0) {
  3729. for (let i = 0; i < records.length; i++) {
  3730. let types = records[i].getTypes();
  3731. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3732. const fileUriUds =
  3733. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3734. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3735. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3736. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3737. this.targetFile = fileUriUds.oriUri;
  3738. this.saveVideoDatas([this.targetFile])
  3739. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3740. }
  3741. }
  3742. }
  3743. } else {
  3744. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3745. }
  3746. } else {
  3747. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3748. }
  3749. } catch (error) {
  3750. const err = error as BusinessError;
  3751. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3752. }
  3753. })
  3754. }
  3755. setBarHeightNormal() {
  3756. this.hideDone = false;
  3757. this.getUIContext().animateTo({
  3758. duration: 300
  3759. }, () => {
  3760. this.bottomBarHeight = 55 + 0;
  3761. this.topBarHeight = 50 + 0;
  3762. this.barOpacity = 1;
  3763. this.barBottomOpacity = 1
  3764. this.currentYOffset = 0;
  3765. this.isHiding = false;
  3766. });
  3767. }
  3768. setBarHeightHide(offset: number) {
  3769. if (offset > 0 && !this.hideDone) {
  3770. this.currentYOffset += offset;
  3771. if (this.currentYOffset <= 100) {
  3772. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  3773. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  3774. this.barOpacity = 1 - this.currentYOffset / 100;
  3775. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  3776. } else {
  3777. this.topBarHeight = 0;
  3778. this.bottomBarHeight = 0;
  3779. this.barBottomOpacity = 0
  3780. this.barOpacity = 0;
  3781. this.hideDone = true;
  3782. }
  3783. this.isHiding = true;
  3784. }
  3785. if (offset < 0 && this.isHiding) {
  3786. this.hideDone = false;
  3787. this.getUIContext().animateTo({
  3788. duration: 300
  3789. }, () => {
  3790. this.bottomBarHeight = 55 + 0;
  3791. this.topBarHeight = 50 + 0;
  3792. this.barOpacity = 1;
  3793. this.barBottomOpacity = 1
  3794. this.currentYOffset = 0;
  3795. this.isHiding = false;
  3796. });
  3797. }
  3798. }
  3799. //这个方法没隐藏bottomBar,只隐藏topbar
  3800. setBarHeightHide2(offset: number) {
  3801. if (offset > 0 && !this.hideDone) {
  3802. this.currentYOffset += offset;
  3803. if (this.currentYOffset <= 100) {
  3804. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  3805. this.barOpacity = 1 - this.currentYOffset / 100;
  3806. } else {
  3807. this.topBarHeight = 0;
  3808. this.barOpacity = 0;
  3809. this.hideDone = true;
  3810. }
  3811. this.isHiding = true;
  3812. }
  3813. if (offset < 0 && this.isHiding) {
  3814. this.hideDone = false;
  3815. this.getUIContext().animateTo({
  3816. duration: 300
  3817. }, () => {
  3818. this.topBarHeight = 50 + 0;
  3819. this.barOpacity = 1;
  3820. this.currentYOffset = 0;
  3821. this.isHiding = false;
  3822. });
  3823. }
  3824. }
  3825. private doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean) {
  3826. switch (item.type) {
  3827. case CommonConstants.TYPE_IS_DIR:
  3828. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  3829. let offsetB = 0
  3830. if (this.isGridMusic) {
  3831. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  3832. let cur = this.scroller.currentOffset()
  3833. if (cur && typeof cur.yOffset === 'number') {
  3834. offsetB = cur.yOffset
  3835. }
  3836. }
  3837. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  3838. } else {
  3839. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  3840. let cur = this.listScroller.currentOffset()
  3841. if (cur && typeof cur.yOffset === 'number') {
  3842. offsetB = cur.yOffset
  3843. }
  3844. }
  3845. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  3846. }
  3847. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  3848. this.showVerifyDialog()
  3849. this.currentTitleName = '私密音频'
  3850. this.currentTitleCover = $r('app.media.ic_avatar5')
  3851. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  3852. this.titleBarModel.setTitleName('最近播放')
  3853. this.currentTitleCover = $r('app.media.ic_avatar2')
  3854. this.currentTitleName = '最近播放'
  3855. //加载动画效果
  3856. this.updateListData(this.historyList, true)
  3857. // this.videoLocalList = this.historyList
  3858. if (ArrayUtil.isEmpty(this.historyList)) {
  3859. ToastUtil.showToast('最近播放记录空空如也')
  3860. } else {
  3861. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  3862. }
  3863. this.isHistory = true
  3864. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3865. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  3866. this.titleBarModel.setTitleName('我的收藏')
  3867. this.currentTitleName = '我的收藏'
  3868. this.currentTitleCover = $r('app.media.ic_avatar1')
  3869. //加载动画效果
  3870. this.updateListData(this.favList)
  3871. if (ArrayUtil.isEmpty(this.favList)) {
  3872. ToastUtil.showToast('无音乐收藏记录')
  3873. } else {
  3874. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  3875. }
  3876. this.isFavMusic = true
  3877. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3878. } else {
  3879. this.currentTitleName = item.name
  3880. this.currentPath = item.filePath
  3881. this.currentTitleCover = $r('app.media.ic_avatar5')
  3882. this.getSortedFiles(this.currentPath)
  3883. }
  3884. //进入歌单的时候的滚动位置在顶部
  3885. if (this.isGridMusic) {
  3886. this.scroller.scrollToIndex(0)
  3887. }
  3888. setTimeout(() => {
  3889. if (this.modeType == 0) {
  3890. if (!this.isGridMusic) {
  3891. this.listScroller.scrollToIndex(0)
  3892. }
  3893. }
  3894. }, 200)
  3895. break;
  3896. case CommonConstants.TYPE_IS_ARTIST:
  3897. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  3898. let offsetA = 0
  3899. if (this.isGridMusic) {
  3900. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  3901. let cur = this.scroller.currentOffset()
  3902. if (cur && typeof cur.yOffset === 'number') {
  3903. offsetA = cur.yOffset
  3904. }
  3905. }
  3906. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  3907. } else {
  3908. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  3909. let cur = this.listScroller.currentOffset()
  3910. if (cur && typeof cur.yOffset === 'number') {
  3911. offsetA = cur.yOffset
  3912. }
  3913. }
  3914. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  3915. }
  3916. let mList = this.artistMap.get(item.name)
  3917. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  3918. Utility.doSortListAscending(mList)
  3919. this.isCanBack = true
  3920. this.titleBarModel.setTitleName(item.name)
  3921. this.currentTitleName = '艺术家:' + item.name
  3922. if (item.pixelMapPath) {
  3923. this.currentTitleCover = item.pixelMapPath
  3924. }
  3925. this.updateListData(mList)
  3926. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3927. }
  3928. //进入歌单的时候的滚动位置在顶部
  3929. if (this.isGridMusic) {
  3930. this.scroller.scrollToIndex(0)
  3931. }
  3932. break;
  3933. case CommonConstants.TYPE_IS_ALBUM:
  3934. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  3935. let offset = 0
  3936. if (this.isGridMusic) {
  3937. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  3938. let cur = this.scroller.currentOffset()
  3939. if (cur && typeof cur.yOffset === 'number') {
  3940. offset = cur.yOffset
  3941. }
  3942. }
  3943. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  3944. } else {
  3945. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  3946. let cur = this.listScroller.currentOffset()
  3947. if (cur && typeof cur.yOffset === 'number') {
  3948. offset = cur.yOffset
  3949. }
  3950. }
  3951. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  3952. }
  3953. let albumList = this.albumMap.get(item.name)
  3954. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  3955. Utility.doSortListAscending(albumList)
  3956. this.isCanBack = true
  3957. this.titleBarModel.setTitleName(item.name)
  3958. this.currentTitleName = '专辑:' + item.name
  3959. if (item.pixelMapPath) {
  3960. this.currentTitleCover = item.pixelMapPath
  3961. }
  3962. this.updateListData(albumList)
  3963. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3964. this.mScrollMap.set(item.name, this.selectedIndex)
  3965. }
  3966. //进入歌单的时候的滚动位置在顶部
  3967. if (this.isGridMusic) {
  3968. this.scroller.scrollToIndex(0)
  3969. }
  3970. break;
  3971. case CommonConstants.TYPE_IS_CSJAD:
  3972. return
  3973. break;
  3974. case CommonConstants.TYPE_LOCAL:
  3975. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  3976. this.stop();
  3977. }
  3978. if (isFromSonPlayList) { //点击来自右下角的播放列表
  3979. this.currentSong = item
  3980. if (index !== undefined) {
  3981. this.curIndex = index
  3982. }
  3983. } else {
  3984. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  3985. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  3986. this.songList = globalVideoList
  3987. this.sonDataSource.pushArrayData(this.songList)
  3988. this.currentSong = globalVideoList[this.curIndex]
  3989. }
  3990. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  3991. this.videoUrl = this.currentSong.filePath
  3992. this.name = this.currentSong.name
  3993. this.cover = this.currentSong.pixelMapPath
  3994. this.artist = this.currentSong.artist
  3995. LogUtil.info('this.currentSong.duration =' + this.currentSong.duration)
  3996. LogUtil.info('this.currentSong.sampleRate =' + this.currentSong.sampleRate)
  3997. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  3998. this.startPlayOrResumePlay()
  3999. break;
  4000. }
  4001. }
  4002. @Builder
  4003. PlayController() {
  4004. Column() {
  4005. Line().width('100%').height(1).backgroundColor($r('app.color.index_background'))
  4006. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  4007. Row() {
  4008. Row() {
  4009. RotatingCover({ songLabel: this.currentSong?.pixelMapPath })
  4010. Column() {
  4011. Text(this.currentSong?.name)
  4012. .fontSize(16)
  4013. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4014. .maxLines(1)
  4015. .fontColor($r('app.color.text_color'))
  4016. .fontWeight(500)
  4017. Row() {
  4018. Text(this.currentSong?.artist)
  4019. .margin({ top: 2 })
  4020. .fontSize(13)
  4021. .fontColor($r('app.color.text_color'))
  4022. }
  4023. }
  4024. .alignItems(HorizontalAlign.Start)
  4025. .margin({ right: 22 })
  4026. }
  4027. .padding({ right: 18 })
  4028. .layoutWeight(1)
  4029. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4030. .onClick(() => {
  4031. if (ArrayUtil.isNotEmpty(this.songList)) {
  4032. this.isShowPlay = true;
  4033. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  4034. this.initLyric(lyricPath);
  4035. this.startAutoHide()
  4036. } else {
  4037. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4038. }
  4039. })
  4040. Row() {
  4041. Image($r('app.media.hm_previous'))
  4042. .height(28)
  4043. .width(28)
  4044. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4045. .margin({ left: 8, right: 16 })
  4046. .fillColor(this.themeColor)
  4047. .displayPriority(2)
  4048. .onClick(() => {
  4049. if (ArrayUtil.isNotEmpty(this.songList)) {
  4050. this.playPrevious()
  4051. } else {
  4052. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4053. }
  4054. })
  4055. //播放进度条
  4056. Stack() {
  4057. Progress({
  4058. value: Math.floor(this.progressValue),
  4059. type: ProgressType.Ring,
  4060. })
  4061. .color(this.themeColor)// 进度条前景色为灰色
  4062. .backgroundColor($r('app.color.index_background'))
  4063. .height(40)
  4064. .aspectRatio(CommonConstants.ASPECT_RATIO)
  4065. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ? $r('app.media.hm_pause') : $r('app.media.hm_play2'))
  4066. .height(38)
  4067. .width(38)
  4068. .displayPriority(3)
  4069. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4070. .fillColor(this.themeColor)
  4071. .onClick(() => {
  4072. if (ArrayUtil.isNotEmpty(this.songList)) {
  4073. this.playOrPause()
  4074. } else {
  4075. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4076. }
  4077. })
  4078. }
  4079. Image($r('app.media.hm_next'))
  4080. .height(28)
  4081. .width(28)
  4082. .margin({
  4083. right: 16,
  4084. left: 16
  4085. })
  4086. .fillColor(this.themeColor)
  4087. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4088. .displayPriority(2)
  4089. .onClick(() => {
  4090. if (ArrayUtil.isNotEmpty(this.songList)) {
  4091. this.playNext()
  4092. } else {
  4093. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4094. }
  4095. })
  4096. Image($r('app.media.hm_playlist'))
  4097. .height(28)
  4098. .width(28)
  4099. .displayPriority(1)
  4100. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4101. .fillColor(this.themeColor)
  4102. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  4103. height: '95%',
  4104. dragBar: true,
  4105. showClose: true,
  4106. blurStyle: BlurStyle.Thin,
  4107. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  4108. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  4109. title: {
  4110. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  4111. + `(${this.songList.length}首)`
  4112. }
  4113. })
  4114. .onClick(() => {
  4115. if (ArrayUtil.isNotEmpty(this.songList)) {
  4116. this.isShowSheet = !this.isShowSheet;
  4117. this.isFrontWhite = false
  4118. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  4119. setTimeout(() => {
  4120. this.playListScroller.scrollToIndex(this.curIndex, true, ScrollAlign.CENTER)
  4121. }, 123)
  4122. } else {
  4123. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4124. }
  4125. })
  4126. }
  4127. }
  4128. .width('100%')
  4129. .height(this.bottomBarHeight)
  4130. .justifyContent(FlexAlign.Center)
  4131. .hitTestBehavior(HitTestMode.Transparent)
  4132. .backgroundColor(this.isCustomizeBg ? Color.Transparent : $r('app.color.bottom_control_background'))
  4133. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  4134. // modalTransition: ModalTransition.DEFAULT,
  4135. transition: AnimationHelper.transitionInDown(666),
  4136. backgroundColor: 'rgba(0, 0, 0, 0.9)',
  4137. })
  4138. .padding({
  4139. left: 16,
  4140. right: 16
  4141. })
  4142. Line()
  4143. .width('100%')
  4144. .height(25)
  4145. .backgroundColor($r('app.color.bottom_control_background'))// .visibility(this.isPhoneLan()?Visibility.None:this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  4146. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  4147. }
  4148. .clickEffect({ level: ClickEffectLevel.HEAVY })
  4149. }
  4150. @State isFrontWhite: boolean = false
  4151. //播放列表布局
  4152. @Builder
  4153. PlayListSheet() {
  4154. Column() {
  4155. this.PlayList()
  4156. }
  4157. .width('100%')
  4158. .height('100%')
  4159. }
  4160. @State titleStr: string = ''
  4161. @State ablumStr: string = ''
  4162. @State artistStr: string = ''
  4163. @State lyricConStr: string = ''
  4164. @State currentEditItem: string = ''
  4165. doUpdateData() {
  4166. setTimeout(() => {
  4167. if (this.modeType === 0) {
  4168. this.deleteCache(this.currentPath)
  4169. this.getSortedFiles(this.currentPath)
  4170. }
  4171. workerInstance.postMessage({ code: 2, data: this.context });
  4172. workerInstance.postMessage({ code: 3, data: this.context });
  4173. workerInstance.postMessage({ code: 4, data: this.context });
  4174. }, 999)
  4175. }
  4176. //编辑信息
  4177. doEdit(item: VideoItem) {
  4178. if (!item) {
  4179. return
  4180. }
  4181. if (StrUtil.isEmpty(this.titleStr)) {
  4182. ToastUtil.showToast('标题不能为空')
  4183. return
  4184. }
  4185. this.table.updateMediaInfo(item.filePath, this.titleStr, this.artistStr, this.ablumStr,
  4186. (success: boolean, error?: string) => {
  4187. this.isShowEdit = false
  4188. if (success) {
  4189. console.log(" onecold 编辑信息成功,数据库已同步");
  4190. ToastUtil.showToast('保存成功')
  4191. this.isShowMoreView = false
  4192. this.name = this.titleStr
  4193. if (item.filePath == this.currentSong?.filePath) {
  4194. this.currentSong.name = this.titleStr
  4195. this.artist = this.artistStr
  4196. this.currentSong.artist = this.artistStr
  4197. this.currentSong.album = this.ablumStr
  4198. }
  4199. this.doUpdateData()
  4200. } else {
  4201. ToastUtil.showToast('保存失败' + error?.toString())
  4202. console.error(" onecold 编辑信息数据库失败原因: " + error);
  4203. }
  4204. });
  4205. let doChangeLyric = false
  4206. if (item.filePath == this.currentSong?.filePath) {
  4207. if (this.lyricConStr !== this.lyricContent) {
  4208. doChangeLyric = true
  4209. }
  4210. } else if (this.lyricConStr !== this.tempLyricContent) {
  4211. doChangeLyric = true
  4212. }
  4213. if (doChangeLyric) {
  4214. let lyricPath = item.filePath.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  4215. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  4216. let isJiaMi = false;
  4217. let realLyricPath = lyricPath
  4218. if (FileUtil.accessSync(jiaMilyricPath)) {
  4219. isJiaMi = true
  4220. realLyricPath = jiaMilyricPath
  4221. console.info("onecold doEdit找到加密本地歌词 ");
  4222. } else {
  4223. isJiaMi = false
  4224. realLyricPath = lyricPath
  4225. console.info("onecold doEdit本地歌词 ");
  4226. }
  4227. this.saveDataToFile(this.lyricConStr, realLyricPath, isJiaMi)
  4228. }
  4229. }
  4230. updateLyricToDB() {
  4231. }
  4232. @Builder
  4233. editSheet(item: VideoItem) {
  4234. Scroll() {
  4235. Column() {
  4236. this.editDetail(item)
  4237. }
  4238. }
  4239. .width('100%')
  4240. .height('100%')
  4241. }
  4242. @Builder
  4243. editDetail(item: VideoItem) {
  4244. Column() {
  4245. if (item) {
  4246. Row() {
  4247. Stack() {
  4248. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') :
  4249. item.pixelMapPath)
  4250. .fillColor(this.themeColor)
  4251. .height(33)
  4252. .width(33)
  4253. .borderRadius('100%')
  4254. .clip(true)
  4255. .opacity(this.opacityItem)// 绑定透明度
  4256. .margin({ left: 20 })
  4257. }
  4258. .width('15%')
  4259. Row() {
  4260. Column() {
  4261. Text(item.name)
  4262. .fontSize(14)
  4263. .maxLines(1)
  4264. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4265. .animation({
  4266. duration: 555,
  4267. curve: 'Linear',
  4268. })
  4269. .fontColor(this.themeColor)
  4270. .margin({ left: 10 })
  4271. Row() {
  4272. Text(item.artist)
  4273. .fontSize(11)
  4274. .maxLines(1)
  4275. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4276. .padding({ top: 8 })
  4277. .fontColor(this.themeColor)
  4278. .margin({ left: 10 })
  4279. }
  4280. }
  4281. .height('100%')
  4282. .width(100)
  4283. .visibility(this.isDarkMode ? Visibility.None : Visibility.Visible)
  4284. .justifyContent(FlexAlign.Center)
  4285. .alignItems(HorizontalAlign.Start)
  4286. Button('本地封面')
  4287. .fontColor(Color.White)
  4288. .fontSize(12)
  4289. .height(38)
  4290. .width(88)
  4291. .backgroundColor(this.themeColor)
  4292. .stateEffect(true)
  4293. .margin({ right: 5, left: 12 })
  4294. .onClick(async () => {
  4295. this.goSelectImage(item)
  4296. })
  4297. Button('获取封面')
  4298. .fontColor(Color.White)
  4299. .fontSize(12)
  4300. .height(38)
  4301. .width(88)
  4302. .backgroundColor(this.themeColor)
  4303. .stateEffect(true)
  4304. .margin({ right: 12, left: 5 })
  4305. .onClick(async () => {
  4306. this.doSearchCover(item)
  4307. })
  4308. }
  4309. .height('100%')
  4310. .justifyContent(FlexAlign.Start)
  4311. .layoutWeight(1)
  4312. }
  4313. .width('100%')
  4314. .height(58)
  4315. Row() {
  4316. Text('标题:')
  4317. .fontSize(14)
  4318. .fontColor($r('app.color.text_color'))
  4319. .margin({ left: 22 })
  4320. TextInput({ text: item.name })
  4321. .height(40)
  4322. .maxLines(1)
  4323. .fontSize(14)
  4324. .layoutWeight(1)
  4325. .fontColor($r('app.color.text_color'))
  4326. .margin({ right: 20, left: 10 })
  4327. .onChange((val: string) => {
  4328. this.titleStr = val
  4329. })
  4330. }
  4331. .width('100%')
  4332. .margin({ top: 10, bottom: 10 })
  4333. .justifyContent(FlexAlign.Start)
  4334. Row() {
  4335. Text('艺术家:')
  4336. .fontSize(14)
  4337. .fontColor($r('app.color.text_color'))
  4338. .margin({ left: 22 })
  4339. TextInput({ text: item.artist })
  4340. .height(40)
  4341. .maxLines(1)
  4342. .fontSize(14)
  4343. .layoutWeight(1)
  4344. .fontColor($r('app.color.text_color'))
  4345. .margin({ right: 20, left: 10 })
  4346. .onChange((val: string) => {
  4347. this.artistStr = val
  4348. })
  4349. }
  4350. .width('100%')
  4351. .margin({ top: 10, bottom: 10 })
  4352. .justifyContent(FlexAlign.Start)
  4353. Row() {
  4354. Text('专辑名:')
  4355. .fontSize(14)
  4356. .fontColor($r('app.color.text_color'))
  4357. .margin({ left: 22 })
  4358. TextInput({ text: item.album })
  4359. .height(40)
  4360. .maxLines(1)
  4361. .fontSize(14)
  4362. .layoutWeight(1)
  4363. .fontColor($r('app.color.text_color'))
  4364. .margin({ right: 20, left: 10 })
  4365. .onChange((val: string) => {
  4366. this.ablumStr = val
  4367. })
  4368. }
  4369. .width('100%')
  4370. .margin({ top: 10, bottom: 10 })
  4371. .justifyContent(FlexAlign.Start)
  4372. Row() {
  4373. Text('歌词:')
  4374. .fontSize(14)
  4375. .fontColor($r('app.color.text_color'))
  4376. .margin({ left: 22 })
  4377. TextArea({ text: item.filePath === this.currentSong?.filePath ? this.lyricContent : this.tempLyricContent })
  4378. .type(TextAreaType.NORMAL)
  4379. .height(275)
  4380. .fontSize(14)
  4381. .layoutWeight(1)
  4382. .fontColor($r('app.color.text_color'))
  4383. .margin({ right: 20, left: 10 })
  4384. .onChange((val: string) => {
  4385. this.lyricConStr = val
  4386. })
  4387. }
  4388. .width('100%')
  4389. .margin({ top: 10, bottom: 10 })
  4390. .justifyContent(FlexAlign.Start)
  4391. Row() {
  4392. Button('保存')
  4393. .fontColor(Color.White)
  4394. .layoutWeight(1)
  4395. .height(50)
  4396. .width(100)
  4397. .backgroundColor(this.themeColor)
  4398. .stateEffect(true)
  4399. .margin({ right: 20, bottom: 20 })
  4400. .onClick(async () => {
  4401. this.doEdit(item)
  4402. })
  4403. Button('取消')
  4404. .fontColor(Color.White)
  4405. .layoutWeight(1)
  4406. .height(50)
  4407. .width(100)
  4408. .backgroundColor(this.themeColor)
  4409. .stateEffect(true)
  4410. .margin({ left: 20, bottom: 20 })
  4411. .onClick(async () => {
  4412. this.isShowEdit = false
  4413. })
  4414. }
  4415. .margin({
  4416. left: 38,
  4417. right: 38,
  4418. top: 10,
  4419. bottom: 10
  4420. })
  4421. .width(250)
  4422. .height(60)
  4423. }
  4424. }
  4425. .margin({ bottom: 20 })
  4426. }
  4427. @Builder
  4428. detailSheet(item:VideoItem) {
  4429. Scroll() {
  4430. Column() {
  4431. this.songDetail(item)
  4432. }
  4433. }
  4434. .width('100%')
  4435. .height('100%')
  4436. }
  4437. @Builder
  4438. songDetail(currentItem:VideoItem) {
  4439. Column() {
  4440. if (currentItem) {
  4441. Row() {
  4442. Stack() {
  4443. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.music_red') :
  4444. currentItem.pixelMapPath)
  4445. .fillColor(this.themeColor)
  4446. .height(33)
  4447. .width(33)
  4448. .borderRadius('100%')
  4449. .clip(true)
  4450. .opacity(this.opacityItem)// 绑定透明度
  4451. .margin({ left: 20 })
  4452. }
  4453. .width('15%')
  4454. Column() {
  4455. Column() {
  4456. Text(currentItem.name)
  4457. .fontSize(14)
  4458. .maxLines(1)
  4459. .animation({
  4460. duration: 555,
  4461. curve: 'Linear',
  4462. })
  4463. .fontColor($r('app.color.text_color'))
  4464. .margin({ left: 10 })
  4465. Row() {
  4466. Text(StrUtil.isEmpty(currentItem.artist) ? currentItem.cTime :
  4467. currentItem.artist + ' ' + currentItem?.album)
  4468. .fontSize(11)
  4469. .padding({ top: 8 })
  4470. .fontColor($r('app.color.text_color'))
  4471. .margin({ left: 10 })
  4472. }
  4473. }
  4474. .height('100%')
  4475. .width('100%')
  4476. .justifyContent(FlexAlign.Center)
  4477. .alignItems(HorizontalAlign.Start)
  4478. }
  4479. .height('100%')
  4480. }
  4481. .width('100%')
  4482. .height(58)
  4483. .justifyContent(FlexAlign.SpaceBetween)
  4484. Row() {
  4485. Text('歌手名:')
  4486. .fontSize(14)
  4487. .fontColor(Color.White)
  4488. .margin({ left: 22 })
  4489. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  4490. .fontSize(14)
  4491. .fontColor(Color.White)
  4492. .margin({ left: 10 })
  4493. .layoutWeight(1)
  4494. }
  4495. .width('100%')
  4496. .margin({ top: 10, bottom: 10 })
  4497. .justifyContent(FlexAlign.Start)
  4498. Row() {
  4499. Text('专辑名:')
  4500. .fontSize(14)
  4501. .fontColor(Color.White)
  4502. .margin({ left: 22 })
  4503. Text(currentItem?.album ?currentItem.album : '未知专辑')
  4504. .fontSize(14)
  4505. .margin({ left: 10 })
  4506. .fontColor(Color.White)
  4507. .layoutWeight(1)
  4508. }
  4509. .width('100%')
  4510. .margin({ top: 10, bottom: 10 })
  4511. .justifyContent(FlexAlign.Start)
  4512. Row() {
  4513. Text('时长:')
  4514. .fontSize(14)
  4515. .fontColor(Color.White)
  4516. .margin({ left: 22 })
  4517. Text(StrUtil.isEmpty(currentItem.duration)?
  4518. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  4519. .fontSize(14)
  4520. .margin({ left: 10 })
  4521. .fontColor(Color.White)
  4522. .layoutWeight(1)
  4523. }
  4524. .width('100%')
  4525. .margin({ top: 10, bottom: 10 })
  4526. .justifyContent(FlexAlign.Start)
  4527. Row() {
  4528. Text('采样率:')
  4529. .fontSize(14)
  4530. .fontColor(Color.White)
  4531. .margin({ left: 22 })
  4532. Text(Utility.convertToKHz(currentItem.sampleRate))
  4533. .fontSize(14)
  4534. .margin({ left: 10 })
  4535. .fontColor(Color.White)
  4536. .layoutWeight(1)
  4537. }
  4538. .width('100%')
  4539. .margin({ top: 10, bottom: 10 })
  4540. .justifyContent(FlexAlign.Start)
  4541. Row() {
  4542. Text('比特率:')
  4543. .fontSize(14)
  4544. .fontColor(Color.White)
  4545. .margin({ left: 22 })
  4546. Text(currentItem.bit_rate)
  4547. .fontSize(14)
  4548. .margin({ left: 10 })
  4549. .fontColor(Color.White)
  4550. .layoutWeight(1)
  4551. }
  4552. .width('100%')
  4553. .margin({ top: 10, bottom: 10 })
  4554. .justifyContent(FlexAlign.Start)
  4555. Row() {
  4556. Text('风格:')
  4557. .fontSize(14)
  4558. .fontColor(Color.White)
  4559. .margin({ left: 22 })
  4560. Text(currentItem.genre)
  4561. .fontSize(14)
  4562. .margin({ left: 10 })
  4563. .fontColor(Color.White)
  4564. .layoutWeight(1)
  4565. }
  4566. .width('100%')
  4567. .margin({ top: 10, bottom: 10 })
  4568. .justifyContent(FlexAlign.Start)
  4569. Row() {
  4570. Text('发行时间:')
  4571. .fontSize(14)
  4572. .fontColor(Color.White)
  4573. .margin({ left: 22 })
  4574. Text(currentItem.year)
  4575. .fontSize(14)
  4576. .margin({ left: 10 })
  4577. .fontColor(Color.White)
  4578. .layoutWeight(1)
  4579. }
  4580. .width('100%')
  4581. .margin({ top: 10, bottom: 10 })
  4582. .justifyContent(FlexAlign.Start)
  4583. Row() {
  4584. Text('质量评分:')
  4585. .fontSize(14)
  4586. .fontColor(Color.White)
  4587. .margin({ left: 22 })
  4588. Text(currentItem.probe_score+"")
  4589. .fontSize(14)
  4590. .margin({ left: 10 })
  4591. .fontColor(Color.White)
  4592. .layoutWeight(1)
  4593. }
  4594. .width('100%')
  4595. .margin({ top: 10, bottom: 10 })
  4596. .justifyContent(FlexAlign.Start)
  4597. Row() {
  4598. Text('音轨号:')
  4599. .fontSize(14)
  4600. .fontColor(Color.White)
  4601. .margin({ left: 22 })
  4602. Text(currentItem.track)
  4603. .fontSize(14)
  4604. .margin({ left: 10 })
  4605. .fontColor(Color.White)
  4606. .layoutWeight(1)
  4607. }
  4608. .width('100%')
  4609. .margin({ top: 10, bottom: 10 })
  4610. .justifyContent(FlexAlign.Start)
  4611. Row() {
  4612. Text('格式:')
  4613. .fontSize(14)
  4614. .fontColor(Color.White)
  4615. .margin({ left: 22 })
  4616. Text(Utility.formatMimeType(currentItem.mimeType))
  4617. .fontSize(14)
  4618. .margin({ left: 10 })
  4619. .fontColor(Color.White)
  4620. .layoutWeight(1)
  4621. }
  4622. .width('100%')
  4623. .margin({ top: 10, bottom: 10 })
  4624. .justifyContent(FlexAlign.Start)
  4625. Row() {
  4626. Text('播放次数:')
  4627. .fontSize(14)
  4628. .fontColor(Color.White)
  4629. .margin({ left: 22 })
  4630. Text(currentItem.playCount?.toString())
  4631. .fontSize(14)
  4632. .margin({ left: 10 })
  4633. .fontColor(Color.White)
  4634. .layoutWeight(1)
  4635. }
  4636. .width('100%')
  4637. .margin({ top: 10, bottom: 10 })
  4638. .justifyContent(FlexAlign.Start)
  4639. Row() {
  4640. Text('流数量:')
  4641. .fontSize(14)
  4642. .fontColor(Color.White)
  4643. .margin({ left: 22 })
  4644. Text(currentItem.nb_streams?.toString())
  4645. .fontSize(14)
  4646. .margin({ left: 10 })
  4647. .fontColor(Color.White)
  4648. .layoutWeight(1)
  4649. }
  4650. .width('100%')
  4651. .margin({ top: 10, bottom: 10 })
  4652. .justifyContent(FlexAlign.Start)
  4653. Row() {
  4654. Text('文件大小:')
  4655. .fontSize(14)
  4656. .fontColor(Color.White)
  4657. .margin({ left: 22 })
  4658. Text(currentItem.size)
  4659. .fontSize(14)
  4660. .margin({ left: 10 })
  4661. .fontColor(Color.White)
  4662. .layoutWeight(1)
  4663. }
  4664. .width('100%')
  4665. .margin({ top: 10, bottom: 10 })
  4666. .justifyContent(FlexAlign.Start)
  4667. Row() {
  4668. Text('文件名:')
  4669. .fontSize(14)
  4670. .fontColor(Color.White)
  4671. .margin({ left: 22 })
  4672. Text(currentItem.fileName)
  4673. .fontSize(14)
  4674. .margin({ left: 10 })
  4675. .fontColor(Color.White)
  4676. .layoutWeight(1)
  4677. }
  4678. .width('100%')
  4679. .margin({ top: 10, bottom: 10 })
  4680. .justifyContent(FlexAlign.Start)
  4681. Row() {
  4682. Text('修改时间:')
  4683. .fontSize(14)
  4684. .fontColor(Color.White)
  4685. .margin({ left: 22 })
  4686. Text(currentItem.cTime)
  4687. .fontSize(14)
  4688. .margin({ left: 10 })
  4689. .fontColor(Color.White)
  4690. .layoutWeight(1)
  4691. }
  4692. .width('100%')
  4693. .margin({ top: 10, bottom: 10 })
  4694. .justifyContent(FlexAlign.Start)
  4695. Row() {
  4696. Text('存放目录:')
  4697. .fontSize(14)
  4698. .fontColor(Color.White)
  4699. .margin({ left: 22 })
  4700. Text(currentItem.filePath)
  4701. .fontSize(12)
  4702. .margin({ left: 10 })
  4703. .fontColor(Color.White)
  4704. .layoutWeight(1)
  4705. }
  4706. .margin({ top: 10, bottom: 10 })
  4707. .width('100%')
  4708. .justifyContent(FlexAlign.Start)
  4709. }
  4710. }
  4711. .margin({ bottom: 20 })
  4712. }
  4713. //定时关闭布局
  4714. @Builder
  4715. TimeCloseSheet() {
  4716. Scroll() {
  4717. Column() {
  4718. this.TimeClose()
  4719. }
  4720. }
  4721. .width('100%')
  4722. .height('100%')
  4723. }
  4724. //倒计时关闭音乐,退出App功能实现。
  4725. @State selectedMinutes: number = 0 // 0表示未开启
  4726. @State remainingSeconds: number = 0
  4727. // 预设时间选项
  4728. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  4729. private formatTime(seconds: number): string {
  4730. const mins = Math.floor(seconds / 60)
  4731. const secs = seconds % 60
  4732. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  4733. }
  4734. // 开始倒计时
  4735. private handleTimeSelect(minutes: number) {
  4736. if (minutes === this.selectedMinutes) {
  4737. this.stopCountdown();
  4738. this.selectedMinutes = 0;
  4739. return;
  4740. }
  4741. this.selectedMinutes = minutes;
  4742. this.remainingSeconds = minutes * 60;
  4743. this.startCountdown(); // 新增调用
  4744. }
  4745. @Builder
  4746. TimeClose() {
  4747. Column() {
  4748. // 倒计时显示区域
  4749. Text(this.selectedMinutes > 0 ?
  4750. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  4751. "定时关闭未开启")
  4752. .fontSize(17)
  4753. .fontColor($r('app.color.text_color'))
  4754. .margin({ top: 2, bottom: 8 });
  4755. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  4756. ForEach(this.presetTimes, (minutes: number, index: number) => {
  4757. // 单行时间选项容器
  4758. Row() {
  4759. // 文字描述区域
  4760. Text(this.getDisplayText(minutes))
  4761. .fontSize(15)
  4762. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  4763. $r('app.color.text_color'))// 选中态颜色变化
  4764. .textAlign(TextAlign.Start)
  4765. .layoutWeight(1); // 占据剩余空间
  4766. // 复选框样式的选择器
  4767. Row() {
  4768. if (minutes === this.selectedMinutes) {
  4769. // 选中状态 - 带勾号的圆形复选框
  4770. Row() {
  4771. // 使用系统内置的勾号图标
  4772. Image($r('sys.media.ohos_ic_public_ok'))
  4773. .width(14)
  4774. .height(14)
  4775. .fillColor(Color.White)
  4776. }
  4777. .width(24)
  4778. .height(24)
  4779. .borderRadius(12)
  4780. .backgroundColor(this.themeColor)
  4781. .justifyContent(FlexAlign.Center)
  4782. .alignItems(VerticalAlign.Center)
  4783. } else {
  4784. // 未选中状态的圆形边框
  4785. Row()
  4786. .width(24)
  4787. .height(24)
  4788. .borderRadius(12)
  4789. .border({
  4790. width: 2,
  4791. color: $r('app.color.text_color'),
  4792. style: BorderStyle.Solid
  4793. })
  4794. .backgroundColor(Color.Transparent)
  4795. }
  4796. }
  4797. .width(24)
  4798. .height(24)
  4799. .margin({ left: 20 })
  4800. .justifyContent(FlexAlign.Center)
  4801. .alignItems(VerticalAlign.Center)
  4802. }
  4803. .width('100%')
  4804. .padding({
  4805. top: 18,
  4806. bottom: 18,
  4807. left: 18,
  4808. right: 18
  4809. })
  4810. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  4811. $r('app.color.bottom_control_background')) // 选中背景高亮
  4812. .borderRadius(12)
  4813. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  4814. .margin({ bottom: 18 })
  4815. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  4816. });
  4817. }
  4818. .width('100%')
  4819. .padding(16)
  4820. }
  4821. }
  4822. // 获取显示文本
  4823. private getDisplayText(minutes: number): string {
  4824. if (minutes === -1) {
  4825. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  4826. }
  4827. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  4828. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  4829. }
  4830. // 处理选择事件
  4831. private handleSelect(minutes: number): void {
  4832. if (minutes === -1) { // 自定义
  4833. // 弹出自定义时间对话框
  4834. DialogHelper.showTextInputDialog({
  4835. title: '自定义时间',
  4836. maskColor: Color.Transparent,
  4837. inputType: InputType.Number,
  4838. text: '',
  4839. onChange: (text) => {
  4840. console.error("onChange: " + text);
  4841. },
  4842. onAction: (action, dialogId, content) => {
  4843. if (action == DialogAction.TWO) {
  4844. const customMinutes = Number(content);
  4845. if (customMinutes > 0) {
  4846. this.handleTimeSelect(customMinutes); // 设置自定义时间
  4847. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  4848. }
  4849. }
  4850. }
  4851. });
  4852. } else {
  4853. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  4854. }
  4855. }
  4856. // 添加定时器引用
  4857. private timerId: number = -1;
  4858. // 启动/重置倒计时
  4859. private startCountdown() {
  4860. // 清除旧定时器
  4861. if (this.timerId !== -1) {
  4862. clearInterval(this.timerId);
  4863. }
  4864. // 创建新定时器
  4865. if (this.selectedMinutes > 0) {
  4866. this.timerId = setInterval(() => {
  4867. if (this.remainingSeconds === 15) {
  4868. this.showConfirmationDialog();
  4869. }
  4870. if (this.remainingSeconds > 0) {
  4871. this.remainingSeconds -= 1;
  4872. } else {
  4873. this.stopCountdown();
  4874. this.handleTimeout();
  4875. }
  4876. }, 1000);
  4877. }
  4878. }
  4879. // 15倒计时后再次提示显示确认是否关闭App对话框
  4880. private showConfirmationDialog() {
  4881. DialogHelper.showAlertDialog({
  4882. backgroundColor: $r('app.color.btn_green'),
  4883. title: '确认关闭',
  4884. maskColor: Color.Transparent,
  4885. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  4886. borderStyle: BorderStyle.Dashed,
  4887. primaryButton: '暂不关闭',
  4888. secondaryButton: '确定',
  4889. onAction: (action) => {
  4890. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  4891. this.stopCountdown();
  4892. this.selectedMinutes = 0
  4893. } else if (action == DialogAction.TWO) {
  4894. }
  4895. }
  4896. })
  4897. }
  4898. // 停止倒计时
  4899. private stopCountdown() {
  4900. if (this.timerId !== -1) {
  4901. clearInterval(this.timerId);
  4902. this.timerId = -1;
  4903. }
  4904. }
  4905. // 超时处理
  4906. private handleTimeout() {
  4907. // 执行播放器关闭逻辑
  4908. this.selectedMinutes = 0;
  4909. ToastUtil.showToast(" 定时关闭已完成");
  4910. this.stop(); // 假设存在的播放器实例
  4911. //退出APP
  4912. const mContext = getContext(this) as common.UIAbilityContext
  4913. mContext.terminateSelf();
  4914. AvSessionController.getInstance(true).unregisterSessionListener()
  4915. }
  4916. //倒计时关闭音乐,退出App功能实现结束。
  4917. //播放列表的拖动List 重新排序
  4918. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  4919. //左滑操作 移动文件 重命名 删除等操作
  4920. @Builder
  4921. sonButton(item: VideoItem, index: number, filePath: string) {
  4922. Row() {
  4923. //加入下一首播放
  4924. Button() {
  4925. Image($r('app.media.next_to_play'))
  4926. .fillColor(Color.White)
  4927. .width(20)
  4928. }
  4929. .width(40)
  4930. .height(40)
  4931. .type(ButtonType.Circle)
  4932. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  4933. .backgroundColor(this.themeColor)
  4934. .margin(5)
  4935. .onClick(() => {
  4936. this.addToNextPlay(item);
  4937. })
  4938. Button() {
  4939. Image($r('app.media.close'))
  4940. .fillColor(Color.White)
  4941. .width(20)
  4942. }
  4943. .width(40)
  4944. .height(40)
  4945. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  4946. .type(ButtonType.Circle)
  4947. .backgroundColor(this.themeColor)
  4948. .margin(5)
  4949. .onClick(() => {
  4950. this.songList.splice(Number(index), 1)
  4951. this.sonDataSource.pushArrayData(this.songList)
  4952. })
  4953. Button() {
  4954. Image($r('app.media.share2'))
  4955. .fillColor(Color.White)
  4956. .width(20)
  4957. }
  4958. .width(40)
  4959. .height(40)
  4960. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  4961. .type(ButtonType.Circle)
  4962. .backgroundColor(this.themeColor)
  4963. .margin(5)
  4964. .onClick(() => {
  4965. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  4966. })
  4967. }
  4968. }
  4969. itemMoveSon(index: number, newIndex: number): void {
  4970. if (newIndex < 0 || newIndex >= this.songList.length) {
  4971. return;
  4972. }
  4973. let tmp = this.songList.splice(index, 1);
  4974. this.songList.splice(newIndex, 0, tmp[0]);
  4975. this.sonDataSource.pushArrayData(this.songList)
  4976. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  4977. }
  4978. @Builder
  4979. PlayList() {
  4980. List({ scroller: this.playListScroller }) {
  4981. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  4982. ListItem() {
  4983. this.MusicItemSon(item, index)
  4984. }
  4985. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  4986. .animation({
  4987. duration: 666,
  4988. curve: 'ease-in-out' // 可选动画曲线
  4989. })
  4990. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  4991. TransitionEffect.scale({ x: 0, y: 0 })))
  4992. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  4993. //拖动List关键代码开始
  4994. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  4995. .zIndex(this.dragItem === index ? 1 : 0)
  4996. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  4997. .gesture(
  4998. GestureGroup(GestureMode.Sequence,
  4999. LongPressGesture({ repeat: true })
  5000. .onAction((event?: GestureEvent) => {
  5001. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5002. this.scaleItem = index
  5003. })
  5004. })
  5005. .onActionEnd(() => {
  5006. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5007. this.scaleItem = -1
  5008. })
  5009. }),
  5010. PanGesture({ fingers: 1, direction: null, distance: 0 })
  5011. .onActionStart(() => {
  5012. this.dragItem = index // 记录当前拖动项索引
  5013. this.dragRefOffset = 0 // 重置偏移基准
  5014. })
  5015. .onActionUpdate((event: GestureEvent) => {
  5016. this.offsetY = event.offsetY - this.dragRefOffset;
  5017. this.neighborItem = -1;
  5018. let indexA = this.songList.indexOf(item);
  5019. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  5020. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  5021. let value: number = 0;
  5022. if (this.offsetY < 0) {
  5023. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  5024. this.neighborItem = indexA - 1;
  5025. this.neighborScale = 1 - value / 20;
  5026. } else if (this.offsetY > 0) {
  5027. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  5028. this.neighborItem = indexA + 1;
  5029. this.neighborScale = 1 - value / 20;
  5030. }
  5031. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  5032. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5033. this.offsetY -= this.ITEM_INTV;
  5034. this.dragRefOffset += this.ITEM_INTV;
  5035. this.itemMoveSon(indexA, indexA + 1);
  5036. });
  5037. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  5038. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5039. this.offsetY += this.ITEM_INTV;
  5040. this.dragRefOffset -= this.ITEM_INTV;
  5041. this.itemMoveSon(indexA, indexA - 1);
  5042. });
  5043. }
  5044. })
  5045. .onActionEnd((event: GestureEvent) => {
  5046. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5047. this.dragItem = -1
  5048. this.neighborItem = -1
  5049. })
  5050. animateTo({
  5051. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5052. }, () => {
  5053. this.scaleItem = -1
  5054. })
  5055. })
  5056. )
  5057. .onCancel(() => {
  5058. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5059. this.dragItem = -1
  5060. this.neighborItem = -1
  5061. })
  5062. animateTo({
  5063. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5064. }, () => {
  5065. this.scaleItem = -1
  5066. })
  5067. })
  5068. ) //拖动List关键代码结束
  5069. .onClick(() => {
  5070. this.doPlay(item, index, true)
  5071. })
  5072. }, (item: VideoItem) => item.filePath)
  5073. }
  5074. .width('100%')
  5075. .height('100%')
  5076. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  5077. // .animation({ duration: 500, curve: Curve.Ease }))
  5078. .cachedCount(10)
  5079. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5080. .gesture(PinchGesture({ fingers: 2 })
  5081. .onActionEnd((event: GestureEvent) => {
  5082. this.setlistTwoFingers()
  5083. })
  5084. .onActionUpdate(e => {
  5085. this.scaleValue = this.pinchValue * e.scale
  5086. })
  5087. .onActionStart(e => {
  5088. }))
  5089. .padding({
  5090. bottom: 0
  5091. })
  5092. }
  5093. @Builder
  5094. private MusicItemSon(item: VideoItem, index?: number) {
  5095. Button({ type: ButtonType.Normal, stateEffect: true }) {
  5096. Row() {
  5097. Stack() {
  5098. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  5099. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  5100. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  5101. .alt($r('app.media.music_red'))
  5102. .fillColor(this.themeColor)
  5103. .borderRadius('100%')
  5104. .clip(true)
  5105. .margin({ left: 20 })
  5106. }
  5107. .width('15%')
  5108. Column() {
  5109. Column() {
  5110. Text(item.name)
  5111. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5112. .fontColor(this.curIndex === index ? this.themeColor :
  5113. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  5114. .maxLines(1)
  5115. .margin({ left: this.twoFingerType == 3 ? 18 : 10 })
  5116. Row() {
  5117. Column(){
  5118. Text(item.md5Str?.includes('Lossless')?
  5119. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5120. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5121. .padding({ top: 3,right:6,left:6,bottom:3 })
  5122. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5123. $r('app.color.text_color'))
  5124. .fontWeight(500)
  5125. .borderRadius(12)
  5126. .margin({ left: this.twoFingerType == 3 ? 12 : 10 })
  5127. .backgroundColor('#FFC107')
  5128. }
  5129. .padding({ top: 8 })
  5130. Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
  5131. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5132. .padding({ top: 8 })
  5133. .fontColor(this.curIndex === index ? this.themeColor :
  5134. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  5135. .margin({ left: this.twoFingerType == 3 ? 5 : 3 })
  5136. Blank()
  5137. Text(item.size)
  5138. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5139. .padding({ top: 8 })
  5140. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  5141. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  5142. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  5143. .margin({ left: 10 })
  5144. }
  5145. }
  5146. .height('100%')
  5147. .width('100%')
  5148. .justifyContent(FlexAlign.Center)
  5149. .alignItems(HorizontalAlign.Start)
  5150. }
  5151. .height('100%')
  5152. .width('65%')
  5153. Column() {
  5154. ImageAnimator()
  5155. .images(this.imagesF)// 动画数组
  5156. .duration(1000)// 持续
  5157. .state(this.animationState)// 动画状态
  5158. .fillMode(FillMode.Forwards)
  5159. .width(18)
  5160. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  5161. Visibility.None)
  5162. .height(18)
  5163. .iterations(-1) // 播放次数
  5164. }
  5165. .width('20%')
  5166. }
  5167. }
  5168. .backgroundColor(Color.Transparent)
  5169. .width('100%')
  5170. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  5171. .shadow(this.scaleItem === index ? {
  5172. radius: 70,
  5173. color: '#15000000',
  5174. offsetX: 0,
  5175. offsetY: 0
  5176. } :
  5177. {
  5178. radius: 0,
  5179. color: '#15000000',
  5180. offsetX: 0,
  5181. offsetY: 0
  5182. })
  5183. .animation({ curve: Curve.Sharp, duration: 300 })
  5184. }
  5185. @Builder
  5186. MusicPlayBuilder() {
  5187. Column() {
  5188. this.IjkMusicPlayerView()
  5189. }
  5190. .height('100%')
  5191. .width('100%')
  5192. .onDisAppear(() => {
  5193. this.translateY = 0;
  5194. })
  5195. .translate({ y: this.translateY })
  5196. .gesture(
  5197. PanGesture(this.panOption)
  5198. .onActionUpdate((event?: GestureEvent) => {
  5199. if (event) {
  5200. // 只允许向下滑动,向上滑动时限制为0
  5201. this.translateY = Math.max(0, event.offsetY);
  5202. }
  5203. })
  5204. .onActionEnd((event?: GestureEvent) => {
  5205. // 使用更低的阈值和滑动速度判断
  5206. const minDistance = 100; // 最小滑动距离 100vp
  5207. const minVelocity = 500; // 最小滑动速度
  5208. // 获取滑动速度(如果可用)
  5209. const velocity = event?.velocityY || 0;
  5210. // 判断是否应该关闭:距离足够 或者 速度足够快
  5211. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  5212. if (shouldClose) {
  5213. // 添加关闭动画
  5214. this.getUIContext().animateTo({
  5215. duration: 300,
  5216. curve: Curve.Smooth
  5217. }, () => {
  5218. this.isShowPlay = false;
  5219. this.translateY = 0;
  5220. })
  5221. } else {
  5222. // 回弹动画
  5223. this.getUIContext().animateTo({
  5224. duration: 300,
  5225. curve: Curve.Smooth
  5226. }, () => {
  5227. this.translateY = 0;
  5228. })
  5229. }
  5230. })
  5231. )
  5232. }
  5233. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  5234. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  5235. HeightBreakpoint.HEIGHT_LG;
  5236. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  5237. @State topBarHeight: number = 50
  5238. @State barOpacity: number = 1
  5239. @State barBottomOpacity: number = 1
  5240. private hideDone: boolean = false;
  5241. @State currentYOffset: number = 0;
  5242. @State bottomBarHeight: number = 60;
  5243. private isHiding: boolean = false;
  5244. //是否是Pura X外屏,或者小屏幕
  5245. isPuraWP() {
  5246. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  5247. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  5248. }
  5249. //是否是Pura X外屏,或者小屏幕,手机横屏
  5250. isCoverOpacity() {
  5251. if (this.isPuraWP()) {
  5252. return true
  5253. }
  5254. if (this.isPhoneLan()) {
  5255. return true
  5256. }
  5257. if (deviceInfo.marketName.includes('Pura X')
  5258. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  5259. return true
  5260. }
  5261. return false
  5262. }
  5263. //是不是手机横屏
  5264. isPhoneLan() {
  5265. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  5266. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  5267. LogUtil.info('hicar isPhoneLan width= ' + this.windowWidth);
  5268. LogUtil.info('hicar isPhoneLan height= ' + this.windowHeight);
  5269. LogUtil.info(`twocold hicarWindow size: ${this.windowWidth}x${this.windowHeight}, this.isHiCarStatus: ${this.isHiCarStatus}`);
  5270. LogUtil.info(`twocold hicar Window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall: ${this.isHiCarSmall()}`);
  5271. if (this.isHiCarStatus) {
  5272. return false
  5273. }
  5274. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  5275. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  5276. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  5277. return true
  5278. }
  5279. return false
  5280. }
  5281. //是不是1920x720的hicar的屏幕分辨率
  5282. isHiCarKuanBianPing(){
  5283. const hiCarAspectRatios: HiCarAspectRatio[] = [
  5284. { ratio: 1920 / 720, name: "1920x720" },
  5285. ];
  5286. const currentRatio: number = this.windowWidth / this.windowHeight;
  5287. const RATIO_TOLERANCE: number = 0.18; // 宽高比容差
  5288. LogUtil.info('twocold currentRatio = ' + currentRatio)
  5289. for (const hiCarRatio of hiCarAspectRatios) {
  5290. LogUtil.info('twocold hiCarRatio= ' + hiCarRatio.ratio)
  5291. LogUtil.info('twocold Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  5292. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  5293. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  5294. return true&&this.isHiCarStatus;
  5295. }
  5296. }
  5297. return false;
  5298. }
  5299. //是不是hicar的屏幕分辨率
  5300. isHiCarSmall() {
  5301. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  5302. return false
  5303. const hiCarAspectRatios: HiCarAspectRatio[] = [
  5304. { ratio: 800 / 480, name: "800x480" },
  5305. { ratio: 1280 / 720, name: "1280x720" },
  5306. { ratio: 1920 / 720, name: "1920x720" },
  5307. ];
  5308. const currentRatio: number = this.windowWidth / this.windowHeight;
  5309. const RATIO_TOLERANCE: number = 0.18; // 宽高比容差
  5310. LogUtil.info('twocold currentRatio = ' + currentRatio)
  5311. for (const hiCarRatio of hiCarAspectRatios) {
  5312. LogUtil.info('twocold hiCarRatio= ' + hiCarRatio.ratio)
  5313. LogUtil.info('twocold Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  5314. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  5315. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  5316. return true&&this.isHiCarStatus;
  5317. }
  5318. }
  5319. return false;
  5320. }
  5321. isHiCar() {
  5322. return this.isHiCarStatus;
  5323. // const hiCarAspectRatios: HiCarAspectRatio[] = [
  5324. // { ratio: 800 / 480, name: "800x480" },
  5325. // { ratio: 762 / 752, name: "762x752" },
  5326. // { ratio: 968 / 1280, name: "968x1280" },
  5327. // { ratio: 1200 / 1200, name: "1200x1200" },
  5328. // { ratio: 1280 / 720, name: "1280x720" },
  5329. // { ratio: 1920 / 720, name: "1920x720" },
  5330. // { ratio: 1920 / 1080, name: "1920x1080" }
  5331. // ];
  5332. // const currentRatio: number = this.windowWidth / this.windowHeight;
  5333. // const RATIO_TOLERANCE: number = 0.18; // 宽高比容差
  5334. // LogUtil.info('twocold currentRatio = ' + currentRatio)
  5335. //
  5336. // for (const hiCarRatio of hiCarAspectRatios) {
  5337. // LogUtil.info('twocold hiCarRatio= ' + hiCarRatio.ratio)
  5338. // LogUtil.info('twocold Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  5339. // if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  5340. // // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  5341. // return true&&this.isHiCarStatus;
  5342. // }
  5343. // }
  5344. //
  5345. // return false;
  5346. }
  5347. //是不是正常的手机竖屏
  5348. isPhonePortrait() {
  5349. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  5350. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  5351. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  5352. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  5353. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  5354. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  5355. return true
  5356. }
  5357. return false
  5358. }
  5359. @State showSpeedDialog: boolean = false
  5360. @State longPressSpeed: number = 3 //长按默认倍数
  5361. @Builder
  5362. SpeedDialog() {
  5363. Stack() {
  5364. Column() {
  5365. Text('已切换至' + this.longPressSpeed + '倍速播放')
  5366. .fontColor(Color.White)
  5367. .visibility(Visibility.Hidden)
  5368. }
  5369. .backgroundColor(Color.Black)
  5370. .borderRadius(20)
  5371. .padding({
  5372. top: 10,
  5373. right: 20,
  5374. left: 15,
  5375. bottom: 20
  5376. })
  5377. .opacity(0.6)
  5378. Text('已切换至' + this.longPressSpeed + '倍速播放')
  5379. .fontColor(Color.White)
  5380. }
  5381. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  5382. .zIndex(5)
  5383. .margin({ top: 80 })
  5384. }
  5385. @Builder
  5386. IjkMusicPlayerView() {
  5387. Column() {
  5388. Column() {
  5389. Column() {
  5390. //播放标题
  5391. Column() {
  5392. this.PlayTitle()
  5393. }
  5394. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  5395. .width('100%')
  5396. .margin({ top: 0 })
  5397. .height(PlayConstants.HEIGHT)
  5398. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  5399. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  5400. if (this.showSpeedDialog) {
  5401. this.SpeedDialog()
  5402. }
  5403. Stack() {
  5404. //手势拖动快进
  5405. Column()
  5406. .width(CommonConstants.FULL_PERCENT)
  5407. .height('100%')
  5408. .gesture(
  5409. GestureGroup(GestureMode.Parallel,
  5410. // 长按屏幕倍数播放
  5411. LongPressGesture({ repeat: true })
  5412. .onAction(() => {
  5413. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  5414. this.showSpeedDialog = true;
  5415. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  5416. }
  5417. })
  5418. .onActionEnd(() => {
  5419. this.showSpeedDialog = false;
  5420. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  5421. }),
  5422. //双击屏幕暂停或者播放
  5423. TapGesture({ count: 2 })
  5424. .onAction((event: GestureEvent) => {
  5425. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  5426. ToastUtil.showToast('已暂停')
  5427. }
  5428. this.playOrPause()
  5429. })
  5430. )
  5431. )
  5432. }
  5433. .height('65%')
  5434. Swiper() {
  5435. this.CoverInfo()
  5436. this.PlayerLyrics()
  5437. }
  5438. .onChange((index: number) => {
  5439. this.currentSwiperIndex = index
  5440. })
  5441. .indicator(false)
  5442. // .indicator(this.currentBreakpoint === BreakpointTypeEnum.SM ?
  5443. // new DotIndicator()
  5444. // .top(this.isCoverOpacity()?0:10)
  5445. //
  5446. // .selectedColor($r('app.color.select_swiper'))
  5447. // .color($r('app.color.slider_track')):false
  5448. // )
  5449. .displayCount(new BreakpointType({
  5450. sm: 1,
  5451. md: 2,
  5452. lg: 2,
  5453. xl: 2,
  5454. xxl: 2
  5455. }).getValue(this.currentBreakpoint))
  5456. .clip(false)
  5457. .loop(false)
  5458. .autoPlay(false)
  5459. // .interval(8000)
  5460. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  5461. .height('100%')
  5462. .hitTestBehavior(HitTestMode.Transparent)
  5463. Image($r('app.media.icon_replay'))
  5464. .objectFit(ImageFit.Auto)
  5465. .width('120px')
  5466. .height('120px')
  5467. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  5468. .border({ width: 0 })
  5469. .visibility(Visibility.None)
  5470. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  5471. .onClick(() => {
  5472. this.startPlayOrResumePlay();
  5473. })
  5474. }
  5475. .width(CommonConstants.FULL_PERCENT)
  5476. .height(CommonConstants.FULL_PERCENT)
  5477. .justifyContent(FlexAlign.End)
  5478. }
  5479. .justifyContent(FlexAlign.End)
  5480. .margin({ bottom: 8 })
  5481. }
  5482. // .backgroundImage(this.imageLabelBg)
  5483. .backgroundImage(this.isPuraWP() && this.currentSwiperIndex === 0 ?
  5484. (StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover) : this.imageLabelBg)
  5485. .backgroundImageSize(this.isPuraWP() ? { width: '100%' } : { height: '150%', width: '100%' })
  5486. // .backgroundImagePosition(Alignment.Center)
  5487. .animation({
  5488. duration: 666,
  5489. curve: 'ease-in-out' // 可选动画曲线
  5490. })
  5491. .backgroundBlurStyle(this.isPuraWP() && this.currentSwiperIndex === 0 ? BlurStyle.NONE :
  5492. BlurStyle.BACKGROUND_ULTRA_THICK)
  5493. .hitTestBehavior(HitTestMode.Transparent)
  5494. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  5495. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  5496. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  5497. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  5498. .onClick(() => {
  5499. // this.startAutoHide()
  5500. this.is_auto_hide_progress = false
  5501. setTimeout(() => {
  5502. this.is_auto_hide_progress = true
  5503. }, 6000)
  5504. })
  5505. }
  5506. @State progressValue: number = 0;
  5507. @State currentTime: string = "00:00";
  5508. @State totalTime: string = "00:00";
  5509. @State loadingVisible: Visibility = Visibility.None;
  5510. @State replayVisible: Visibility = Visibility.None;
  5511. @State slideEnable: boolean = false;
  5512. @State aspRatio: number = 0.5;
  5513. @State mContext: object | undefined = undefined;
  5514. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  5515. @State mFirst: boolean = true;
  5516. @State mDestroyPage: boolean = false;
  5517. @State playSpeed: number = 1;
  5518. @State oldSeconds: number = 0;
  5519. @State isSeekTo: boolean = false;
  5520. @State isCurrentTime: boolean = false;
  5521. @State videoWidth: string = '100%';
  5522. @State videoHeight: string = '100%';
  5523. @State initAspectRatio: number = 1;
  5524. @State videoAspectRatio: number = this.initAspectRatio;
  5525. private videoUrl: string = '';
  5526. private last: number = 0;
  5527. @State videoParentAspectRatio: number = this.initAspectRatio;
  5528. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  5529. @State CONTROL_PlayStatus: number = PlayStatus.INIT;
  5530. @State PROGRESS_MAX_VALUE: number = 100;
  5531. @State updateProgressTimer: number = 0;
  5532. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  5533. @State name: string = '';
  5534. // @State loop: boolean = false;
  5535. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  5536. @State multiple: string = '1.0X';
  5537. xcomponentController: XComponentController = new XComponentController()
  5538. private panOptionBright: PanGestureOptions =
  5539. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  5540. private panOptionVolume: PanGestureOptions =
  5541. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  5542. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  5543. //手势的音量控制和亮度控制
  5544. private positionX: number = PlayConstants.POSITION_X;
  5545. private positionY: number = PlayConstants.POSITION_Y;
  5546. private windowClass: window.Window = globalThis.windowClass
  5547. @State volume: number = 0.3;
  5548. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  5549. @State bright: number = PlayConstants.BRIGHT;
  5550. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  5551. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  5552. @State screenWidth: number = 0
  5553. @State screenHeight: number = 0
  5554. @State statusBarHeight: number = 0
  5555. @State isYesFull: boolean = false
  5556. private seekValue: number = 0
  5557. @State isVideoLock: boolean = false; // Whether the video playback is locked
  5558. eventHub = getContext().eventHub;
  5559. //投播组件
  5560. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  5561. private castController: avSession.AVCastController | undefined = undefined;
  5562. @State isCastPlaying: boolean = false;
  5563. @State currentTime2: number = 0;
  5564. @State currentStringTime: string = '00:00';
  5565. @State duration: number = 0;
  5566. @State isReady: boolean = false;
  5567. @State durationTime: number = 0;
  5568. @State durationStringTime: string = '00:00';
  5569. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  5570. // @State isPlaying: boolean = false;
  5571. private castSeek: boolean = false;
  5572. private castItem: avSession.AVQueueItem | undefined = undefined;
  5573. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  5574. @State imageLabel: PixelMap | Resource = CommonConstants.musicBgList[0];
  5575. @State imageLabelBg: PixelMap | Resource = CommonConstants.musicBgList[0];
  5576. @State rotateAngle2: number = 0
  5577. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  5578. @State cover: string | undefined = '';
  5579. @State artist: string | undefined = ''
  5580. // 1.初始化controller
  5581. private lyricController: LyricController = new LyricController()
  5582. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  5583. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  5584. private parser = new LyricParser()
  5585. @State randomColor: string = 'rgb(0,0,0)'
  5586. @State randomShakenX: number = 0
  5587. @State randomShakenY: number = 0
  5588. @State lyricTextSize: number = 24
  5589. @State lyricContent: string = ''
  5590. @State isDebug: boolean = false
  5591. @State isHightLightCenter: boolean = true
  5592. /**
  5593. * 初始化歌词加载与展示逻辑
  5594. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  5595. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  5596. * @param isApi2 是否使用API2获取歌词(可选)
  5597. *
  5598. * 主要流程:
  5599. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  5600. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  5601. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  5602. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  5603. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  5604. * 6. 解析失败或读取失败时,清空歌词显示。
  5605. *
  5606. * 注意事项:
  5607. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  5608. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  5609. * - 歌词内容解析后通过lyricController驱动UI渲染。
  5610. */
  5611. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean) {
  5612. if (StrUtil.isEmpty(lyricPath)) {
  5613. return
  5614. }
  5615. this.initPipLyricSetting()
  5616. this.lyricControllerSingle
  5617. .setTextSize(15)
  5618. .setCacheSize(4)
  5619. .setTextColor("#FFFFFF")
  5620. .setHighlightColor("#FFFFFF")
  5621. .setHighlightScale(1.2)
  5622. .setEmptyHint("")
  5623. .setAlignMode('center')
  5624. .setAnimationDuration(500)
  5625. .setSingleLine(true)
  5626. this.lyricContent = ''
  5627. this.lyricController
  5628. .setTextSize(this.currentLyricSize)
  5629. .setCacheSize(4)
  5630. .setTextColor("#DDDDDD")
  5631. .setHighlightColor("#FFFFFF")
  5632. .setEmptyHint("")
  5633. .setAnimationDuration(1000)
  5634. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  5635. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  5636. this.setBlurDegree(this.blurDegree, false)
  5637. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  5638. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  5639. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  5640. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  5641. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  5642. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  5643. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  5644. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  5645. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  5646. this.lyricController.setTextWeight(this.lyricTextWeight)
  5647. this.showSingleLyric = false
  5648. this.timeOffset = 0
  5649. this.lyricController.setLyric(null)
  5650. this.lyricControllerSingle.setLyric(null)
  5651. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  5652. console.log("onecold lyricPath =" + lyricPath)
  5653. let neiqianLrc = ''
  5654. let lyContent = this.currentSong?.lyricContent
  5655. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  5656. neiqianLrc = lyContent
  5657. }else{
  5658. neiqianLrc = LrcParser.getLyrics(this.videoUrl); //获取内嵌歌词
  5659. }
  5660. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast) {
  5661. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  5662. //赋值给this.lyricContent,播控中心才可以显示歌词
  5663. this.lyricContent = neiqianLrc
  5664. // 将文件内容按行分割成字符串数组
  5665. let lines = neiqianLrc.split('\n').map(line => line.trim());
  5666. // 3.解析歌词
  5667. let lyric = this.parser.parse(lines);
  5668. // 4.设置歌词
  5669. this.lyricController.setLyric(lyric);
  5670. this.lyricControllerXF.setLyric(lyric)
  5671. this.lyricControllerSingle.setLyric(lyric)
  5672. return
  5673. }
  5674. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  5675. && !Utility.isVideoByExtension(this.videoUrl))) {
  5676. if (this.currentSong !== undefined) {
  5677. // ToastUtil.showShort('正在为你搜索在线歌词!')
  5678. //判断是不是赞助会员,是会员的话才开启歌词功能
  5679. // if (!this.isDebug) {
  5680. // if (!Utility.isNoble()) {
  5681. // LogUtil.debug("onecold 不是赞助会员")
  5682. // return
  5683. // }
  5684. // if(!Utility.isPassInstallTime(33)){
  5685. // LogUtil.debug("onecold not pass time")
  5686. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  5687. // return
  5688. // }
  5689. // }
  5690. let artist = this.currentSong?.artist
  5691. if (artist === undefined) {
  5692. artist = ''
  5693. }
  5694. if (isApi2 === undefined) {
  5695. isApi2 = false
  5696. }
  5697. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  5698. // LogUtil.debug("onecold res =" + res)
  5699. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  5700. if (StrUtil.isNotEmpty(res)) {
  5701. this.lyricContent = res
  5702. let lines = res.split('\n').map(line => line.trim());
  5703. // 3.解析歌词
  5704. let lyric = this.parser.parse(lines);
  5705. // 4.设置歌词
  5706. this.lyricController.setLyric(lyric);
  5707. this.lyricControllerXF.setLyric(lyric)
  5708. this.lyricControllerSingle.setLyric(lyric)
  5709. this.showSingleLyric = true
  5710. // 4.保存歌词文件lyric到本地
  5711. this.saveDataToFile(res, jiaMilyricPath, true)
  5712. } else {
  5713. this.lyricController.setLyric(null)
  5714. this.lyricControllerXF.setLyric(null)
  5715. this.lyricControllerSingle.setLyric(null)
  5716. if (isOnLineAndToast) {
  5717. ToastUtil.showShort('未获取到歌词!')
  5718. }
  5719. }
  5720. } else {
  5721. this.lyricController.setLyric(null)
  5722. this.lyricControllerXF.setLyric(null)
  5723. this.lyricControllerSingle.setLyric(null)
  5724. if (isOnLineAndToast) {
  5725. ToastUtil.showShort('未获取到歌词!')
  5726. }
  5727. }
  5728. })
  5729. } else {
  5730. this.lyricController.setLyric(null)
  5731. this.lyricControllerXF.setLyric(null)
  5732. this.lyricControllerSingle.setLyric(null)
  5733. if (isOnLineAndToast) {
  5734. ToastUtil.showShort('未获取到歌词!')
  5735. }
  5736. }
  5737. return
  5738. }
  5739. try {
  5740. let isJiaMi = false;
  5741. let realLyricPath = lyricPath
  5742. if (FileUtil.accessSync(jiaMilyricPath)) {
  5743. isJiaMi = true
  5744. realLyricPath = jiaMilyricPath
  5745. console.info("onecold 找到加密本地歌词 ");
  5746. } else {
  5747. isJiaMi = false
  5748. realLyricPath = lyricPath
  5749. console.info("onecold 找到本地歌词 ");
  5750. }
  5751. // 3.读取文件内容并指定编码为 UTF-8
  5752. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_WRITE);
  5753. let arrayBuffer = new ArrayBuffer(4096);
  5754. fs.read(file.fd, arrayBuffer)
  5755. .then((readLen: number) => {
  5756. console.info("read file data succeed");
  5757. // let buf = buffer.from(arrayBuffer, 0, readLen);
  5758. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  5759. // 检查 buf 是否为空
  5760. if (buf.length === 0) {
  5761. throw new Error("Buffer is empty after reading the file");
  5762. }
  5763. try {
  5764. // 检测文件编码
  5765. // let detectedEncoding = chardet.detect(buf);
  5766. // console.info("onecoldT Detected encoding: " + detectedEncoding);
  5767. let detectedEncoding = this.detect(arrayBuffer)
  5768. console.info("onecoldT Detected encoding: " + detectedEncoding);
  5769. // 使用检测到的编码解码,解决中文乱码问题
  5770. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  5771. console.info("onecoldT Detected textDecoder: " + textDecoder);
  5772. let fileContent = textDecoder.decode(buf);
  5773. console.info(`onecoldT The content of file1: ${fileContent}`);
  5774. //解密
  5775. if (isJiaMi) {
  5776. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  5777. }
  5778. console.info(`onecold The content of file2: ${fileContent}`);
  5779. this.lyricContent = fileContent
  5780. // 将文件内容按行分割成字符串数组
  5781. let lines = fileContent.split('\n').map(line => line.trim());
  5782. console.info(`onecold The content of file: ${fileContent}`);
  5783. // 3.解析歌词
  5784. let lyric = this.parser.parse(lines);
  5785. // 4.设置歌词
  5786. this.lyricController.setLyric(lyric);
  5787. this.lyricControllerXF.setLyric(lyric)
  5788. this.lyricControllerSingle.setLyric(lyric)
  5789. this.showSingleLyric = true
  5790. console.info(`The content of file: ${fileContent}`);
  5791. } catch (chardetError) {
  5792. console.error("chardet.detect failed with error: " + chardetError.message);
  5793. this.lyricController.setLyric(null);
  5794. this.lyricControllerXF.setLyric(null)
  5795. this.lyricControllerSingle.setLyric(null)
  5796. }
  5797. })
  5798. .catch((err: BusinessError) => {
  5799. this.lyricController.setLyric(null)
  5800. this.lyricControllerXF.setLyric(null)
  5801. this.lyricControllerSingle.setLyric(null)
  5802. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  5803. })
  5804. .catch((err: Error) => {
  5805. this.lyricController.setLyric(null)
  5806. this.lyricControllerXF.setLyric(null)
  5807. this.lyricControllerSingle.setLyric(null)
  5808. console.error("read file 2 data failed with error message: " + err.message);
  5809. })
  5810. .finally(() => {
  5811. fs.closeSync(file);
  5812. });
  5813. } catch (error) {
  5814. this.lyricController.setLyric(null)
  5815. this.lyricControllerSingle.setLyric(null)
  5816. this.lyricControllerXF.setLyric(null)
  5817. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  5818. }
  5819. }
  5820. detect(data: ArrayBuffer): string {
  5821. //创建检测对象
  5822. let detector: UniversalDetector = new UniversalDetector();
  5823. // 传入检测数据并实时判断编码格式
  5824. detector.handleData(data, 0, data.byteLength);
  5825. // 标记检测数据 读取结束
  5826. detector.dataEnd();
  5827. // 获取检测结果
  5828. let detected: string = detector.getDetectedCharset();
  5829. // 释放资源
  5830. detector.reset();
  5831. return detected;
  5832. }
  5833. //初始化悬浮歌词的自定义设置
  5834. initPipLyricSetting() {
  5835. this.lyricControllerXF
  5836. .setTextSize(this.currentLyricSize)
  5837. .setCacheSize(4)
  5838. .setTextColor("#DDDDDD")
  5839. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  5840. .setEmptyHint("")
  5841. .setAnimationDuration(1000)
  5842. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  5843. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  5844. this.setBlurDegree(this.blurDegreePip, true)
  5845. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  5846. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  5847. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  5848. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  5849. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  5850. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  5851. this.lyricControllerXF.setHightLightCenter(true)
  5852. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  5853. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  5854. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  5855. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  5856. if (this.pipBgIndex === 0) {
  5857. if (this.cover) {
  5858. this.pipBg = this.cover
  5859. } else {
  5860. this.pipBg = this.imageColor
  5861. }
  5862. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  5863. }
  5864. }
  5865. //根据item返回歌词内容
  5866. async getLyricContent(item: VideoItem): Promise<string> {
  5867. try {
  5868. let filePath = item.filePath;
  5869. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  5870. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  5871. let isJiaMi = false;
  5872. let realLyricPath = lyricPath;
  5873. if (FileUtil.accessSync(jiaMilyricPath)) {
  5874. isJiaMi = true;
  5875. realLyricPath = jiaMilyricPath;
  5876. console.info("onecold 找到加密本地歌词");
  5877. } else {
  5878. console.info("onecold 找到本地歌词");
  5879. }
  5880. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_WRITE);
  5881. let arrayBuffer = new ArrayBuffer(4096);
  5882. const readLen = await fs.read(file.fd, arrayBuffer);
  5883. console.info("read file data succeed");
  5884. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  5885. if (buf.length === 0) {
  5886. throw new Error("Buffer is empty after reading the file");
  5887. }
  5888. // let detectedEncoding = chardet.detect(buf);
  5889. let detectedEncoding = this.detect(arrayBuffer)
  5890. console.info("Detected encoding: " + detectedEncoding);
  5891. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  5892. let fileContent = textDecoder.decode(buf);
  5893. console.info(`onecold The content of file1: ${fileContent}`);
  5894. if (isJiaMi) {
  5895. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  5896. }
  5897. console.info(`onecold The content of file2: ${fileContent}`);
  5898. fs.closeSync(file);
  5899. return fileContent;
  5900. } catch (error) {
  5901. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  5902. return '';
  5903. }
  5904. }
  5905. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  5906. if (StrUtil.isEmpty(filePath)) {
  5907. return
  5908. }
  5909. try {
  5910. //将content进行加密
  5911. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  5912. let lyricContent = ''
  5913. if (isJiaMi) {
  5914. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  5915. } else {
  5916. lyricContent = content
  5917. }
  5918. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  5919. // 清空文件内容
  5920. await fileIo.truncate(file.fd, 0);
  5921. await fileIo.write(file.fd, lyricContent);
  5922. await fileIo.close(file);
  5923. console.log('onecold lyric file Data saved successfully.');
  5924. } catch (error) {
  5925. console.error('onecold lyric file Failed to save data:', error);
  5926. }
  5927. }
  5928. /**
  5929. * Get largest proportion color of an image.
  5930. */
  5931. getImageColor() {
  5932. if (!this.context) {
  5933. return;
  5934. }
  5935. let bg = Utility.getMusisBg()
  5936. this.imageLabel = bg
  5937. ColorConversion.setSysBarLightBackground(true);
  5938. this.context.resourceManager.getMediaContent(bg)
  5939. .then((value: Uint8Array) => {
  5940. let buffer = value.buffer as ArrayBuffer;
  5941. image.createImageSource(buffer).createPixelMap().then((pixelMap) => {
  5942. effectKit.createColorPicker(pixelMap, (error, colorPicker) => {
  5943. if (error) {
  5944. Logger.error('Failed to create color picker.');
  5945. } else {
  5946. let color = colorPicker.getLargestProportionColor();
  5947. let colorArr = ColorConversion.dealColor(color.red, color.green, color.blue);
  5948. this.imageColor = `rgba(${colorArr[0]}, ${colorArr[1]}, ${colorArr[2]}, 1)`;
  5949. }
  5950. })
  5951. let headFilter = effectKit.createEffect(pixelMap);
  5952. if (headFilter !== null) {
  5953. headFilter.blur(15);
  5954. headFilter.getEffectPixelMap().then((value) => {
  5955. this.imageLabelBg = value;
  5956. })
  5957. }
  5958. })
  5959. .catch((error: BusinessError) => {
  5960. Logger.error(`${error.code} + ${error.message}`)
  5961. })
  5962. })
  5963. .catch((error: BusinessError) => {
  5964. Logger.error(`${error.code} + ${error.message}`)
  5965. })
  5966. }
  5967. setImageColor(cover: string) {
  5968. if (!this.context) {
  5969. return;
  5970. }
  5971. if (cover === undefined) {
  5972. return;
  5973. }
  5974. ImageUtil.imagePathToPixelMap(cover).then((value) => {
  5975. let headFilter = effectKit.createEffect(value);
  5976. if (headFilter !== null) {
  5977. headFilter.blur(15);
  5978. headFilter.getEffectPixelMap().then((value) => {
  5979. this.imageLabelBg = value;
  5980. })
  5981. }
  5982. }).catch((error: BusinessError) => {
  5983. Logger.error(`${error.code} + ${error.message}`)
  5984. })
  5985. }
  5986. setImageColor2(cover: string) {
  5987. if (!this.context) {
  5988. return;
  5989. }
  5990. if (cover === undefined) {
  5991. return;
  5992. }
  5993. LogUtils.getInstance().LOGI("setImageColor2--> cover ==" + cover);
  5994. ImageUtils.getImageDealData(getContext(this), cover, this.videoUrl).then((data) => {
  5995. this.imageColor = data.imageColor;
  5996. if (data.blurPixelMap) {
  5997. this.imageLabelBg = data.blurPixelMap;
  5998. }
  5999. })
  6000. }
  6001. // 定义开始旋转的方法
  6002. // 定时器用于一百毫秒执行一次旋转角度
  6003. @State timer: number = 0
  6004. @State rotateAngle: number = 0
  6005. //封面旋转动画
  6006. animationRoFun() {
  6007. if (this.isPlaying && !this.isCoverRectangle) {
  6008. this.timer = setInterval(() => {
  6009. this.rotateAngle += 1
  6010. }, 100)
  6011. this.startRotation()
  6012. } else {
  6013. clearInterval(this.timer)
  6014. this.stopRotation()
  6015. }
  6016. }
  6017. // 定义开始旋转的方法
  6018. startRotation() {
  6019. if (this.isPlaying) {
  6020. animateTo({
  6021. duration: 777,
  6022. iterations: 1,
  6023. curve: Curve.Linear
  6024. }, () => {
  6025. this.rotateAngle2 = 0
  6026. })
  6027. }
  6028. }
  6029. // 回调,暂停和播放按钮回调,下一首和上一首
  6030. playChange() {
  6031. // if(this.isCoverRectangle){
  6032. // return
  6033. // }
  6034. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  6035. this.setIsPlaying(true)
  6036. this.animationState = AnimationStatus.Running
  6037. } else {
  6038. this.setIsPlaying(false)
  6039. this.animationState = AnimationStatus.Paused
  6040. }
  6041. }
  6042. // 定义停止旋转的方法
  6043. stopRotation() {
  6044. if (this.isCoverRectangle) {
  6045. this.rotateAngle = 0
  6046. } else {
  6047. //唱针以左上角为点选择逆时针40度
  6048. animateTo({
  6049. duration: 1000,
  6050. curve: Curve.Linear,
  6051. iterations: 1,
  6052. }, () => {
  6053. this.rotateAngle2 = -40;
  6054. });
  6055. }
  6056. }
  6057. @Builder
  6058. private LyricsTopItem() {
  6059. Row() {
  6060. Stack() {
  6061. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  6062. .height(55)
  6063. .width(55)
  6064. .alt(this.imageLabel)
  6065. .borderRadius(8)
  6066. .clickEffect({ level: ClickEffectLevel.HEAVY })
  6067. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  6068. }
  6069. .width('18%')
  6070. Column() {
  6071. Column() {
  6072. Text(this.name)
  6073. .fontSize(16)
  6074. .maxLines(1)
  6075. .fontWeight(FontWeight.Bolder)
  6076. .fontColor(this.currentLyricColor)
  6077. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  6078. Row() {
  6079. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  6080. .fontSize(13)
  6081. .fontWeight(FontWeight.Bold)
  6082. .padding({ top: 8 })
  6083. .fontColor(this.currentLyricColor)
  6084. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  6085. Blank()
  6086. }
  6087. }
  6088. .height('100%')
  6089. .width('100%')
  6090. .justifyContent(FlexAlign.Center)
  6091. .alignItems(HorizontalAlign.Start)
  6092. }
  6093. .height('100%')
  6094. .width('65%')
  6095. Column() {
  6096. Image($r('app.media.lyric'))
  6097. .width(28)
  6098. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6099. .margin({ right: 30 })
  6100. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6101. .onClick(() => {
  6102. this.isLyricSetting = !this.isLyricSetting;
  6103. })
  6104. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  6105. height: this.isCoverOpacity() ? '95%' : '88%',
  6106. dragBar: true,
  6107. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6108. showClose: true,
  6109. blurStyle: BlurStyle.Thin,
  6110. backgroundColor: Color.Transparent,
  6111. // title: { title: $r('app.string.lyric_setting') }
  6112. })
  6113. }
  6114. .width('18%')
  6115. }
  6116. .width('82%')
  6117. .height(58)
  6118. .justifyContent(FlexAlign.SpaceBetween)
  6119. }
  6120. //歌词显示
  6121. @Builder
  6122. PlayerLyrics() {
  6123. Column() {
  6124. Column() {
  6125. this.LyricsTopItem()
  6126. }
  6127. .height(this.isPuraWP() ? 15 : 58)
  6128. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  6129. Visibility.None : Visibility.Visible)
  6130. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  6131. .width("100%")
  6132. Column() {
  6133. LyricView2({
  6134. controller: this.lyricController,
  6135. enableSeek: true,
  6136. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  6137. seekLineColor: "#80ffffff", // 滑动定位线颜色
  6138. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  6139. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  6140. if (!this.isPlaying) {
  6141. this.startPlayOrResumePlay()
  6142. } else {
  6143. this.isSeekTo = true;
  6144. this.mDestroyPage = false;
  6145. this.showLoadIng();
  6146. this.seekTo(position + "");
  6147. this.isSeekTo = false;
  6148. }
  6149. return true
  6150. }
  6151. })
  6152. .width("100%")
  6153. .layoutWeight(1)
  6154. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  6155. if (this.isPhoneLan()) {
  6156. Column() {
  6157. this.playCenterView()
  6158. }
  6159. .margin({ bottom: 20, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  6160. }
  6161. }
  6162. .position({
  6163. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  6164. (this.isPuraWP() ? 58 : 99)
  6165. })
  6166. .justifyContent(FlexAlign.Center)
  6167. .height(this.isCoverOpacity() ? '95%' : '80%')
  6168. }
  6169. }
  6170. @Builder
  6171. SingleLyricView() {
  6172. Column() {
  6173. Column() {
  6174. LyricView2({
  6175. controller: this.lyricControllerSingle,
  6176. enableSeek: false,
  6177. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  6178. seekLineColor: "#80ffffff", // 滑动定位线颜色
  6179. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  6180. })
  6181. }
  6182. .height(66)
  6183. .margin({ bottom: 20 })
  6184. }
  6185. }
  6186. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  6187. @Builder
  6188. BottomControl() {
  6189. Column() {
  6190. //播放 暂停,下一首,上一首
  6191. this.playCenterView()
  6192. //播放进度条
  6193. this.playProgressView()
  6194. }
  6195. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 100) }) // 将 固定在底部
  6196. }
  6197. //播放控制上一首 下一首 暂停和播放
  6198. @Builder
  6199. playCenterView() {
  6200. Row() {
  6201. Row({ space: 20 }) {
  6202. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6203. //更多功能
  6204. Image($r('app.media.menu'))
  6205. .width(24)
  6206. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  6207. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  6208. height: this.isCoverOpacity() ? '95%' : '93%',
  6209. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6210. dragBar: true,
  6211. showClose: true,
  6212. blurStyle: BlurStyle.Thin,
  6213. backgroundColor: Color.Transparent,
  6214. })
  6215. }
  6216. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6217. .backgroundColor(Color.Transparent)
  6218. .onClick(() => {
  6219. this.isShowMoreView = !this.isShowMoreView;
  6220. })
  6221. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6222. Image($r('app.media.ic_previous'))
  6223. .width(33)
  6224. .clickEffect({ level: ClickEffectLevel.HEAVY })
  6225. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6226. }
  6227. .onClick(async () => {
  6228. this.playPrevious()
  6229. })
  6230. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6231. .backgroundColor(Color.Transparent)
  6232. .margin({ left: 5 })
  6233. }
  6234. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6235. Column() {
  6236. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  6237. (this.isCircleBtn ? $r('app.media.hm_pause') : $r('app.media.ic_public_play'))
  6238. : (this.isCircleBtn ? $r('app.media.hm_play2') : $r('app.media.ic_public_pause')))
  6239. .width(this.isPhoneLan() ? 48 : 60)
  6240. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6241. .fillColor(Color.White)
  6242. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6243. .onClick(async () => {
  6244. this.playOrPause()
  6245. })
  6246. }
  6247. }
  6248. .backgroundColor(Color.Transparent)
  6249. .layoutWeight(1)
  6250. .margin({ left: 38, right: 38 })
  6251. Row({ space: 20 }) {
  6252. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6253. Image($r('app.media.ic_next'))
  6254. .width(33)
  6255. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6256. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6257. .onClick(() => {
  6258. this.playNext();
  6259. })
  6260. }
  6261. .backgroundColor(Color.Transparent)
  6262. .margin({ right: 5 })
  6263. .width(33)
  6264. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6265. //添加或取消收藏
  6266. Image(Utility.getIsFav(this.favList, this.currentSong) ?
  6267. $r('app.media.add_fac_light') : $r('app.media.add_fac'))
  6268. .width(24)
  6269. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  6270. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6271. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6272. .onClick(async () => {
  6273. if (this.currentSong) {
  6274. this.doFav(this.currentSong)
  6275. }
  6276. })
  6277. }
  6278. .backgroundColor(Color.Transparent)
  6279. .width(24)
  6280. }
  6281. // .margin({ left: 5 })
  6282. }
  6283. .width('100%')
  6284. .margin({ left: 10, right: 10, bottom: this.isCoverOpacity() ? 0 : 20 })
  6285. .justifyContent(FlexAlign.Center)
  6286. }
  6287. //播放进度条
  6288. @Builder
  6289. playProgressView() {
  6290. Row() {
  6291. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6292. Column() {
  6293. if (this.playType === 0) {
  6294. Image($r('app.media.loop'))
  6295. .width($r('app.float.control_image_width'))
  6296. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6297. } else if (this.playType === 1) {
  6298. Image($r('app.media.single'))
  6299. .width($r('app.float.control_image_width'))
  6300. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6301. } else if (this.playType === 2) {
  6302. Image($r('app.media.normal_play'))
  6303. .width($r('app.float.control_image_width'))
  6304. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6305. } else if (this.playType === 3) {
  6306. Image($r('app.media.random'))
  6307. .width($r('app.float.control_image_width'))
  6308. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6309. }
  6310. }
  6311. }
  6312. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  6313. .animation({
  6314. duration: 666,
  6315. curve: 'ease-in-out' // 可选动画曲线
  6316. })
  6317. .backgroundColor(Color.Transparent)
  6318. .margin({ left: 20, right: 10 })
  6319. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6320. .onClick(async () => {
  6321. this.setLoopMode()
  6322. })
  6323. Text(this.currentTime)
  6324. .fontSize($r('app.float.slider_font_size'))
  6325. .fontColor(Color.White)
  6326. .margin(3)
  6327. Slider({
  6328. value: this.progressValue,
  6329. min: 0,
  6330. max: this.PROGRESS_MAX_VALUE,
  6331. step: 1,
  6332. style: SliderStyle.OutSet
  6333. })
  6334. .width('600px')
  6335. .blockColor('rgba(255,255,255,1)')
  6336. .trackColor('rgba(255,255,255,0.3)')
  6337. .selectedColor(Color.White)
  6338. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  6339. .layoutWeight(1)
  6340. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  6341. .showSteps(false)
  6342. .showTips(true)
  6343. .enabled(this.slideEnable)
  6344. .onChange((value: number, mode: SliderChangeMode) => {
  6345. // if (mode == 2) {
  6346. this.isSeekTo = true;
  6347. this.mDestroyPage = false;
  6348. this.showLoadIng();
  6349. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  6350. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  6351. this.seekTo(seekValue + "");
  6352. // this.setProgress()
  6353. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  6354. this.isSeekTo = false;
  6355. // }
  6356. })
  6357. Text(this.totalTime)
  6358. .fontSize($r('app.float.slider_font_size'))
  6359. .fontColor(Color.White)
  6360. .margin(3)
  6361. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  6362. //播放列表
  6363. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6364. Image($r('app.media.hm_playlist'))
  6365. .width($r('app.float.control_image_width'))
  6366. .fillColor(Color.White)
  6367. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6368. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  6369. height: '95%',
  6370. dragBar: true,
  6371. showClose: true,
  6372. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6373. blurStyle: BlurStyle.Thin,
  6374. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  6375. title: {
  6376. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  6377. + `(${this.songList.length}首)`
  6378. }
  6379. })
  6380. }
  6381. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  6382. .animation({
  6383. duration: 666,
  6384. curve: 'ease-in-out' // 可选动画曲线
  6385. })
  6386. .backgroundColor(Color.Transparent)
  6387. .margin({ right: 20, left: 10 })
  6388. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6389. .onClick(() => {
  6390. this.isShowSheetView = !this.isShowSheetView;
  6391. if (this.isPlayListBgGrass) {
  6392. this.isFrontWhite = true
  6393. } else {
  6394. this.isFrontWhite = false
  6395. }
  6396. setTimeout(() => {
  6397. this.playListScroller.scrollToIndex(this.curIndex, true, ScrollAlign.CENTER)
  6398. }, 123)
  6399. })
  6400. }
  6401. //x5的竖屏模式需要99%
  6402. .width(this.isPhonePortrait() ? '93.4%'
  6403. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  6404. .height(this.isPhoneLan() ? 25 : 33)
  6405. .animation({
  6406. duration: 666,
  6407. curve: 'ease-in-out' // 可选动画曲线
  6408. })
  6409. }
  6410. isBigScreen() {
  6411. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  6412. return true
  6413. }
  6414. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  6415. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  6416. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  6417. return false
  6418. } else {
  6419. return true
  6420. }
  6421. return false
  6422. }
  6423. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  6424. @State isCoverRectangle: boolean = false
  6425. @State isCoverTop: boolean = true
  6426. // 添加控制缩放的状态变量
  6427. @State scaleValueImage: number = 1
  6428. @Builder
  6429. CoverInfo() {
  6430. Column() {
  6431. //如果是方形,判断是不是封面在顶部,如果不是顶部,显示musicNameInfo, 如果是圆形显示musicNameInfo
  6432. if (this.isCoverRectangle) {
  6433. if (!this.isCoverTop) {
  6434. this.musicNameInfo(false)
  6435. }
  6436. } else {
  6437. this.musicNameInfo(false)
  6438. }
  6439. Stack() {
  6440. // 唱片旋转效果
  6441. Image($r('app.media.ic_music_disc'))
  6442. .width(245)
  6443. .height(245)
  6444. .margin({ right: 20, left: 20 })
  6445. .aspectRatio(1)
  6446. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  6447. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  6448. .borderRadius('100%')
  6449. .align(Alignment.Center)
  6450. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  6451. .rotate({
  6452. angle: this.rotateAngle,
  6453. centerX: "50%",
  6454. centerY: "50%",
  6455. })
  6456. .animation({
  6457. duration: 100,
  6458. curve: Curve.Linear
  6459. })
  6460. .shadow({
  6461. radius: 30,
  6462. color: this.randomColor
  6463. })
  6464. Column() {
  6465. if (this.isCoverTop && !this.isCoverOpacity() && this.isCoverRectangle) {
  6466. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)// .height(this.isCoverOpacity() ? 250 : this.isCoverRectangle ? 320 : 162)
  6467. .width(this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '86%')
  6468. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  6469. .alt(this.imageLabel)
  6470. .margin({ right: 8, left: 8, top: 8 })
  6471. .aspectRatio(1)
  6472. .opacity(this.opacityValueImage)
  6473. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  6474. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  6475. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  6476. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  6477. .align(Alignment.Center)//
  6478. .clip(true)
  6479. .rotate({
  6480. x: 0,
  6481. y: 0,
  6482. z: 1,
  6483. angle: this.rotateAngle
  6484. })
  6485. .onClick(() => {
  6486. this.getImageColor()
  6487. })
  6488. this.musicNameInfo(false)
  6489. } else {
  6490. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  6491. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:220):(this.isCoverOpacity() ? 250 : this.isCoverRectangle ? 320 : 162))
  6492. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  6493. .alt(this.imageLabel)
  6494. .margin({ right: 20, left: 20 })
  6495. .aspectRatio(1)
  6496. .opacity(this.opacityValueImage)
  6497. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  6498. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  6499. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  6500. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  6501. .align(Alignment.Center)//
  6502. .clip(true)
  6503. .rotate({
  6504. x: 0,
  6505. y: 0,
  6506. z: 1,
  6507. angle: this.rotateAngle
  6508. })
  6509. .onClick(() => {
  6510. this.getImageColor()
  6511. })
  6512. if (this.isPhoneLan()) {
  6513. Text(this.name)
  6514. .fontSize(18)
  6515. .fontWeight(FontWeight.Bold)
  6516. .margin({ top: 13 })
  6517. .textOverflow({ overflow: TextOverflow.Ellipsis })
  6518. .maxLines(1)
  6519. .width('99%')
  6520. .textAlign(TextAlign.Center)
  6521. .fontColor(Color.White)
  6522. }
  6523. }
  6524. }
  6525. // 唱针以左上角为点选择逆时针40度
  6526. Image($r('app.media.ic_music_cover_hand'))
  6527. .height(130)
  6528. .margin({ bottom: 220, top: 0 })
  6529. .align(Alignment.Top)
  6530. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  6531. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  6532. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  6533. Column({ space: 8 }) {
  6534. Text(this.name)
  6535. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  6536. .fontWeight(FontWeight.Bold)
  6537. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6538. .maxLines(1)
  6539. .width('48%')
  6540. .textAlign(TextAlign.Center)
  6541. .fontColor(Color.White)
  6542. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  6543. Text(this.artist)
  6544. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  6545. .fontColor(Color.White)
  6546. .fontWeight(FontWeight.Bold)
  6547. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  6548. }
  6549. .justifyContent(FlexAlign.Start)
  6550. .zIndex(1)
  6551. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  6552. }
  6553. .margin({
  6554. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  6555. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  6556. top: this.isCoverOpacity() ? 0 : 20
  6557. })
  6558. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  6559. this.SingleLyricView()
  6560. }
  6561. if (this.isPhoneLan()) {
  6562. Column() {
  6563. this.playProgressView()
  6564. }
  6565. .position({ left: 40, bottom: 48 })
  6566. } else {
  6567. this.BottomControl()
  6568. }
  6569. }
  6570. .width(CommonConstants.FULL_PERCENT)
  6571. .clip(true)
  6572. }
  6573. @Builder
  6574. private musicNameInfo(isHidden: boolean) {
  6575. Column({ space: 8 }) {
  6576. Text(this.name)
  6577. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22)
  6578. .fontWeight(FontWeight.Bold)
  6579. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6580. .maxLines(1)
  6581. .width('99%')
  6582. .textAlign(TextAlign.Center)
  6583. .fontColor(Color.White)
  6584. Text(this.artist + ' ' + this.currentSong?.album)
  6585. .fontSize(this.isCoverOpacity() ? 12 : 15)
  6586. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6587. .fontColor(Color.White)
  6588. .textAlign(TextAlign.Center)
  6589. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  6590. .width('99%')
  6591. .maxLines(1)
  6592. }
  6593. .margin({ top: this.isCoverOpacity() ? 20 : isHidden ? 40 : 20 })
  6594. .zIndex(1)
  6595. // .opacity(this.opacityValueImage)
  6596. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  6597. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  6598. }
  6599. @Builder
  6600. private PlayTitle() {
  6601. Row() {
  6602. Row() {
  6603. Image($r('app.media.ic_back_down'))
  6604. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  6605. .hitTestBehavior(HitTestMode.Transparent)
  6606. Text(this.name + ' ' + this.artist)
  6607. .fontColor(Color.White)
  6608. .fontSize($r('app.float.title_font_size'))
  6609. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6610. .maxLines(1)
  6611. .visibility(Visibility.None)
  6612. .margin({ left: 2, right: 30 })
  6613. }
  6614. .layoutWeight(1)
  6615. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6616. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  6617. .onClick(() => {
  6618. this.isShowPlay = false;
  6619. })
  6620. Column() {
  6621. AVCastPicker({
  6622. normalColor: Color.White,
  6623. onStateChange: this.onStateVastChange
  6624. })
  6625. .width(24)
  6626. .height(24)
  6627. }
  6628. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  6629. }
  6630. .width(PlayConstants.ROW_WIDTH)
  6631. }
  6632. @Builder
  6633. lyricSettingSheet(isPip: boolean) {
  6634. Scroll() {
  6635. this.lyricSetting(isPip)
  6636. }
  6637. .width('100%')
  6638. .height('100%')
  6639. }
  6640. @Builder
  6641. lyricSetting(isPip: boolean) {
  6642. Column() {
  6643. // 时间调节模块
  6644. if (!isPip) {
  6645. this.BuildTimeControls()
  6646. }
  6647. // 字号控制模块
  6648. this.BuildFontControls(isPip)
  6649. }
  6650. }
  6651. // 歌词时间偏移状态
  6652. @State timeOffset: number = 0.0
  6653. @State currentLyricColor: string = '#FFFFFF'
  6654. @State currentLyricColorPip: string = '#FFFFFF'
  6655. @State currentHighLightLyricColor: string = '#FF4081'
  6656. @State currentHighLightLyricColorPip: string = '#FF4081'
  6657. // 歌词字号状态
  6658. @State currentLyricSize: number = 20
  6659. @State currentLyricSizePip: number = 20
  6660. // 高亮歌词放大倍数
  6661. @State currentHightLyricSize: number = 1.2
  6662. @State currentHightLyricSizePip: number = 1.2
  6663. @State currentLyricLineSpace: number = 10
  6664. @State currentLyricLineSpacePip: number = 10
  6665. @State currentLyricAlignMode: number = 1
  6666. @State currentLyricAlignModePip: number = 1
  6667. @State blurDegree: number = 2
  6668. @State blurDegreePip: number = 2
  6669. @State isShowSelectColor: boolean = false
  6670. @State isShowHLSelectColor: boolean = false
  6671. @State isShowPipBgSelectColor: boolean = false
  6672. @State pipLyWidth: number = 330
  6673. @State pipLyHeight: number = 120
  6674. // 构建颜色选择器
  6675. @Builder
  6676. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  6677. Row({ space: 10 }) {
  6678. HSBColorPicker({
  6679. color: '#FFFFFF',
  6680. radius: 8,
  6681. layout: HSBColorPickerLayout.COLUMN,
  6682. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  6683. '#fa7105'],
  6684. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  6685. this.changeLyricColor(value, isPip, isBGPip)
  6686. })
  6687. .height(250)
  6688. .layoutWeight(1)
  6689. .padding(25)
  6690. }
  6691. .width('66%')
  6692. }
  6693. @State isOpenPip: boolean = false
  6694. @State pipBgIndex: number = 0
  6695. // 构建字号控制器
  6696. @Builder
  6697. BuildFontControls(isPip: boolean) {
  6698. Column() {
  6699. if (isPip) {
  6700. Column() {
  6701. Row() {
  6702. Text('悬浮歌词')
  6703. .margin({ left: 18 })
  6704. .fontSize(15)
  6705. .fontColor(Color.White)
  6706. .fontWeight(480)
  6707. .layoutWeight(1)
  6708. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  6709. .selectedColor(this.themeColor)
  6710. .switchPointColor(Color.White)
  6711. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6712. .margin({ right: 18 })
  6713. .onChange((checked: boolean) => {
  6714. this.isOpenPip = checked;
  6715. if (this.isOpenPip) {
  6716. this.startPip()
  6717. } else {
  6718. this.stopPip()
  6719. }
  6720. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  6721. })
  6722. .width(50)
  6723. .height(30);
  6724. }
  6725. .height(55)
  6726. }
  6727. .backgroundColor(Color.Transparent)
  6728. .borderRadius(15)
  6729. .margin({
  6730. left: 30,
  6731. right: 30,
  6732. top: 0,
  6733. bottom: 20
  6734. })
  6735. .padding(0)
  6736. .border({
  6737. color: Color.White,
  6738. width: 1.8
  6739. })
  6740. }
  6741. Row() {
  6742. Text(`歌词居中:`)
  6743. .fontSize(14)
  6744. .fontColor(Color.White)
  6745. .margin({ left: 2 })
  6746. Row() {
  6747. ForEach(['居中', '居左'], (size: string, index: number) => {
  6748. Button(size)
  6749. .width(60)
  6750. .height(28)
  6751. .fontSize(12)
  6752. .fontColor('#FFFFFF')
  6753. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  6754. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  6755. .border({
  6756. color: (!isPip && this.currentLyricAlignMode === index) ||
  6757. (isPip && this.currentLyricAlignModePip === index) ?
  6758. '#007DFF' : '#DDDDDD',
  6759. width: 1.8
  6760. })
  6761. .onClick(() => {
  6762. this.setLyricAlignMode(index, isPip)
  6763. })
  6764. .margin({ left: 10, right: 8 })
  6765. })
  6766. }
  6767. .width('76%')
  6768. Blank()
  6769. }
  6770. .margin({
  6771. top: 10,
  6772. bottom: 10,
  6773. right: 20,
  6774. left: 20
  6775. })
  6776. if (isPip) {
  6777. Row() {
  6778. Text(`悬浮背景:`)
  6779. .fontSize(14)
  6780. .fontColor(Color.White)
  6781. Select([
  6782. { value: CommonConstants.PIP_LYRIC_BG[0] },
  6783. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  6784. .font({ size: 13, weight: FontWeight.Medium })
  6785. .fontColor(Color.White)
  6786. .margin({ left: 10 })
  6787. .selected(this.pipBgIndex)
  6788. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  6789. .onSelect(async (_index: number, text?: string | undefined) => {
  6790. this.pipBgIndex = _index
  6791. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  6792. if (this.pipBgIndex === 0) {
  6793. if (this.cover) {
  6794. this.pipBg = this.cover
  6795. } else {
  6796. this.pipBg = this.imageColor
  6797. }
  6798. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  6799. } else {
  6800. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  6801. }
  6802. })
  6803. Column() {
  6804. }
  6805. .backgroundColor(this.pipBg)
  6806. .margin({ left: 10, right: 10 })
  6807. .borderRadius(20)
  6808. .height(28)
  6809. .width(28)
  6810. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6811. Row() {
  6812. SymbolGlyph($r('sys.symbol.paintbrush'))
  6813. .fontColor([Color.White])
  6814. .effectStrategy(1)
  6815. Text(`选择颜色`)
  6816. .fontSize(13)
  6817. .margin({ left: 10 })
  6818. .fontColor(Color.White)
  6819. }
  6820. }
  6821. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  6822. .backgroundColor(Color.Transparent)
  6823. .border({
  6824. color: '#FFFFFF',
  6825. radius: 20,
  6826. width: 1.8
  6827. })
  6828. .height(36)
  6829. .width(110)
  6830. .onClick(() => {
  6831. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  6832. })
  6833. .bindPopup(this.isShowPipBgSelectColor, {
  6834. builder: this.SelectColor(false, isPip, true),
  6835. placement: Placement.Top,
  6836. mask: { color: '#33000000' },
  6837. enableArrow: false, //是否显示箭头
  6838. showInSubWindow: false,
  6839. onStateChange: (e) => {
  6840. if (!e.isVisible) {
  6841. this.isShowPipBgSelectColor = false
  6842. }
  6843. }
  6844. })
  6845. }
  6846. .width('76%')
  6847. .margin({ bottom: 5, right: 45, left: 20 })
  6848. }
  6849. if (!isPip) {
  6850. Row() {
  6851. Text(`高亮居中:`)
  6852. .fontSize(14)
  6853. .fontColor(Color.White)
  6854. Column() {
  6855. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  6856. .selectedColor(this.themeColor)
  6857. .switchPointColor(Color.White)
  6858. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6859. .onChange((checked: boolean) => {
  6860. this.isHightLightCenter = checked;
  6861. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  6862. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  6863. })
  6864. .width(50)
  6865. .height(30)
  6866. .alignSelf(ItemAlign.Start)
  6867. .margin({ left: 12 })
  6868. Blank()
  6869. }
  6870. .width('76%')
  6871. }
  6872. .margin({
  6873. left: 20,
  6874. right: 15,
  6875. top: 10,
  6876. bottom: 10
  6877. })
  6878. }
  6879. Row() {
  6880. Text(`歌词颜色:`)
  6881. .fontSize(14)
  6882. .fontColor(Color.White)
  6883. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  6884. .fontSize(15)
  6885. .fontColor(Color.White)
  6886. .margin({ left: 12, right: 12 })
  6887. Column() {
  6888. }
  6889. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  6890. .margin({ right: 12 })
  6891. .borderRadius(20)
  6892. .height(28)
  6893. .width(28)
  6894. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6895. Row() {
  6896. SymbolGlyph($r('sys.symbol.paintbrush'))
  6897. .fontColor([Color.White])
  6898. .effectStrategy(1)
  6899. Text(`选择颜色`)
  6900. .fontSize(13)
  6901. .margin({ left: 10 })
  6902. .fontColor(Color.White)
  6903. }
  6904. }
  6905. .backgroundColor(Color.Transparent)
  6906. .border({
  6907. color: '#FFFFFF',
  6908. radius: 20,
  6909. width: 1.8
  6910. })
  6911. .height(36)
  6912. .width(110)
  6913. .onClick(() => {
  6914. this.isShowSelectColor = !this.isShowSelectColor
  6915. })
  6916. .bindPopup(this.isShowSelectColor, {
  6917. builder: this.SelectColor(false, isPip),
  6918. placement: Placement.Top,
  6919. mask: { color: '#33000000' },
  6920. enableArrow: false, //是否显示箭头
  6921. showInSubWindow: false,
  6922. onStateChange: (e) => {
  6923. if (!e.isVisible) {
  6924. this.isShowSelectColor = false
  6925. }
  6926. }
  6927. })
  6928. }
  6929. .width('76%')
  6930. .margin({
  6931. top: 10,
  6932. bottom: 10,
  6933. right: 45,
  6934. left: 20
  6935. })
  6936. Row() {
  6937. Text(`高亮颜色:`)
  6938. .fontSize(14)
  6939. .fontColor(Color.White)
  6940. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  6941. .fontSize(15)
  6942. .fontColor(Color.White)
  6943. .margin({ left: 12, right: 12 })
  6944. Column() {
  6945. }
  6946. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  6947. .margin({ right: 12 })
  6948. .borderRadius(20)
  6949. .height(28)
  6950. .width(28)
  6951. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6952. Row() {
  6953. SymbolGlyph($r('sys.symbol.paintbrush'))
  6954. .fontColor([Color.White])
  6955. .effectStrategy(1)
  6956. Text(`选择颜色`)
  6957. .fontSize(13)
  6958. .margin({ left: 10 })
  6959. .fontColor(Color.White)
  6960. }
  6961. }
  6962. .backgroundColor(Color.Transparent)
  6963. .border({
  6964. color: '#FFFFFF',
  6965. radius: 20,
  6966. width: 1.8
  6967. })
  6968. .height(36)
  6969. .width(110)
  6970. .onClick(() => {
  6971. this.isShowHLSelectColor = !this.isShowHLSelectColor
  6972. })
  6973. .bindPopup(this.isShowHLSelectColor, {
  6974. builder: this.SelectColor(true, isPip),
  6975. placement: Placement.Top,
  6976. mask: { color: '#33000000' },
  6977. enableArrow: false, //是否显示箭头
  6978. showInSubWindow: false,
  6979. onStateChange: (e) => {
  6980. if (!e.isVisible) {
  6981. this.isShowHLSelectColor = false
  6982. }
  6983. }
  6984. })
  6985. }
  6986. .width('76%')
  6987. .margin({
  6988. top: 10,
  6989. bottom: 10,
  6990. right: 45,
  6991. left: 20
  6992. })
  6993. if (isPip) {
  6994. Row() {
  6995. Text(`显示宽度:`)
  6996. .fontSize(14)
  6997. .fontColor(Color.White)
  6998. Slider({
  6999. value: this.pipLyWidth,
  7000. min: 10,
  7001. max: 800,
  7002. step: 1,
  7003. style: SliderStyle.OutSet
  7004. })
  7005. .blockColor(this.themeColor)
  7006. .trackColor($r('app.color.speed_text_color'))
  7007. .selectedColor(Color.White)
  7008. .trackThickness(6)
  7009. .onChange((value: number) => {
  7010. this.pipLyWidth = value
  7011. if (this.pipController) {
  7012. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  7013. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  7014. }
  7015. })
  7016. .width('76%')
  7017. }
  7018. .margin({
  7019. left: 20,
  7020. right: 15,
  7021. top: 5,
  7022. bottom: 5
  7023. })
  7024. Row() {
  7025. Text(`显示高度:`)
  7026. .fontSize(14)
  7027. .fontColor(Color.White)
  7028. Slider({
  7029. value: this.pipLyHeight,
  7030. min: 10,
  7031. max: 1000,
  7032. step: 1,
  7033. style: SliderStyle.OutSet
  7034. })
  7035. .blockColor(this.themeColor)
  7036. .trackColor($r('app.color.speed_text_color'))
  7037. .selectedColor(Color.White)
  7038. .trackThickness(6)
  7039. .onChange((value: number) => {
  7040. this.pipLyHeight = value
  7041. if (this.pipController) {
  7042. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  7043. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  7044. }
  7045. })
  7046. .width('76%')
  7047. }
  7048. .margin({
  7049. left: 20,
  7050. right: 15,
  7051. top: 5,
  7052. bottom: 5
  7053. })
  7054. }
  7055. Row() {
  7056. Text(`歌词字号:`)
  7057. .fontSize(14)
  7058. .fontColor(Color.White)
  7059. Slider({
  7060. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  7061. min: 12,
  7062. max: 30,
  7063. step: 0.1,
  7064. style: SliderStyle.OutSet
  7065. })
  7066. .blockColor(this.themeColor)
  7067. .trackColor($r('app.color.speed_text_color'))
  7068. .selectedColor(Color.White)
  7069. .trackThickness(6)
  7070. .onChange((value: number) => {
  7071. this.setLyricTextSize(value, isPip)
  7072. })
  7073. .width('76%')
  7074. }
  7075. .margin({
  7076. left: 20,
  7077. right: 15,
  7078. top: 5,
  7079. bottom: 5
  7080. })
  7081. Row() {
  7082. Text(`高亮倍数:`)
  7083. .fontSize(14)
  7084. .fontColor(Color.White)
  7085. Slider({
  7086. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  7087. min: 1,
  7088. max: 2,
  7089. step: 0.1,
  7090. style: SliderStyle.OutSet
  7091. })
  7092. .blockColor(this.themeColor)
  7093. .trackColor($r('app.color.speed_text_color'))
  7094. .selectedColor(Color.White)
  7095. .trackThickness(6)
  7096. .onChange((value: number) => {
  7097. this.setHighLyricTextSize(value, isPip)
  7098. })
  7099. .width('76%')
  7100. }
  7101. .margin({
  7102. left: 20,
  7103. right: 15,
  7104. top: 5,
  7105. bottom: 5
  7106. })
  7107. Row() {
  7108. Text(`歌词间隙:`)
  7109. .fontSize(14)
  7110. .fontColor(Color.White)
  7111. Slider({
  7112. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  7113. min: 0,
  7114. max: 100,
  7115. step: 1,
  7116. style: SliderStyle.OutSet
  7117. })
  7118. .blockColor(this.themeColor)
  7119. .trackColor($r('app.color.speed_text_color'))
  7120. .selectedColor(Color.White)
  7121. .trackThickness(6)
  7122. .onChange((value: number) => {
  7123. this.setLyricLineSpace(value, isPip)
  7124. })
  7125. .width('76%')
  7126. }
  7127. .margin({
  7128. left: 20,
  7129. right: 15,
  7130. top: 5,
  7131. bottom: 5
  7132. })
  7133. //取值间隔为100,默认为400,取值越大,字体越粗
  7134. Row() {
  7135. Text(`歌词字重:`)
  7136. .fontSize(14)
  7137. .fontColor(Color.White)
  7138. Slider({
  7139. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  7140. min: 100,
  7141. max: 900,
  7142. step: 100,
  7143. style: SliderStyle.OutSet
  7144. })
  7145. .blockColor(this.themeColor)
  7146. .trackColor($r('app.color.speed_text_color'))
  7147. .selectedColor(Color.White)
  7148. .trackThickness(6)
  7149. .onChange((value: number) => {
  7150. if (isPip) {
  7151. this.lyricTextWeightPip = value
  7152. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  7153. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  7154. } else {
  7155. this.lyricTextWeight = value
  7156. this.lyricController.setTextWeight(this.lyricTextWeight)
  7157. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  7158. }
  7159. })
  7160. .width('76%')
  7161. }
  7162. .margin({
  7163. left: 20,
  7164. right: 15,
  7165. top: 5,
  7166. bottom: 5
  7167. })
  7168. if (!isPip) {
  7169. Row() {
  7170. Text(`歌词模糊:`)
  7171. .fontSize(14)
  7172. .fontColor(Color.White)
  7173. Slider({
  7174. value: isPip ? this.blurDegreePip : this.blurDegree,
  7175. min: 0,
  7176. max: 5,
  7177. step: 0.1,
  7178. style: SliderStyle.OutSet
  7179. })
  7180. .blockColor(this.themeColor)
  7181. .trackColor($r('app.color.speed_text_color'))
  7182. .selectedColor(Color.White)
  7183. .trackThickness(6)
  7184. .onChange((value: number) => {
  7185. this.setBlurDegree(value, isPip)
  7186. })
  7187. .width('76%')
  7188. }
  7189. .margin({
  7190. left: 20,
  7191. right: 15,
  7192. top: 5,
  7193. bottom: 15
  7194. })
  7195. }
  7196. Row() {
  7197. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  7198. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  7199. }
  7200. .justifyContent(FlexAlign.Center)
  7201. .margin({ top: 3, bottom: 10 })
  7202. }
  7203. }
  7204. private setBlurDegree(index: number, isPip: boolean) {
  7205. if (isPip) {
  7206. this.blurDegreePip = index
  7207. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  7208. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  7209. } else {
  7210. this.blurDegree = index
  7211. this.lyricController.setBlurDegree(this.blurDegree)
  7212. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  7213. }
  7214. }
  7215. private setLyricAlignMode(index: number, isPip: boolean) {
  7216. if (isPip) {
  7217. this.currentLyricAlignModePip = index
  7218. if (this.currentLyricAlignModePip === 1) {
  7219. this.lyricControllerXF.setAlignMode("left")
  7220. } else {
  7221. this.lyricControllerXF.setAlignMode("center")
  7222. }
  7223. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  7224. } else {
  7225. this.currentLyricAlignMode = index
  7226. if (this.currentLyricAlignMode === 1) {
  7227. this.lyricController.setAlignMode("left")
  7228. } else {
  7229. this.lyricController.setAlignMode("center")
  7230. }
  7231. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  7232. }
  7233. }
  7234. private setLyricTextSize(index: number, isPip: boolean) {
  7235. if (isPip) {
  7236. this.currentLyricSizePip = index
  7237. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  7238. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  7239. } else {
  7240. this.currentLyricSize = index
  7241. this.lyricController.setTextSize(this.currentLyricSize)
  7242. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  7243. }
  7244. }
  7245. private setHighLyricTextSize(scale: number, isPip: boolean) {
  7246. if (isPip) {
  7247. this.currentHightLyricSizePip = scale
  7248. this.lyricControllerXF
  7249. .setHighlightScale(this.currentHightLyricSizePip)
  7250. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  7251. } else {
  7252. this.currentHightLyricSize = scale
  7253. this.lyricController
  7254. .setHighlightScale(this.currentHightLyricSize)
  7255. PreferencesUtil.putSync('HighLyricTextSize', scale)
  7256. }
  7257. }
  7258. private setLyricLineSpace(index: number, isPip: boolean) {
  7259. if (isPip) {
  7260. this.currentLyricLineSpacePip = index
  7261. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  7262. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  7263. } else {
  7264. this.currentLyricLineSpace = index
  7265. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  7266. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  7267. }
  7268. }
  7269. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  7270. LogUtil.info('onecold isBG = ' + isBG)
  7271. if (isBG) { //如果是设置悬浮背景
  7272. this.pipBg = color
  7273. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  7274. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  7275. return
  7276. }
  7277. if (isPip) {
  7278. this.currentLyricColorPip = color
  7279. this.lyricControllerXF
  7280. .setTextColor(this.currentLyricColorPip)
  7281. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  7282. } else {
  7283. this.currentLyricColor = color
  7284. this.lyricController
  7285. .setTextColor(this.currentLyricColor)
  7286. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  7287. }
  7288. }
  7289. private changeLyricHightLightColor(color: string, isPip: boolean) {
  7290. if (isPip) {
  7291. this.currentHighLightLyricColorPip = color
  7292. this.lyricControllerXF
  7293. .setHighlightColor(this.currentHighLightLyricColorPip)
  7294. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  7295. } else {
  7296. this.currentHighLightLyricColor = color
  7297. this.lyricController
  7298. .setHighlightColor(this.currentHighLightLyricColor)
  7299. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  7300. }
  7301. }
  7302. // 构建时间控制器
  7303. @Builder
  7304. BuildTimeControls() {
  7305. Column() {
  7306. // 时间显示
  7307. Text(this.getTimeText())
  7308. .fontSize(18)
  7309. .fontColor(Color.White)
  7310. .margin({ bottom: 10 })
  7311. Row() {
  7312. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  7313. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  7314. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  7315. }
  7316. .justifyContent(FlexAlign.Center)
  7317. }
  7318. .margin({ top: 12, bottom: 8 })
  7319. }
  7320. // 精度按钮组件
  7321. @Builder
  7322. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  7323. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7324. Column() {
  7325. Image(icon)
  7326. .width(28)
  7327. .margin({ bottom: 5 })
  7328. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  7329. Text(label)
  7330. .fontSize(12)
  7331. .fontColor('#FFFFFF')
  7332. }
  7333. }
  7334. .backgroundColor(Color.Transparent)
  7335. .enabled(!this.isButtonDisabled(step))
  7336. .onClick(() => this.handlePrecisionAdjust(step))
  7337. .padding(5)
  7338. .width(66)
  7339. .height(66)
  7340. .margin({ left: 18, right: 18 })
  7341. .border({
  7342. color: '#FFFFFF',
  7343. width: 1.8
  7344. })
  7345. }
  7346. private handlePrecisionAdjust(step: number) {
  7347. if (step === 0) {
  7348. this.timeOffset = 0
  7349. return
  7350. }
  7351. // 精度处理:保留1位小数
  7352. const newOffset = Number((this.timeOffset + step).toFixed(5))
  7353. // 边界保护(±15.0秒)
  7354. if (newOffset < -30.0 || newOffset > 30.0) {
  7355. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  7356. return
  7357. }
  7358. // 状态更新
  7359. this.timeOffset = newOffset
  7360. }
  7361. // 按钮禁用逻辑
  7362. private isButtonDisabled(step: number): boolean {
  7363. const futureOffset = this.timeOffset + step
  7364. return (futureOffset < -30.0) || (futureOffset > 30.0)
  7365. }
  7366. // 时间显示文本升级
  7367. private getTimeText(): string {
  7368. const absValue = Math.abs(this.timeOffset)
  7369. return this.timeOffset === 0
  7370. ? '歌词时间已重置'
  7371. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  7372. }
  7373. // 导入 本地歌词 搜索歌词
  7374. @Builder
  7375. pushLyricButton(icon: Resource, step: number, label: string) {
  7376. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7377. Row() {
  7378. Image(icon)
  7379. .width(14)
  7380. .margin({ left: 13 })
  7381. Text(label)
  7382. .fontSize(12)
  7383. .margin({ left: 6 })
  7384. .fontColor('#FFFFFF')
  7385. }
  7386. }
  7387. .onClick(() => {
  7388. switch (step) {
  7389. case 0:
  7390. this.callFilePickerSelectFileForLyric()
  7391. break;
  7392. case 1:
  7393. //判断是不是赞助会员
  7394. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  7395. this.isLyricSetting = false
  7396. this.showTipsDialog()
  7397. return
  7398. }
  7399. if (StrUtil.isNotEmpty(this.videoUrl)) {
  7400. ToastUtil.showToast('正在获取')
  7401. this.isLyricSetting = false
  7402. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  7403. this.initLyric(lyricPath, true);
  7404. }
  7405. break;
  7406. }
  7407. })
  7408. .padding(5)
  7409. .width(110)
  7410. .backgroundColor(Color.Transparent)
  7411. .height(40)
  7412. .margin({ left: 6, right: 6 })
  7413. .border({
  7414. color: '#FFFFFF',
  7415. radius: 20,
  7416. width: 1.8
  7417. })
  7418. }
  7419. showVipDialog() {
  7420. DialogHelper.showCustomContentDialog({
  7421. dialogId: 'vip',
  7422. title: "友情提示",
  7423. autoCancel: false, //点击遮障层时,不关闭弹窗
  7424. backCancel: true, //点击返回键,不关闭弹窗
  7425. contentBuilder: () => {
  7426. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  7427. },
  7428. buttons: [],
  7429. })
  7430. }
  7431. //去赞助的自定义内容
  7432. @Builder
  7433. customVipBuilder(content: string) {
  7434. Column() {
  7435. Text(content)
  7436. .fontColor(Color.Gray)
  7437. .fontSize(16)
  7438. .alignSelf(ItemAlign.Start)
  7439. .margin({ bottom: 15 })
  7440. .fontSize(16)
  7441. Row() {
  7442. Button('取消')
  7443. .fontColor(Color.White)
  7444. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  7445. .height(50)
  7446. .layoutWeight(1)
  7447. .stateEffect(true)
  7448. .margin({ right: 6 })
  7449. .onClick(() => {
  7450. DialogHelper.closeDialog('vip'); //关闭弹框
  7451. })
  7452. Button('开通')
  7453. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  7454. .layoutWeight(1)
  7455. .height(50)
  7456. .backgroundColor(this.themeColor)
  7457. .stateEffect(true)
  7458. .margin({ left: 6 })
  7459. .onClick(() => {
  7460. DialogHelper.closeDialog('vip'); //关闭弹框
  7461. this.isShowPlay = false
  7462. this.mType = 1 //跳转到用户中心
  7463. // router.pushUrl({
  7464. // url: 'pages/VipPage'
  7465. // }, router.RouterMode.Single);
  7466. })
  7467. }
  7468. }
  7469. .width("100%")
  7470. .padding(10)
  7471. }
  7472. showTipsDialog() {
  7473. DialogHelper.showCustomContentDialog({
  7474. dialogId: 'tips',
  7475. title: "友情提示",
  7476. autoCancel: false, //点击遮障层时,不关闭弹窗
  7477. backCancel: true, //点击返回键,不关闭弹窗
  7478. contentBuilder: () => {
  7479. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  7480. },
  7481. buttons: [],
  7482. })
  7483. }
  7484. @Builder
  7485. customTipsBuilder(content: string) {
  7486. Column() {
  7487. Text(content)
  7488. .fontColor(Color.Gray)
  7489. .fontSize(16)
  7490. .alignSelf(ItemAlign.Start)
  7491. .margin({ bottom: 15 })
  7492. .fontSize(16)
  7493. Row() {
  7494. Button('取消')
  7495. .fontColor(Color.White)
  7496. .backgroundColor(this.themeColor)
  7497. .height(50)
  7498. .layoutWeight(1)
  7499. .stateEffect(true)
  7500. .margin({ right: 6 })
  7501. .onClick(() => {
  7502. DialogHelper.closeDialog('tips'); //关闭弹框
  7503. })
  7504. Button('跳转')
  7505. .fontColor(Color.White)//
  7506. .layoutWeight(1)
  7507. .height(50)
  7508. .backgroundColor(this.themeColor)
  7509. .stateEffect(true)
  7510. .margin({ left: 6 })
  7511. .onClick(() => {
  7512. DialogHelper.closeDialog('tips'); //关闭弹框
  7513. this.isShowPlay = false
  7514. this.mType = 3
  7515. // router.pushUrl({
  7516. // url: 'pages/SettingPage'
  7517. // }, router.RouterMode.Single);
  7518. })
  7519. }
  7520. }
  7521. .width("100%")
  7522. .padding(10)
  7523. }
  7524. @Builder
  7525. PlayMoreSheet() {
  7526. Column() {
  7527. this.MoreList()
  7528. }
  7529. .width('100%')
  7530. .height('100%')
  7531. }
  7532. @Builder
  7533. MoreList() {
  7534. Scroll() {
  7535. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  7536. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  7537. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7538. Row() {
  7539. if (more.id === 3&&this.currentSong) {
  7540. Image(more.image)
  7541. .width(24)
  7542. .height(24)
  7543. .margin({ left: 10, right: 10 })
  7544. Text(more.title)
  7545. .fontSize(16)
  7546. .fontColor(Color.White)
  7547. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  7548. height: this.isCoverOpacity() ? '95%' : '95%',
  7549. dragBar: true,
  7550. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7551. showClose: true,
  7552. blurStyle: BlurStyle.Thin,
  7553. backgroundColor: Color.Transparent,
  7554. title: { title: '歌曲信息' }
  7555. })
  7556. } else if (more.id === 15 && this.currentSong) { //编辑信息
  7557. Image(more.image)
  7558. .width(24)
  7559. .height(24)
  7560. .margin({ left: 10, right: 10 })
  7561. Text(more.title)
  7562. .fontSize(16)
  7563. .fontColor(Color.White)
  7564. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  7565. height: this.isCoverOpacity() ? '95%' : '93%',
  7566. dragBar: true,
  7567. showClose: true,
  7568. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7569. // blurStyle:BlurStyle.Thin,
  7570. // backgroundColor:Color.Transparent,
  7571. title: { title: '编辑信息' }
  7572. })
  7573. } else if (more.id === 5) { //定时关闭
  7574. Image(more.image)
  7575. .width(24)
  7576. .height(24)
  7577. .margin({ left: 10, right: 10 })
  7578. Text(more.title)
  7579. .fontSize(16)
  7580. .fontColor(Color.White)
  7581. .onClick(() => {
  7582. this.doMore(more.id)
  7583. })
  7584. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  7585. height: this.isCoverOpacity() ? '95%' : '95%',
  7586. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7587. dragBar: true,
  7588. showClose: true,
  7589. title: { title: $r('app.string.time_close') }
  7590. })
  7591. } else if (more.id === 2) { //歌词设置
  7592. Image(more.image)
  7593. .width(24)
  7594. .height(24)
  7595. .margin({ left: 10, right: 10 })
  7596. Text(more.title)
  7597. .fontSize(16)
  7598. .fontColor(Color.White)
  7599. } else if (more.id === 16) { //悬浮歌词设置
  7600. Image(more.image)
  7601. .width(24)
  7602. .height(24)
  7603. .margin({ left: 10, right: 10 })
  7604. Text(more.title)
  7605. .fontSize(16)
  7606. .fontColor(Color.White)
  7607. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  7608. height: this.isCoverOpacity() ? '95%' : '95%',
  7609. dragBar: true,
  7610. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7611. showClose: true,
  7612. blurStyle: BlurStyle.Thin,
  7613. backgroundColor: Color.Transparent,
  7614. title: { title: '悬浮歌词' }
  7615. })
  7616. } else if (more.id === 11) {
  7617. Image(more.image)
  7618. .width(24)
  7619. .height(24)
  7620. .margin({ left: 10, right: 10 })
  7621. Text(more.title)
  7622. .fontSize(16)
  7623. .fontColor(Color.White)
  7624. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  7625. height: this.isCoverOpacity() ? '95%' : '60%',
  7626. dragBar: true,
  7627. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7628. showClose: true,
  7629. blurStyle: BlurStyle.Thin,
  7630. backgroundColor: Color.Transparent,
  7631. title: { title: '跳过头尾' }
  7632. })
  7633. } else if (more.id === 12) { //投播
  7634. AVCastPicker({
  7635. customPicker: (): void => this.TPImageBuilder(more),
  7636. onStateChange: (state) => {
  7637. if (state == AVCastPickerState.STATE_APPEARING) {
  7638. console.log(' The picker starts showing.');
  7639. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  7640. console.log(' The picker finishes presenting.');
  7641. }
  7642. },
  7643. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  7644. sessionType: 'video'
  7645. })
  7646. .id('AVCastPicker')
  7647. } else {
  7648. Image(more.image)
  7649. .width(24)
  7650. .height(24)
  7651. .margin({ left: 10, right: 10 })
  7652. .onClick(() => {
  7653. this.doMore(more.id)
  7654. })
  7655. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  7656. .fontSize(16)
  7657. .fontColor(Color.White)
  7658. .onClick(() => {
  7659. this.doMore(more.id)
  7660. })
  7661. Select([//倍速
  7662. { value: '0.25x' },
  7663. { value: '0.5x' },
  7664. { value: '0.75x' },
  7665. { value: '1x' },
  7666. { value: '1.25x' },
  7667. { value: '1.5x' },
  7668. { value: '1.75x' },
  7669. { value: '2x' },
  7670. { value: '3x' }])
  7671. .font({ size: 16, weight: FontWeight.Medium })
  7672. .fontColor($r('sys.color.white'))
  7673. .margin({ left: 25 })
  7674. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  7675. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  7676. .value(Utility.optimizedFormat(this.playSpeed))
  7677. .onSelect(async (_index: number, text?: string | undefined) => {
  7678. let speed = parseFloat(text?.replace('x', '') || '1');
  7679. if (!CommonConstants.video_speed_list.includes(speed)) {
  7680. speed = 1;
  7681. }
  7682. this.playSpeed = speed
  7683. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  7684. })
  7685. Slider({
  7686. value: this.volume,
  7687. min: 0,
  7688. max: 1,
  7689. step: 0.1,
  7690. style: SliderStyle.OutSet
  7691. })
  7692. .margin({ left: 18, right: 8 })
  7693. .blockColor(this.themeColor)
  7694. .trackColor($r('app.color.speed_text_color'))
  7695. .selectedColor(Color.White)
  7696. .trackThickness(9)
  7697. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  7698. .onChange((value: number) => {
  7699. this.volume = value;
  7700. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  7701. PreferencesUtil.putSync('DefalutVolume',this.volume)
  7702. })
  7703. .layoutWeight(1)
  7704. Blank()
  7705. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  7706. .selectedColor(this.themeColor)
  7707. .switchPointColor(Color.White)
  7708. .margin({ right: 15 })
  7709. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7710. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  7711. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  7712. if (more.id == 6) {
  7713. this.isMusicMemoryPlay = checked;
  7714. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  7715. if (this.isMusicMemoryPlay) {
  7716. ToastUtil.showToast('记忆播放已开启')
  7717. } else {
  7718. ToastUtil.showToast('记忆播放已关闭')
  7719. }
  7720. }
  7721. })
  7722. .width(48)
  7723. .height(24);
  7724. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  7725. .selectedColor(this.themeColor)
  7726. .switchPointColor(Color.White)
  7727. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7728. .margin({ right: 15 })
  7729. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  7730. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  7731. if (more.id == 7) {
  7732. this.isMusicBGCover = checked;
  7733. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  7734. if (this.isMusicBGCover) {
  7735. ToastUtil.showToast('播放背景随音乐封面已开启')
  7736. } else {
  7737. ToastUtil.showToast('播放背景随音乐封面已关闭')
  7738. }
  7739. }
  7740. })
  7741. .width(48)
  7742. .height(24);
  7743. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  7744. .selectedColor(this.themeColor)
  7745. .switchPointColor(Color.White)
  7746. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7747. .margin({ right: 15 })
  7748. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  7749. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  7750. if (more.id == 8) {
  7751. this.isSavePlayMode = checked;
  7752. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  7753. if (this.isSavePlayMode) {
  7754. ToastUtil.showToast('保存播放模式已开启')
  7755. } else {
  7756. ToastUtil.showToast('保存播放模式已关闭')
  7757. }
  7758. }
  7759. })
  7760. .width(48)
  7761. .height(24);
  7762. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  7763. .selectedColor(this.themeColor)
  7764. .switchPointColor(Color.White)
  7765. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7766. .margin({ right: 15 })
  7767. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  7768. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  7769. if (more.id == 13) {
  7770. this.isCoverRectangle = checked;
  7771. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  7772. if (this.isCoverRectangle) {
  7773. ToastUtil.showToast('封面方形已开启')
  7774. this.animationRoFun()
  7775. } else {
  7776. ToastUtil.showToast('封面圆形已开启')
  7777. this.animationRoFun()
  7778. }
  7779. }
  7780. })
  7781. .width(48)
  7782. .height(24);
  7783. }
  7784. }
  7785. .width('100%')
  7786. .height(45)
  7787. .padding(15)
  7788. .backgroundColor(Color.Transparent)
  7789. .borderRadius(12)
  7790. .margin({ bottom: 6 })
  7791. }
  7792. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  7793. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  7794. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  7795. .backgroundColor(Color.Transparent)
  7796. .onClick(() => {
  7797. this.doMore(more.id)
  7798. })
  7799. });
  7800. }
  7801. .width('100%')
  7802. .padding(16)
  7803. }.margin({ bottom: 18 })
  7804. }
  7805. @Builder
  7806. TPImageBuilder(more: MoreItem): void {
  7807. Row() {
  7808. Image($r('app.media.tuoping'))
  7809. .width(22)
  7810. .height(22)
  7811. .margin({ left: 10, right: 10 })
  7812. Text(more.title)
  7813. .fontSize(16)
  7814. .fontColor(Color.White)
  7815. }
  7816. .width('100%')
  7817. .layoutWeight(1)
  7818. .alignItems(VerticalAlign.Center)
  7819. .justifyContent(FlexAlign.Start)
  7820. }
  7821. private moreItems: MoreItem[] = [
  7822. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  7823. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  7824. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  7825. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  7826. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  7827. { id: 15, image: $r('app.media.rename2'), title: '编辑信息' },
  7828. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  7829. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  7830. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  7831. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  7832. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  7833. { id: 4, image: $r('app.media.share2'), title: '分享' },
  7834. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  7835. { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  7836. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  7837. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  7838. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  7839. ];
  7840. @State isShowMoreView: boolean = false;
  7841. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  7842. @State isShowTimeCloseMore: boolean = false
  7843. @State isShowDetailMore: boolean = false
  7844. @State isMusicBGCover: boolean = true
  7845. @State isSavePlayMode: boolean = true
  7846. @State isLyricSetting: boolean = false
  7847. @State isJumpSetting: boolean = false
  7848. @State isShowEdit: boolean = false
  7849. @State showPipLyric: boolean = false
  7850. async setRingTone() {
  7851. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  7852. return
  7853. }
  7854. // 确定后的逻辑
  7855. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  7856. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  7857. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  7858. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  7859. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  7860. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  7861. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  7862. , this.videoUrl, this.name).then(res => {
  7863. LogUtil.info('onecold setFlag :' + res);
  7864. });
  7865. }
  7866. doMore(moreId: number) {
  7867. switch (moreId) {
  7868. case 2: //歌词
  7869. this.isLyricSetting = !this.isLyricSetting;
  7870. this.isShowMoreView = false
  7871. break;
  7872. case 3: //详情
  7873. this.isShowDetailMore = !this.isShowDetailMore;
  7874. break;
  7875. case 4: //分享
  7876. if (this.currentSong !== undefined) {
  7877. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  7878. }
  7879. this.isShowMoreView = false
  7880. break;
  7881. case 5: //定时关闭
  7882. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  7883. break;
  7884. case 10: //设为铃声
  7885. this.setRingTone()
  7886. this.isShowMoreView = false
  7887. break;
  7888. case 11: //跳过头尾
  7889. this.isJumpSetting = !this.isJumpSetting;
  7890. break;
  7891. case 13: //倍速
  7892. break;
  7893. case 14: //搜索封面
  7894. if (this.currentSong !== undefined) {
  7895. this.doSearchCover(this.currentSong)
  7896. }
  7897. this.isShowMoreView = false
  7898. break;
  7899. case 15: //编辑信息
  7900. this.isShowEdit = !this.isShowEdit;
  7901. break;
  7902. case 16: //悬浮歌词
  7903. this.showPipLyric = !this.showPipLyric;
  7904. break;
  7905. case 17: //横屏模式
  7906. if (this.isLandscape) {
  7907. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  7908. } else {
  7909. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  7910. }
  7911. this.isShowMoreView = false
  7912. break;
  7913. }
  7914. }
  7915. /**
  7916. * 切换横竖屏
  7917. *
  7918. */
  7919. setOrientation(orientation: number) {
  7920. this.windowClass.setPreferredOrientation(orientation).then(() => {
  7921. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  7922. }).catch((err: BusinessError) => {
  7923. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  7924. });
  7925. }
  7926. /**
  7927. * 画中画功能(悬浮歌词功能)
  7928. *
  7929. */
  7930. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  7931. pipController?: PiPWindow.PiPController;
  7932. navigationId: string = '';
  7933. @State curState: string = '';
  7934. @State curError: ResourceStr = '';
  7935. @State pipBg: string = '#E8E8E8'
  7936. @State buttonAction: string = '';
  7937. //开启画中画功能
  7938. async startPip() {
  7939. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  7940. if (!this.pipController) {
  7941. await this.createPipController();
  7942. }
  7943. if (!this.pipController) {
  7944. Logger.info(`[${TAG}] pipController create error`);
  7945. return;
  7946. }
  7947. await this.pipController.startPiP();
  7948. }
  7949. async stopPip() {
  7950. if (!this.pipController) {
  7951. Logger.info(`[${TAG}] pipController is not exist`);
  7952. return;
  7953. }
  7954. this.isOpenPip = false
  7955. await this.pipController.stopPiP();
  7956. }
  7957. async createPipController() {
  7958. this.pipController = await PiPWindow.create({
  7959. context: getContext(this),
  7960. componentController: this.xcomponentController,
  7961. navigationId: this.navigationId,
  7962. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  7963. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  7964. customUIController: this.nodeController,
  7965. });
  7966. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  7967. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  7968. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  7969. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  7970. this.onStateChange(state, reason);
  7971. });
  7972. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  7973. this.onActionEvent(event, status);
  7974. });
  7975. }
  7976. destroyPipController() {
  7977. if (!this.pipController) {
  7978. return;
  7979. }
  7980. this.pipController.off('stateChange');
  7981. this.pipController.off('controlPanelActionEvent');
  7982. this.pipController = undefined;
  7983. }
  7984. onStateChange(state: PiPWindow.PiPState, reason: string) {
  7985. switch (state) {
  7986. case PiPWindow.PiPState.ABOUT_TO_START:
  7987. this.curState = 'ABOUT_TO_START';
  7988. this.curError = $r('app.string.current_error_hint');
  7989. break;
  7990. case PiPWindow.PiPState.STARTED:
  7991. this.curState = 'STARTED';
  7992. this.curError = $r('app.string.current_error_hint');
  7993. break;
  7994. case PiPWindow.PiPState.ABOUT_TO_STOP:
  7995. this.curState = 'ABOUT_TO_STOP';
  7996. this.curError = $r('app.string.current_error_hint');
  7997. break;
  7998. case PiPWindow.PiPState.STOPPED:
  7999. this.curState = 'STOPPED';
  8000. this.curError = $r('app.string.current_error_hint');
  8001. this.stopPip()
  8002. this.destroyPipController()
  8003. break;
  8004. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  8005. this.curState = 'ABOUT_TO_RESTORE';
  8006. this.curError = $r('app.string.current_error_hint');
  8007. break;
  8008. case PiPWindow.PiPState.ERROR:
  8009. this.curState = 'ERROR';
  8010. this.curError = reason;
  8011. break;
  8012. default:
  8013. break;
  8014. }
  8015. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  8016. }
  8017. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  8018. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  8019. switch (event) {
  8020. case 'playbackStateChanged':
  8021. if (status === 0) {
  8022. this.pause();
  8023. } else {
  8024. this.startPlayOrResumePlay();
  8025. }
  8026. break;
  8027. case 'nextVideo':
  8028. // 切换到下一个视频
  8029. this.playNext()
  8030. break;
  8031. case 'previousVideo':
  8032. // 切换到上一个视频
  8033. this.playPrevious()
  8034. break;
  8035. case 'previousVideo':
  8036. // 切换到上一个视频
  8037. this.playPrevious()
  8038. break;
  8039. default:
  8040. }
  8041. this.buttonAction = event + `-status:${status}`;
  8042. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  8043. }
  8044. /**
  8045. * 画中画功能(悬浮歌词功能)结束
  8046. *
  8047. */
  8048. doSearchCover(item: VideoItem) {
  8049. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  8050. this.isShowMoreView = false
  8051. this.showTipsDialog()
  8052. return
  8053. }
  8054. if (item !== undefined) {
  8055. let artist = item?.artist
  8056. if (StrUtil.isEmpty(artist) || artist === undefined) {
  8057. artist = ''
  8058. }
  8059. this.searchCover(item, item.name, artist)
  8060. }
  8061. }
  8062. searchCover(item: VideoItem, title: string, artist: string) {
  8063. NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  8064. LogUtil.debug("onecold res =" + res)
  8065. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  8066. if (item.filePath == this.currentSong?.filePath) {
  8067. this.cover = res
  8068. if (this.currentSong) {
  8069. this.currentSong.pixelMapPath = res
  8070. }
  8071. }
  8072. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  8073. if (success) {
  8074. this.doUpdateData()
  8075. console.log(" onecold 更新音乐封面成功,数据库已同步");
  8076. } else {
  8077. console.error(" onecold 更新音乐封面数据库失败原因: " + error);
  8078. }
  8079. });
  8080. LogUtil.debug("onecold this.cover =" + this.cover)
  8081. }
  8082. })
  8083. }
  8084. @State jumpTopTime: number = 0
  8085. @State jumpEndTime: number = 0
  8086. @State isOpenJump: boolean = false
  8087. @Builder
  8088. JumpTopEndSheet() {
  8089. Scroll() {
  8090. Column() {
  8091. Column() {
  8092. Text('仅对本播放列表有效')
  8093. .fontSize(16)
  8094. .fontColor($r('app.color.text_color'))
  8095. // 跳过头尾
  8096. Column() {
  8097. Row() {
  8098. Text('跳过片头:')
  8099. .fontSize(16)
  8100. .fontColor($r('app.color.text_color'))
  8101. Text(this.jumpTopTime + 's')
  8102. .fontSize(16)
  8103. .fontColor($r('app.color.text_color'))
  8104. }
  8105. .margin({ bottom: 5 })
  8106. Row() {
  8107. Slider({
  8108. value: this.jumpTopTime,
  8109. min: 0,
  8110. max: 120,
  8111. step: 1,
  8112. style: SliderStyle.OutSet
  8113. })
  8114. .blockColor(this.themeColor)
  8115. .trackColor($r('app.color.speed_text_color'))
  8116. .selectedColor(Color.White)
  8117. .trackThickness(8)
  8118. .onChange((value: number) => {
  8119. this.jumpTopTime = value;
  8120. })
  8121. .width('85%')
  8122. }
  8123. .alignItems(VerticalAlign.Top)
  8124. }
  8125. .margin({ top: 10, bottom: 10 })
  8126. // 跳过头尾
  8127. Column() {
  8128. Row() {
  8129. Text('跳过片尾:')
  8130. .fontSize(16)
  8131. .fontColor($r('app.color.text_color'))
  8132. Text(this.jumpEndTime + 's')
  8133. .fontSize(16)
  8134. .fontColor($r('app.color.text_color'))
  8135. }
  8136. .margin({ bottom: 5 })
  8137. Row() {
  8138. Slider({
  8139. value: this.jumpEndTime,
  8140. min: 0,
  8141. max: 120,
  8142. step: 1,
  8143. style: SliderStyle.OutSet
  8144. })
  8145. .blockColor(this.themeColor)
  8146. .trackColor($r('app.color.speed_text_color'))
  8147. .selectedColor(Color.White)
  8148. .trackThickness(8)
  8149. .onChange((value: number) => {
  8150. this.jumpEndTime = value;
  8151. })
  8152. .width('85%')
  8153. }
  8154. .alignItems(VerticalAlign.Top)
  8155. }
  8156. .margin({ top: 10, bottom: 10 })
  8157. Row() {
  8158. Button('保存设置')
  8159. .fontColor(Color.White)
  8160. .layoutWeight(1)
  8161. .height(40)
  8162. .width(80)
  8163. .backgroundColor(this.themeColor)
  8164. .stateEffect(true)
  8165. .margin({ left: 0, bottom: 20 })
  8166. .onClick(async () => {
  8167. if (!Utility.isNoble()) {
  8168. this.isJumpSetting = false
  8169. this.isShowMoreView = false
  8170. this.showVipDialog()
  8171. return
  8172. }
  8173. if (this.currentSong === undefined) {
  8174. return
  8175. }
  8176. if (this.modeType === 0) {
  8177. let parentPath = FileUtil.getParentPath(this.videoUrl)
  8178. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  8179. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  8180. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  8181. } else if (this.modeType === 1) { //媒体库
  8182. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  8183. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  8184. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  8185. } else if (this.modeType === 2) { //艺术家
  8186. if (this.currentSong?.artist) {
  8187. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  8188. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  8189. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  8190. }
  8191. } else if (this.modeType === 3) { //专辑
  8192. if (this.currentSong?.album) {
  8193. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  8194. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  8195. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  8196. }
  8197. }
  8198. ToastUtil.showShort("保存成功")
  8199. this.isJumpSetting = false
  8200. })
  8201. }
  8202. .margin({
  8203. left: 38,
  8204. right: 38,
  8205. top: 10,
  8206. bottom: 10
  8207. })
  8208. .width(120)
  8209. .height(50)
  8210. }
  8211. }
  8212. }
  8213. .width('100%')
  8214. .height('100%')
  8215. }
  8216. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  8217. private onStateVastChange(state: AVCastPickerState) {
  8218. if (state == AVCastPickerState.STATE_APPEARING) {
  8219. console.log('The picker starts showing.');
  8220. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  8221. console.log('The picker finishes presenting.');
  8222. }
  8223. }
  8224. private showSelectLyric() {
  8225. DialogHelper.showActionSheetDialog({
  8226. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  8227. // sheets: ["本地歌词", "搜索歌词"],
  8228. sheets: [
  8229. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  8230. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  8231. ],
  8232. maskColor: Color.Transparent,
  8233. backgroundColor: $r('app.color.bg_card'),
  8234. transition: AnimationHelper.transitionInDown(666),
  8235. onAction: (index) => {
  8236. switch (index) {
  8237. case 0:
  8238. this.callFilePickerSelectFileForLyric()
  8239. break;
  8240. case 1:
  8241. if (StrUtil.isNotEmpty(this.videoUrl)) {
  8242. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  8243. this.initLyric(lyricPath);
  8244. }
  8245. break;
  8246. }
  8247. }
  8248. })
  8249. }
  8250. // 拉起picker选择文件管理器
  8251. async callFilePickerSelectFileForLyric(): Promise<void> {
  8252. try {
  8253. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  8254. DocumentSelectOptions.maxSelectNumber = 1
  8255. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  8256. let documentPicker = new picker.DocumentViewPicker();
  8257. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  8258. Logger.info(TAG,
  8259. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  8260. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  8261. this.saveVideoDatasLyric(DocumentSelectResult)
  8262. }
  8263. }).catch((err: BusinessError) => {
  8264. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  8265. });
  8266. } catch (err) {
  8267. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  8268. }
  8269. }
  8270. async saveVideoDatasLyric(uris: string[]) {
  8271. if (ArrayUtil.isEmpty(uris)) {
  8272. return
  8273. }
  8274. let newUris: string[] = [];
  8275. for (let i = 0; i < uris.length; i++) {
  8276. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  8277. Logger.info(TAG, 'filePath uri: ' + filePath);
  8278. newUris.push(filePath)
  8279. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  8280. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  8281. fileIo.copyFileSync(file.fd, file2.fd)
  8282. fileIo.closeSync(file);
  8283. fileIo.closeSync(file2);
  8284. this.initLyric(filePath)
  8285. }
  8286. }
  8287. private initDelayPlay(context: object) {
  8288. this.mContext = context;
  8289. }
  8290. startPipLyric() {
  8291. if (this.pipController) {
  8292. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  8293. PiPWindow.PiPControlStatus.PLAY);
  8294. }
  8295. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  8296. if (this.isOpenPip) {
  8297. this.startPip()
  8298. } else {
  8299. this.stopPip()
  8300. }
  8301. }
  8302. private startPlayOrResumePlay() {
  8303. this.startPipLyric()
  8304. this.mDestroyPage = false;
  8305. this.animationState = AnimationStatus.Running
  8306. LogUtils.getInstance().LOGI("startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  8307. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  8308. this.stopProgressTask();
  8309. this.startProgressTask();
  8310. this.play(this.videoUrl.toString());
  8311. }
  8312. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  8313. this.mIjkMediaPlayer.start();
  8314. this.setProgress()
  8315. this.CONTROL_PlayStatus = PlayStatus.PLAY
  8316. }
  8317. this.setIsPlaying(true)
  8318. this.updateSessionPlayState(true)
  8319. this.watchStatus();
  8320. this.updateLastPlayTimeStr(this.videoUrl)
  8321. }
  8322. updateLastPlayTimeStr(filePath: string) {
  8323. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  8324. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  8325. if (success) {
  8326. this.getHistoryList(false)
  8327. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  8328. } else {
  8329. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  8330. }
  8331. });
  8332. }
  8333. private completionNum(num: number): string | number {
  8334. if (num < 10) {
  8335. return '0' + num;
  8336. } else {
  8337. return num;
  8338. }
  8339. }
  8340. private stringForTime(timeMs: number): string {
  8341. let totalSeconds: number | string = (timeMs / 1000);
  8342. let newSeconds: number | string = totalSeconds % 60;
  8343. let minutes: number | string = (totalSeconds / 60) % 60;
  8344. let hours: number | string = totalSeconds / 3600;
  8345. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  8346. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  8347. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  8348. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  8349. if (this.isCurrentTime) {
  8350. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  8351. this.oldSeconds = newSeconds
  8352. } else {
  8353. newSeconds = this.oldSeconds
  8354. }
  8355. }
  8356. newSeconds = this.completionNum(newSeconds);
  8357. if (hours > 0) {
  8358. return hours + ":" + minutes + ":" + newSeconds;
  8359. } else {
  8360. return minutes + ":" + newSeconds;
  8361. }
  8362. }
  8363. private setProgress() {
  8364. let position = this.mIjkMediaPlayer.getCurrentPosition();
  8365. let duration = this.mIjkMediaPlayer.getDuration();
  8366. let pos = 0;
  8367. if (duration > 0) {
  8368. this.slideEnable = true;
  8369. let curPercent = position / duration;
  8370. pos = curPercent * 100;
  8371. if (pos > this.PROGRESS_MAX_VALUE) {
  8372. this.progressValue = this.PROGRESS_MAX_VALUE
  8373. } else {
  8374. this.progressValue = pos;
  8375. }
  8376. }
  8377. // LogUtils.getInstance()
  8378. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  8379. this.totalTime = this.stringForTime(duration);
  8380. if (position > duration) {
  8381. position = duration;
  8382. }
  8383. this.isCurrentTime = true;
  8384. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  8385. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  8386. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  8387. this.currentTime = this.stringForTime(position);
  8388. this.isCurrentTime = false
  8389. if (this.mIjkMediaPlayer.isPlaying()) {
  8390. this.randomColor =
  8391. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  8392. // 判断是否播放到结束时间
  8393. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  8394. if (position >= duration - this.jumpEndTime * 1000) {
  8395. this.playNext()
  8396. }
  8397. }
  8398. } else {
  8399. this.randomColor = 'rbg(0,0,0)'
  8400. }
  8401. }
  8402. private startProgressTask() {
  8403. let that = this;
  8404. this.updateProgressTimer = setInterval(() => {
  8405. //LogUtils.getInstance().LOGI("startProgressTask");
  8406. if (!that.mDestroyPage) {
  8407. that.setProgress();
  8408. }
  8409. }, 300);
  8410. }
  8411. private stopProgressTask() {
  8412. LogUtils.getInstance().LOGI("stopProgressTask");
  8413. clearInterval(this.updateProgressTimer);
  8414. }
  8415. private showLoadIng() {
  8416. this.loadingVisible = Visibility.Visible;
  8417. this.replayVisible = Visibility.None;
  8418. }
  8419. private hideLoadIng() {
  8420. this.loadingVisible = Visibility.None;
  8421. this.replayVisible = Visibility.None;
  8422. }
  8423. private showRePlay() {
  8424. this.loadingVisible = Visibility.None;
  8425. this.replayVisible = Visibility.Visible;
  8426. }
  8427. private async play(url: string) {
  8428. let that = this;
  8429. that.showLoadIng();
  8430. //设置XComponent回调的context
  8431. if (!!this.mContext) {
  8432. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  8433. }
  8434. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  8435. this.mIjkMediaPlayer.reset();
  8436. }
  8437. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  8438. //设置debug模式
  8439. this.mIjkMediaPlayer.setDebug(false);
  8440. //初始化配置
  8441. this.mIjkMediaPlayer.native_setup();
  8442. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  8443. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  8444. this.mIjkMediaPlayer.setVolume('1', '1');
  8445. }else{
  8446. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  8447. }
  8448. //设置视频源
  8449. this.mIjkMediaPlayer.setDataSource(url);
  8450. //设置视频源http请求头
  8451. let headers = new Map([
  8452. ["user_agent", "Mozilla/5.0 BiliDroid/7.30.0 (bbcallen@gmail.com)"],
  8453. ["referer", "https://www.bilibili.com"]
  8454. ]);
  8455. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  8456. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  8457. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  8458. // }
  8459. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  8460. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  8461. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  8462. const fileSize = await this.getFileSize(this.videoUrl);
  8463. let bufferSize = 1 * 1024 * 1024; // 默认缓冲区大小为2MB
  8464. if (fileSize > 3 * 1024 * 1024 * 1024) { // 文件大于3GB
  8465. bufferSize = 25 * 1024 * 1024; // 设置缓冲区大小为25MB
  8466. }
  8467. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  8468. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  8469. //停止预读的最小帧数
  8470. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  8471. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  8472. // 设置其他缓冲相关选项
  8473. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  8474. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  8475. //启动预加载
  8476. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  8477. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  8478. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  8479. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  8480. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  8481. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  8482. // 因此需要播放器丢包,才不会累积延时
  8483. // 这个和第三个参数packet-buffering无关。
  8484. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  8485. // 无限制收流
  8486. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  8487. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  8488. // 屏幕常亮
  8489. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  8490. // 设置超时
  8491. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  8492. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  8493. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  8494. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  8495. // 变速播放
  8496. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  8497. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  8498. let Speed = this.mIjkMediaPlayer.getSpeed()
  8499. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  8500. //是否开启循环播放
  8501. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  8502. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  8503. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  8504. if (height === 0) {
  8505. return;
  8506. }
  8507. const va = width / height;
  8508. const vpa = that.videoParentAspectRatio;
  8509. if (vpa > va) {
  8510. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  8511. } else {
  8512. that.videoWidth = '100%';
  8513. }
  8514. if (width && height) {
  8515. that.videoAspectRatio = width / height;
  8516. }
  8517. LogUtils.getInstance()
  8518. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  8519. that.hideLoadIng();
  8520. }
  8521. }
  8522. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  8523. let mOnPreparedListener: OnPreparedListener = {
  8524. onPrepared: async () => {
  8525. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  8526. try {
  8527. // this.cover = this.songList[this.curIndex].pixelMapPath
  8528. // this.artist = this.songList[this.curIndex].artist
  8529. // this.videoUrl = this.songList[this.curIndex].filePath
  8530. let isBgCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  8531. if (isBgCover && this.cover !== undefined && StrUtil.isNotEmpty(this.cover)) {
  8532. this.setImageColor2(this.cover)
  8533. } else {
  8534. this.getImageColor();
  8535. }
  8536. //保存碰一碰分享的当前的歌曲
  8537. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  8538. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  8539. await this.initLyric(lyricPath);
  8540. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  8541. this.avSessionController.initAvSession(false);
  8542. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  8543. this.setAvSessionListener();
  8544. this.updateSessionPlayState(true)
  8545. this.setCurrentPlayMode()
  8546. }, 500)
  8547. let timeoutPlay = 0
  8548. if (StrUtil.isNotEmpty(this.videoUrl) &&
  8549. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  8550. timeoutPlay = 1000
  8551. }
  8552. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  8553. if (this.modeType === 0) { //文件夹
  8554. let parentPath = FileUtil.getParentPath(this.videoUrl)
  8555. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  8556. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  8557. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  8558. } else if (this.modeType === 1) { //媒体库
  8559. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  8560. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  8561. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  8562. } else if (this.modeType === 2) { //艺术家
  8563. if (this.currentSong?.artist) {
  8564. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  8565. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  8566. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  8567. }
  8568. } else if (this.modeType === 3) { //专辑
  8569. if (this.currentSong?.album) {
  8570. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  8571. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  8572. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  8573. }
  8574. }
  8575. this.duration = this.mIjkMediaPlayer.getDuration()
  8576. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  8577. if (this.mIjkMediaPlayer != null) {
  8578. if (this.jumpTopTime * 1000 <= this.duration) {
  8579. // 调用 seekTo 方法,跳到指定时间
  8580. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  8581. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  8582. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  8583. }
  8584. }, timeoutPlay)
  8585. } else {
  8586. // 提示用户无法跳过
  8587. ToastUtil.showToast('跳过时间超过视频时长');
  8588. }
  8589. }
  8590. } else {
  8591. this.jumpTopTime = 0
  8592. this.jumpEndTime = 0
  8593. console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  8594. console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  8595. console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  8596. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  8597. //记忆播放(每一首都会记忆播放)
  8598. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  8599. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  8600. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  8601. this.restorePlaybackPosition() //读取播放记忆功能
  8602. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  8603. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  8604. this.restorePlaybackPosition() //读取播放记忆功能
  8605. }
  8606. this.isFirstStartPlay = false
  8607. }, timeoutPlay)
  8608. } else {
  8609. this.isFirstStartPlay = false
  8610. }
  8611. }
  8612. this.saveLastPlayList()
  8613. } catch (error) {
  8614. let err: BusinessError = error as BusinessError;
  8615. console.error('onecold failed with err: ' + JSON.stringify(err));
  8616. }
  8617. }
  8618. }
  8619. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  8620. let mOnTimedTextListener: OnTimedTextListener = {
  8621. onTimedText: () => {
  8622. }
  8623. }
  8624. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  8625. let mOnCompletionListener: OnCompletionListener = {
  8626. onCompletion: () => {
  8627. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  8628. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  8629. this.playNext()
  8630. } else if (this.playType == 1) { //1:单片重复播放
  8631. this.CONTROL_PlayStatus = PlayStatus.INIT
  8632. that.startPlayOrResumePlay();
  8633. } else if (this.playType == 2) { //2:正常播放,单曲播完
  8634. that.showRePlay();
  8635. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  8636. that.progressValue = this.PROGRESS_MAX_VALUE;
  8637. that.slideEnable = false;
  8638. that.stop();
  8639. // ToastUtil.showToast('开始重新播放')
  8640. } else if (this.playType == 3) { //3:随机播放
  8641. this.randomPlay()
  8642. }
  8643. }
  8644. }
  8645. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  8646. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  8647. onBufferingUpdate: (percent: number) => {
  8648. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  8649. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  8650. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  8651. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  8652. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  8653. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  8654. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  8655. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  8656. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  8657. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  8658. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  8659. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  8660. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  8661. let Looping = this.mIjkMediaPlayer.isLooping()
  8662. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  8663. }
  8664. }
  8665. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  8666. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  8667. onSeekComplete: () => {
  8668. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  8669. that.startPlayOrResumePlay();
  8670. }
  8671. }
  8672. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  8673. let mOnInfoListener: OnInfoListener = {
  8674. onInfo: (what: number, extra: number) => {
  8675. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  8676. that.hideLoadIng();
  8677. }
  8678. }
  8679. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  8680. let mOnErrorListener: OnErrorListener = {
  8681. onError: (what: number, extra: number) => {
  8682. this.stopProgressTask();
  8683. LogUtils.getInstance().LOGI("OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  8684. that.hideLoadIng();
  8685. if (StrUtil.isNotEmpty(this.videoUrl) && !FileUtil.accessSync(this.videoUrl)) {
  8686. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  8687. } else {
  8688. ToastUtil.showToast(getContext()
  8689. .resourceManager
  8690. .getStringByNameSync("Honey_the_video_is_playing_errant_The_system_is_wandering"))
  8691. }
  8692. }
  8693. }
  8694. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  8695. this.mIjkMediaPlayer.setMessageListener();
  8696. this.mIjkMediaPlayer.prepareAsync();
  8697. this.mIjkMediaPlayer.start();
  8698. }
  8699. //保存最后播放的那首歌和已经对应的播放列表
  8700. saveLastPlayList() {
  8701. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  8702. PreferencesUtil.putSync('LastMusicList', this.songList)
  8703. }
  8704. // 清空播放记录
  8705. clearVideoHistory() {
  8706. this.table.clearPlayHistory((success: boolean, error?: string) => {
  8707. if (success) {
  8708. this.historyList = [];
  8709. this.updateListData(this.historyList)
  8710. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  8711. ToastUtil.showToast('清空播放记录成功')
  8712. } else {
  8713. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  8714. }
  8715. });
  8716. }
  8717. public async setAvSessionListener() {
  8718. if (!this.avSessionController) {
  8719. return;
  8720. }
  8721. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  8722. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  8723. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  8724. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  8725. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  8726. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  8727. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  8728. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  8729. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  8730. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  8731. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  8732. }
  8733. setLoopMode() {
  8734. let itype = this.playType + 1
  8735. if (itype >= 4) {
  8736. this.playType = 0
  8737. ToastUtil.showToast('连续播放')
  8738. } else if (itype === 1) {
  8739. this.playType = 1
  8740. ToastUtil.showToast('单曲循环')
  8741. } else if (itype === 2) {
  8742. this.playType = 2
  8743. ToastUtil.showToast('单曲播完')
  8744. } else if (itype === 3) {
  8745. this.playType = 3
  8746. ToastUtil.showToast('随机播放')
  8747. } else if (itype === 0) {
  8748. this.playType = 0
  8749. ToastUtil.showToast('连续播放')
  8750. }
  8751. PreferencesUtil.putSync('musicPlayType', this.playType)
  8752. this.setCurrentPlayMode()
  8753. }
  8754. private sessionSetLoopModeCallback = (mode: number) => {
  8755. if (this.mIjkMediaPlayer != null) {
  8756. ToastUtil.showToast('当前播放模式:' + mode)
  8757. Logger.info('onecold 当前播放模式= ' + mode)
  8758. let hmPlayMode = mode + 1
  8759. if (hmPlayMode >= 4) {
  8760. hmPlayMode = 0
  8761. }
  8762. if (hmPlayMode === 1) {
  8763. this.playType = 1
  8764. ToastUtil.showToast('单曲循环')
  8765. } else if (hmPlayMode === 0) {
  8766. this.playType = 2
  8767. ToastUtil.showToast('单曲播完')
  8768. } else if (hmPlayMode === 3) {
  8769. this.playType = 3
  8770. ToastUtil.showToast('随机播放')
  8771. } else if (hmPlayMode === 2) {
  8772. this.playType = 0
  8773. ToastUtil.showToast('连续播放')
  8774. }
  8775. PreferencesUtil.putSync('musicPlayType', this.playType)
  8776. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  8777. let playBackState: avSession.AVPlaybackState = {
  8778. loopMode: hmPlayMode,
  8779. };
  8780. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  8781. console.info(`set setLoopMode AVPlaybackState successfully`);
  8782. }).catch((err: BusinessError) => {
  8783. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  8784. });
  8785. }
  8786. }
  8787. setCurrentPlayMode() {
  8788. if (!this.avSessionController) {
  8789. return;
  8790. }
  8791. let mLoopMode = 0
  8792. switch (this.playType) {
  8793. case 0:
  8794. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  8795. break;
  8796. case 1:
  8797. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  8798. break;
  8799. case 2:
  8800. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  8801. break;
  8802. case 3:
  8803. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  8804. break;
  8805. }
  8806. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  8807. let playBState: avSession.AVPlaybackState = {
  8808. loopMode: mLoopMode,
  8809. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  8810. };
  8811. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  8812. console.info(`set setLoopMode AVPlaybackState successfully`);
  8813. }).catch((err: BusinessError) => {
  8814. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  8815. });
  8816. }
  8817. private sessionToggleFavoriteCallback = (assetId: string) => {
  8818. if (this.mIjkMediaPlayer != null && this.currentSong) {
  8819. console.info(`on toggleFavorite `);
  8820. // 应用收到收藏命令,进行收藏处理。
  8821. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  8822. this.doFav(this.currentSong)
  8823. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  8824. let playbackState: avSession.AVPlaybackState = {
  8825. isFavorite: !this.isFac,
  8826. };
  8827. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  8828. console.info(`SetAVPlaybackState successfully`);
  8829. }).catch((err: BusinessError) => {
  8830. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  8831. });
  8832. }
  8833. }
  8834. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  8835. device: avSession.OutputDeviceInfo) => {
  8836. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  8837. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  8838. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  8839. await this.startCasting();
  8840. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  8841. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  8842. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  8843. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  8844. if (device) {
  8845. this.endCasting();
  8846. }
  8847. }
  8848. };
  8849. private async startCasting() {
  8850. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  8851. this.setPlaybackStateChangeListener();
  8852. this.pause();
  8853. this.initQueueItem();
  8854. this.prepare();
  8855. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  8856. refToIsCasting?.set(true);
  8857. this.castSeek = true;
  8858. this.isCastPlaying = true;
  8859. }
  8860. async changeCasting() {
  8861. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  8862. this.initQueueItem();
  8863. this.prepare();
  8864. this.setPlaybackStateChangeListener();
  8865. this.isCastPlaying = true;
  8866. this.castSeek = true;
  8867. }
  8868. public endCasting() {
  8869. this.avSessionController.getAvSession()?.stopCasting();
  8870. this.stopCast();
  8871. this.isCastPlaying = false;
  8872. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  8873. refToIsCasting?.set(false);
  8874. this.pause();
  8875. this.setIsPlaying(false);
  8876. // if (this.curIndex === this.curSource.index) {
  8877. // this.play
  8878. // this.seek(this.currentTime * 1000);
  8879. // this.setIsPlaying(true);
  8880. // } else {
  8881. // this.pauseVideo();
  8882. // this.setIsPlaying(false);
  8883. // }
  8884. }
  8885. public setIsPlaying(isPlayer: boolean) {
  8886. this.isPlaying = isPlayer;
  8887. }
  8888. private setPlaybackStateChangeListener(): void {
  8889. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  8890. this.castController?.on('endOfStream', this.reloadCasting);
  8891. this.castController?.on('playNext', this.playNextCallback);
  8892. this.castController?.on('playPrevious', this.playPreviousCallback);
  8893. }
  8894. private updateSessionPlayState(isPlay: boolean): void {
  8895. // if(!this.isBgPlayOpen)
  8896. // return
  8897. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  8898. this.setAVSessionPlayState({
  8899. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  8900. position: {
  8901. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  8902. updateTime: new Date().getTime()
  8903. }
  8904. });
  8905. }
  8906. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  8907. this.avSessionController.setAvSessionPlayState(playbackState)
  8908. }
  8909. private positionChange(position: number) {
  8910. this.currentTime2 = position / 1000;
  8911. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  8912. }
  8913. private playDurationChange(duration: number) {
  8914. this.duration = duration;
  8915. this.durationTime = Math.floor(this.duration / 1000);
  8916. this.durationStringTime = secondToTime((this.durationTime));
  8917. }
  8918. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  8919. const duration = playbackState?.extras?.duration;
  8920. if (typeof duration === 'number') {
  8921. this.playDurationChange(duration as number);
  8922. }
  8923. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  8924. this.positionChange(playbackState?.position?.elapsedTime);
  8925. }
  8926. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  8927. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  8928. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  8929. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  8930. this.isCastPlaying = false;
  8931. }
  8932. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  8933. this.isCastPlaying = true;
  8934. }
  8935. };
  8936. private reloadCasting = async () => {
  8937. let item = this.songList[this.curIndex];
  8938. let uri = fileUri.getUriFromPath(item.filePath);
  8939. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  8940. // description.startPosition = 0;
  8941. this.castItem = {
  8942. itemId: this.curIndex,
  8943. description: {
  8944. assetId: item.filePath,
  8945. title: item.name,
  8946. artist: '',
  8947. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  8948. // mediaUri: item.filePath,
  8949. fdSrc: {
  8950. fd: file.fd
  8951. },
  8952. // 该字段大写,音频'AUDIO',视频'VIDEO'
  8953. mediaType: 'VIDEO',
  8954. mediaSize: item.videoSize,
  8955. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  8956. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  8957. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  8958. duration: this.duration,
  8959. // albumCoverUri: 'https://www.example.jpeg',
  8960. // albumTitle: '《ExampleAlbum》',
  8961. appName: this.appName,
  8962. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  8963. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  8964. }
  8965. };
  8966. this.prepare();
  8967. this.isCastPlaying = true;
  8968. };
  8969. public playNextCallback = (): void => {
  8970. this.playNext()
  8971. };
  8972. public playPreviousCallback = (): void => {
  8973. this.playPrevious()
  8974. };
  8975. async prepare() {
  8976. await this.castController?.prepare(this.castItem);
  8977. await this.castController?.start(this.castItem);
  8978. }
  8979. public initQueueItem() {
  8980. let item = this.songList[this.curIndex];
  8981. let time = this.currentTime;
  8982. let uri = fileUri.getUriFromPath(item.filePath);
  8983. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  8984. this.castItem = {
  8985. itemId: this.curIndex,
  8986. description: {
  8987. assetId: item.filePath,
  8988. title: item.name,
  8989. artist: '',
  8990. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  8991. fdSrc: {
  8992. fd: file.fd
  8993. },
  8994. // 该字段大写,音频'AUDIO',视频'VIDEO'
  8995. mediaType: 'AUDIO',
  8996. mediaSize: item.videoSize,
  8997. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  8998. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  8999. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  9000. duration: this.duration,
  9001. // albumCoverUri: 'https://www.example.jpeg',
  9002. // albumTitle: '《ExampleAlbum》',
  9003. appName: this.appName,
  9004. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  9005. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  9006. }
  9007. };
  9008. }
  9009. async stopCast() {
  9010. try {
  9011. this.castController?.off('playbackStateChange');
  9012. this.castController?.off('endOfStream');
  9013. this.castController?.off('playNext');
  9014. this.castController?.off('playPrevious');
  9015. this.castController?.off('error');
  9016. } catch (error) {
  9017. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  9018. }
  9019. }
  9020. private sessionPlayCallback = (): void => {
  9021. this.playOrPause()
  9022. };
  9023. private sessionPauseCallback = (): void => {
  9024. this.playOrPause()
  9025. };
  9026. private playOrPause() {
  9027. if (!this.debounce()) {
  9028. return;
  9029. }
  9030. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  9031. this.pause();
  9032. } else {
  9033. this.startPlayOrResumePlay();
  9034. this.playChange()
  9035. }
  9036. }
  9037. private sessionPlayNextCallback = (): void => {
  9038. this.playNext()
  9039. };
  9040. private sessionPlayPreviousCallback = (): void => {
  9041. this.playPrevious()
  9042. };
  9043. private sessionStopCallback = (): void => {
  9044. this.stop()
  9045. };
  9046. private sessionFastForwardCallback = (time?: number) => {
  9047. if (!time) {
  9048. return;
  9049. }
  9050. if (this.mIjkMediaPlayer != null) {
  9051. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  9052. let seeTime = curPosition + time * 1000;
  9053. // 限制 seekValue 在合法范围内
  9054. if (seeTime < 0) {
  9055. seeTime = 0;
  9056. } else if (seeTime > this.duration) {
  9057. seeTime = this.duration;
  9058. }
  9059. Logger.info('onecold seeTime= ' + seeTime)
  9060. this.setSeekToActionProgress(seeTime)
  9061. this.seekTo(seeTime + "")
  9062. }
  9063. };
  9064. /**
  9065. * Gesture method onActionUpdate.
  9066. *
  9067. * @param event Gesture event.手势拖动设置快进和后退
  9068. */
  9069. private setSeekToActionProgress(position: number) {
  9070. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  9071. let duration = this.mIjkMediaPlayer.getDuration();
  9072. let pos = 0;
  9073. if (duration > 0) {
  9074. this.slideEnable = true;
  9075. let curPercent = position / duration;
  9076. pos = curPercent * 100;
  9077. if (pos > this.PROGRESS_MAX_VALUE) {
  9078. this.progressValue = this.PROGRESS_MAX_VALUE
  9079. } else {
  9080. this.progressValue = pos;
  9081. }
  9082. }
  9083. // LogUtils.getInstance()
  9084. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  9085. this.totalTime = this.stringForTime(duration);
  9086. if (position > duration) {
  9087. position = duration;
  9088. }
  9089. this.isCurrentTime = true;
  9090. this.currentTime = this.stringForTime(position);
  9091. this.isCurrentTime = false
  9092. }
  9093. private sessionRewindCallback = (time?: number) => {
  9094. if (!time) {
  9095. return;
  9096. }
  9097. if (this.mIjkMediaPlayer != null) {
  9098. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  9099. let seeTime = curPosition - time * 1000;
  9100. // 限制 seekValue 在合法范围内
  9101. if (seeTime < 0) {
  9102. seeTime = 0;
  9103. } else if (seeTime > this.duration) {
  9104. seeTime = this.duration;
  9105. }
  9106. Logger.info('onecold seeTime= ' + seeTime)
  9107. this.setSeekToActionProgress(seeTime)
  9108. this.seekTo(seeTime + "")
  9109. }
  9110. };
  9111. private sessionSeekCallback = (seekTime: number) => {
  9112. if (this.mIjkMediaPlayer != null) {
  9113. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  9114. this.seekTo(seekTime + "")
  9115. }
  9116. };
  9117. private async getFileSize(filePath: string): Promise<number> {
  9118. try {
  9119. const stat = await fs.stat(filePath);
  9120. return stat.size;
  9121. } catch (err) {
  9122. console.error('Failed to get file size: ' + err.message);
  9123. return 0;
  9124. }
  9125. }
  9126. private pause() {
  9127. if (this.mIjkMediaPlayer.isPlaying()) {
  9128. this.savePlaybackPosition();
  9129. this.mIjkMediaPlayer.pause();
  9130. this.setProgress();
  9131. this.mDestroyPage = true;
  9132. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  9133. this.updateSessionPlayState(false)
  9134. this.playChange()
  9135. if (this.pipController) {
  9136. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  9137. PiPWindow.PiPControlStatus.PAUSE);
  9138. }
  9139. }
  9140. }
  9141. private stop() {
  9142. this.savePlaybackPosition();
  9143. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9144. this.mIjkMediaPlayer.stop();
  9145. this.mIjkMediaPlayer.release();
  9146. this.stopProgressTask();
  9147. this.updateSessionPlayState(false)
  9148. this.playChange()
  9149. this.watchStatus();
  9150. }
  9151. //保持记忆播放功能
  9152. private savePlaybackPosition() {
  9153. if (this.mIjkMediaPlayer != null) {
  9154. const position = this.mIjkMediaPlayer.getCurrentPosition();
  9155. // ToastUtil.showToast('保存记忆播放 = ' + position)
  9156. const duration = this.mIjkMediaPlayer.getDuration();
  9157. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  9158. // 如果播放位置接近视频末尾,则保存 position 为 0
  9159. const playbackPosition = (duration - position < threshold) ? 0 : position;
  9160. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  9161. }
  9162. }
  9163. //获取记忆播放功能
  9164. private restorePlaybackPosition() {
  9165. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  9166. // ToastUtil.showToast('position = ' + position)
  9167. if (this.mIjkMediaPlayer != null && position > 0) {
  9168. // ToastUtil.showToast('seekTo = ' + position)
  9169. this.seekTo(position + "");
  9170. }
  9171. }
  9172. private seekTo(value: string) {
  9173. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  9174. ToastUtil.showToast('wma格式不支持拖动快进。')
  9175. return
  9176. }
  9177. this.mIjkMediaPlayer.seekTo(value);
  9178. // this.startPlayOrResumePlay()
  9179. // 在这里恢复计时器状态
  9180. this.setProgress()
  9181. // this.startProgressTask();
  9182. }
  9183. // 添加到下一首播放
  9184. private addToNextPlay(song: VideoItem) {
  9185. if (!this.debounce()) {
  9186. return;
  9187. }
  9188. if (this.currentSong) {
  9189. if (this.currentSong === song) {
  9190. ToastUtil.showToast('当前已经在播放这首歌了!')
  9191. return
  9192. }
  9193. }
  9194. // 如果未开始播放或队列为空
  9195. if (this.curIndex === -1 || this.songList.length === 0) {
  9196. this.songList = [song];
  9197. this.curIndex = 0;
  9198. this.doPlay(song)
  9199. return;
  9200. }
  9201. // 插入到当前索引+1的位置
  9202. const insertPos = this.curIndex + 1;
  9203. this.songList.splice(insertPos, 0, song);
  9204. this.songList = [...this.songList]; // 触发状态更新
  9205. this.sonDataSource.pushArrayData(this.songList)
  9206. ToastUtil.showToast('已添加至下一首播放')
  9207. }
  9208. //下一个
  9209. private playNext() {
  9210. if (!this.debounce()) {
  9211. return;
  9212. }
  9213. if (this.playType == 3) { //3:随机播放
  9214. this.randomPlay()
  9215. return;
  9216. }
  9217. if (ArrayUtil.isNotEmpty(this.songList)) {
  9218. if (this.curIndex == this.songList.length - 1) {
  9219. this.curIndex = 0;
  9220. } else {
  9221. this.curIndex++;
  9222. }
  9223. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9224. this.stop();
  9225. this.currentSong = this.songList[this.curIndex]
  9226. this.videoUrl = this.songList[this.curIndex].filePath;
  9227. //this.cover = this.songList[this.curIndex].pixelMapPath
  9228. this.changeImageAnimation()
  9229. this.artist = this.songList[this.curIndex].artist
  9230. this.name = this.songList[this.curIndex].name
  9231. this.startPlayOrResumePlay()
  9232. }
  9233. }
  9234. changeImageAnimation() {
  9235. // 第一步:淡出动画
  9236. this.getUIContext()?.animateTo({
  9237. duration: 500,
  9238. curve: Curve.EaseOut,
  9239. }, () => {
  9240. this.opacityValueImage = 0.3;
  9241. if(this.isCoverRectangle){
  9242. this.scaleValueImage = 0.88
  9243. }
  9244. });
  9245. // 第二步:切换图片后淡入
  9246. setTimeout(() => {
  9247. this.cover = this.songList[this.curIndex].pixelMapPath
  9248. this.getUIContext()?.animateTo({
  9249. duration: 500,
  9250. curve: Curve.EaseIn,
  9251. }, () => {
  9252. this.opacityValueImage = 1;
  9253. this.scaleValueImage = 1 // 图标恢复到原始大小
  9254. });
  9255. }, 500);
  9256. }
  9257. // 存储已播放的歌曲索引
  9258. private playedIndices: Set<number> = new Set();
  9259. //随机播放
  9260. private randomPlay() {
  9261. // if (!this.debounce()) {
  9262. // return;
  9263. // }
  9264. if (ArrayUtil.isNotEmpty(this.songList)) {
  9265. if (this.songList.length > 3) {
  9266. // 如果所有歌曲都播放过一次,清空已播放索引集合
  9267. if (this.playedIndices.size === this.songList.length) {
  9268. this.playedIndices.clear();
  9269. }
  9270. // 随机选择一个未播放的歌曲索引
  9271. let newIndex: number;
  9272. // 添加超时机制防止无限循环
  9273. let attempt = 0;
  9274. const maxAttempts = 100; // 根据需求调整
  9275. do {
  9276. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  9277. attempt++;
  9278. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  9279. if (attempt >= maxAttempts) {
  9280. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  9281. newIndex = Math.floor(Math.random() * this.songList.length);
  9282. }
  9283. this.curIndex = newIndex;
  9284. this.playedIndices.add(newIndex);
  9285. } else {
  9286. // 当歌曲数量小于或等于3时,直接播放下一首
  9287. if (this.curIndex == this.songList.length - 1) {
  9288. this.curIndex = 0;
  9289. } else {
  9290. this.curIndex++;
  9291. }
  9292. }
  9293. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9294. this.stop();
  9295. this.currentSong = this.songList[this.curIndex];
  9296. this.videoUrl = this.songList[this.curIndex].filePath;
  9297. this.name = this.songList[this.curIndex].name;
  9298. // this.cover = this.songList[this.curIndex].pixelMapPath
  9299. this.changeImageAnimation()
  9300. this.artist = this.songList[this.curIndex].artist
  9301. this.startPlayOrResumePlay();
  9302. }
  9303. }
  9304. private playIndex(index: number) {
  9305. if (!this.debounce()) {
  9306. return;
  9307. }
  9308. if (ArrayUtil.isNotEmpty(this.songList)) {
  9309. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9310. this.stop();
  9311. this.currentSong = this.songList[this.curIndex]
  9312. this.videoUrl = this.songList[index].filePath;
  9313. this.name = this.songList[index].name
  9314. this.changeImageAnimation()
  9315. this.artist = this.songList[this.curIndex].artist
  9316. this.curIndex = index;
  9317. this.startPlayOrResumePlay()
  9318. }
  9319. }
  9320. //上一个
  9321. private playPrevious() {
  9322. if (!this.debounce()) {
  9323. return;
  9324. }
  9325. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  9326. this.randomModePlayFromHistory()
  9327. return;
  9328. }
  9329. if (this.curIndex == 0) {
  9330. this.curIndex = this.songList.length - 1;
  9331. } else {
  9332. this.curIndex--;
  9333. }
  9334. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9335. this.stop();
  9336. this.currentSong = this.songList[this.curIndex]
  9337. this.videoUrl = this.songList[this.curIndex].filePath;
  9338. this.name = this.songList[this.curIndex].name
  9339. this.changeImageAnimation()
  9340. // this.cover = this.songList[this.curIndex].pixelMapPath
  9341. this.artist = this.songList[this.curIndex].artist
  9342. this.startPlayOrResumePlay()
  9343. }
  9344. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  9345. private randomModePlayFromHistory() {
  9346. if (this.historyList.length >= 2) {
  9347. // 播放历史记录的第二首
  9348. const prevSong = this.historyList[1];
  9349. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  9350. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9351. this.stop();
  9352. this.currentSong = prevSong;
  9353. this.videoUrl = prevSong.filePath;
  9354. this.cover = prevSong.pixelMapPath
  9355. this.artist = prevSong.artist
  9356. this.name = prevSong.name;
  9357. this.startPlayOrResumePlay();
  9358. } else {
  9359. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  9360. if (this.curIndex === 0) {
  9361. this.curIndex = this.songList.length - 1;
  9362. } else {
  9363. this.curIndex--;
  9364. }
  9365. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9366. this.stop();
  9367. this.currentSong = this.songList[this.curIndex];
  9368. this.videoUrl = this.songList[this.curIndex].filePath;
  9369. this.changeImageAnimation()
  9370. // this.cover = this.songList[this.curIndex].pixelMapPath
  9371. this.artist = this.songList[this.curIndex].artist
  9372. this.name = this.songList[this.curIndex].name;
  9373. this.startPlayOrResumePlay();
  9374. }
  9375. }
  9376. debounce() {
  9377. const delay = 600;
  9378. let cur = new Date().getTime();
  9379. if (cur - this.last > delay) {
  9380. this.last = cur;
  9381. return true;
  9382. }
  9383. return false;
  9384. }
  9385. /**
  9386. * Sets whether the screen is a constant based on the playback status.
  9387. */
  9388. watchStatus() {
  9389. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  9390. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  9391. this.windowClass.setWindowKeepScreenOn(true);
  9392. } else {
  9393. this.windowClass.setWindowKeepScreenOn(false);
  9394. }
  9395. }
  9396. /**
  9397. * Volume gesture method onActionStart.
  9398. *
  9399. * @param event Gesture event.
  9400. */
  9401. private customDialogComponentIdMM: number = 0
  9402. @Builder
  9403. customDialogComponentMM() {
  9404. Column() {
  9405. Row() {
  9406. Blank()
  9407. Text('验证密码')
  9408. .fontSize(22)
  9409. .fontColor($r('app.color.pri_bg'))
  9410. .margin({ top: 18 })
  9411. Blank()
  9412. Image($r('app.media.close'))
  9413. .fillColor(Color.White)
  9414. .margin({ top: 18, right: 18 })
  9415. .width(20)
  9416. .onClick(() => {
  9417. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  9418. })
  9419. }
  9420. .width('100%') // 使Row占据整个宽度
  9421. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  9422. Verify({
  9423. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  9424. });
  9425. }.height('60%')
  9426. .backgroundColor($r('app.color.index_background'))
  9427. .justifyContent(FlexAlign.SpaceBetween)
  9428. }
  9429. private handleVerifyCompleted(isSuccess: boolean) {
  9430. if (isSuccess) {
  9431. console.log('验证成功');
  9432. // 在这里处理验证成功后的逻辑
  9433. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  9434. this.currentPath = this.lockPath
  9435. this.getSortedFiles(this.currentPath)
  9436. } else {
  9437. // console.log('验证失败');
  9438. ToastUtil.showToast('验证失败')
  9439. }
  9440. }
  9441. private showVerifyDialog() {
  9442. promptAction.openCustomDialog({
  9443. transition: TransitionEffect.asymmetric(
  9444. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  9445. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  9446. ,
  9447. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  9448. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  9449. ),
  9450. builder: () => {
  9451. this.customDialogComponentMM()
  9452. },
  9453. isModal: true,
  9454. autoCancel: true,
  9455. maskColor: Color.Transparent,
  9456. alignment: DialogAlignment.Bottom,
  9457. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  9458. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  9459. console.log("dialog onWillDismiss")
  9460. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  9461. dismissDialogAction.dismiss()
  9462. }
  9463. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  9464. dismissDialogAction.dismiss()
  9465. }
  9466. }
  9467. }).then((dialogId: number) => {
  9468. this.customDialogComponentIdMM = dialogId
  9469. })
  9470. }
  9471. //左滑操作 移动文件 重命名 删除等操作
  9472. @Builder
  9473. DeleteButton(item: VideoItem, index: number, filePath: string) {
  9474. Row() {
  9475. //加入收藏
  9476. Button() {
  9477. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  9478. .fillColor(Color.White)
  9479. .width(20)
  9480. }
  9481. .width(40)
  9482. .height(40)
  9483. .type(ButtonType.Circle)
  9484. .backgroundColor(this.themeColor)
  9485. .margin(5)
  9486. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  9487. .onClick(() => {
  9488. if (item) {
  9489. this.doFav(item)
  9490. }
  9491. })
  9492. //加入下一首播放
  9493. Button() {
  9494. Image($r('app.media.next_to_play'))
  9495. .fillColor(Color.White)
  9496. .width(20)
  9497. }
  9498. .width(40)
  9499. .height(40)
  9500. .type(ButtonType.Circle)
  9501. .backgroundColor(this.themeColor)
  9502. .margin(5)
  9503. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  9504. .onClick(() => {
  9505. this.addToNextPlay(item);
  9506. })
  9507. //复制文件
  9508. Button() {
  9509. Image($r('app.media.copy'))
  9510. .fillColor(Color.White)
  9511. .width(20)
  9512. }
  9513. .width(40)
  9514. .height(40)
  9515. .type(ButtonType.Circle)
  9516. .backgroundColor(this.themeColor)
  9517. .margin(5)
  9518. .id(filePath + 'copy')
  9519. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  9520. .onClick(() => {
  9521. this.showCopyDialog(false, item, index, filePath + 'copy');
  9522. })
  9523. //移动文件
  9524. Button() {
  9525. Image($r('app.media.cut'))
  9526. .fillColor(Color.White)
  9527. .width(20)
  9528. }
  9529. .width(40)
  9530. .height(40)
  9531. .type(ButtonType.Circle)
  9532. .backgroundColor(this.themeColor)
  9533. .margin(5)
  9534. .id(filePath)
  9535. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  9536. .onClick(() => {
  9537. this.showCutDialog(false, item, index, filePath);
  9538. })
  9539. Button() {
  9540. Image($r('app.media.cut_current'))
  9541. .fillColor(Color.White)
  9542. .width(20)
  9543. }
  9544. .width(40)
  9545. .height(40)
  9546. .type(ButtonType.Circle)
  9547. .backgroundColor(this.themeColor)
  9548. .margin(5)
  9549. .id(filePath + 'current')
  9550. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  9551. (this.isHasDir ? Visibility.Visible : Visibility.None))
  9552. .onClick(() => {
  9553. this.showCutDialog(true, item, index, filePath + 'current');
  9554. })
  9555. //重命名
  9556. Button() {
  9557. Image($r('app.media.rename2'))
  9558. .fillColor(Color.White)
  9559. .width(20)
  9560. }
  9561. .width(40)
  9562. .height(40)
  9563. .type(ButtonType.Circle)
  9564. .backgroundColor(this.themeColor)
  9565. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  9566. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  9567. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  9568. .margin(5)
  9569. .onClick(() => {
  9570. this.showReNameDialog(item, index + '', filePath)
  9571. })
  9572. Button() {
  9573. Image($r('app.media.delete2'))
  9574. .fillColor(Color.White)
  9575. .width(20)
  9576. }
  9577. .width(40)
  9578. .height(40)
  9579. .type(ButtonType.Circle)
  9580. .backgroundColor(this.themeColor)
  9581. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  9582. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  9583. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  9584. .margin(5)
  9585. .onClick(() => {
  9586. this.showWarnIsDeleteFile(item, index + '', filePath)
  9587. })
  9588. Button() {
  9589. Image($r('app.media.share2'))
  9590. .fillColor(Color.White)
  9591. .width(20)
  9592. }
  9593. .width(40)
  9594. .height(40)
  9595. .type(ButtonType.Circle)
  9596. .backgroundColor(this.themeColor)
  9597. .margin(5)
  9598. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  9599. .onClick(() => {
  9600. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  9601. })
  9602. }
  9603. }
  9604. /**
  9605. * 穿山甲banner广告
  9606. */
  9607. // private declare bannerAd: CSJNativeExpressAd;
  9608. // @State private status: string = "未加载"
  9609. // @State private isShowAd: boolean = false
  9610. // private declare mAdSlot: AdSlot;
  9611. // private mBiddingAdm = '' //服务端bidding才需要设置
  9612. // private expressLoadAdListener: NativeExpressAdListener = {
  9613. // /**
  9614. // * 加载失败的回调
  9615. // *
  9616. // * @param code
  9617. // * @param message
  9618. // */
  9619. // onError: (code: number, message: string) => {
  9620. // console.error("加载广告失败,code=" + code + ",message=" + message);
  9621. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  9622. // },
  9623. //
  9624. // /**
  9625. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  9626. // *
  9627. // * @param ads 返回的广告列表
  9628. // */
  9629. //
  9630. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  9631. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  9632. // if (ads && ads.length > 0) {
  9633. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  9634. // ad.setExpressInteractionListener({
  9635. // /**
  9636. // *广告的点击回调
  9637. // * @param type 广告的交互类型
  9638. // */
  9639. // onAdClicked: (type: number) => {
  9640. // console.log("BannerExpressAdPage==onAdClicked......");
  9641. // },
  9642. //
  9643. // /**
  9644. // * 广告的展示回调 每个广告仅回调一次
  9645. // * @param type 广告的交互类型
  9646. // */
  9647. // onAdShow: (type: number) => {
  9648. // console.log("BannerExpressAdPage==onAdShow......");
  9649. // },
  9650. //
  9651. // /**
  9652. // * 模板渲染失败
  9653. // */
  9654. // onRenderFail: (code: number, msg: string) => {
  9655. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  9656. // },
  9657. //
  9658. // /**
  9659. // * 模板渲染成功
  9660. // * @param width 返回view的宽 单位 vp
  9661. // * @param height 返回view的高 单位 vp
  9662. // */
  9663. // onRenderSuccess: (width: number, height: number) => {
  9664. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  9665. // this.bannerAd = ad;
  9666. // this.status = "广告加载完成待展示";
  9667. //
  9668. // this.showBannerAd()
  9669. // }
  9670. // })
  9671. // //渲染广告
  9672. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  9673. // this.setDislikeCallback(ad); //设置dislike
  9674. // ad.render(this.getUIContext())
  9675. // this.status = "广告加载中...";
  9676. // });
  9677. // }
  9678. // }
  9679. // }
  9680. //
  9681. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  9682. // ad.setDislikeCallback({
  9683. // /**
  9684. // * dislike show
  9685. // */
  9686. // onShow: () => {
  9687. // console.log("BannerExpressAdPage==dislike......show");
  9688. // },
  9689. //
  9690. // /**
  9691. // * @param position 选择的位置
  9692. // * @param value 选择的内容
  9693. // * @param enforceRemove 是否强制关闭广告
  9694. // */
  9695. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  9696. // this.isShowAd = false;
  9697. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  9698. // ",enforce=" + enforceRemove);
  9699. // },
  9700. //
  9701. // /**
  9702. // * 点击取消
  9703. // */
  9704. // onCancel: () => {
  9705. // console.log("BannerExpressAdPage==dislike......onCancel");
  9706. // }
  9707. //
  9708. // })
  9709. // }
  9710. /**
  9711. * 加载Banner广告
  9712. */
  9713. loadBannerAd(rit: string) {
  9714. // if (Utility.isNoble()) {
  9715. // return
  9716. // }
  9717. // if (!Utility.isPassInstallTime(2)) {
  9718. // return
  9719. // }
  9720. // this.isShowAd = false;
  9721. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  9722. // this.mAdSlot = new AdSlotBuilder()
  9723. // .setCodeId(rit)
  9724. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  9725. // .setAdCount(1)
  9726. // .setBidAdm(this.mBiddingAdm)
  9727. // .build()
  9728. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  9729. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  9730. // this.status = "广告加载中..."
  9731. }
  9732. /**
  9733. * 展示Banner广告
  9734. */
  9735. // showBannerAd() {
  9736. // if (!this.bannerAd) {
  9737. // return
  9738. // }
  9739. // this.isShowAd = true
  9740. // this.status = "已展示"
  9741. // }
  9742. /**
  9743. * 穿山甲广告代码结束
  9744. */
  9745. }
  9746. //视频气泡窗口的布局
  9747. @Builder
  9748. function customPopupBuilder(dataBu: BubbleBean) {
  9749. List() {
  9750. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  9751. ListItem() {
  9752. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9753. Row() {
  9754. Column() {
  9755. Image(dataBu.imageRes[index])
  9756. .height(28)
  9757. .fillColor(dataBu.color)
  9758. .alignSelf(ItemAlign.Center)
  9759. }
  9760. .width(32)
  9761. Text(item)
  9762. .padding({
  9763. top: 10,
  9764. bottom: 10,
  9765. right: 10,
  9766. left: 10
  9767. })
  9768. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  9769. .textAlign(TextAlign.Start)
  9770. .width("100%")
  9771. }
  9772. }
  9773. .backgroundColor($r('app.color.settings_background_main'))
  9774. .margin({ top: 6, bottom: 6 })
  9775. }
  9776. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  9777. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  9778. TransitionEffect.scale({ x: 0, y: 0 })))
  9779. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  9780. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  9781. .onClick(() => {
  9782. dataBu.onItemClick?.(index)
  9783. })
  9784. })
  9785. }
  9786. .width(120)
  9787. .divider({
  9788. strokeWidth: 1,
  9789. color: "#22FFFFFF"
  9790. })
  9791. }
  9792. // Function to calculate a hash for the file list
  9793. function simpleHash(fileList: string[]): string {
  9794. let hash = 0;
  9795. const str = fileList.join(',');
  9796. for (let i = 0; i < str.length; i++) {
  9797. const char = str.charCodeAt(i);
  9798. hash = (hash << 5) - hash + char;
  9799. hash |= 0; // Convert to 32bit integer
  9800. }
  9801. return hash.toString();
  9802. }
  9803. interface MoreItem {
  9804. id: number;
  9805. image: Resource;
  9806. title: string;
  9807. }
  9808. //视频气泡窗口的布局
  9809. @Builder
  9810. function cutPopupBuilder(dataBu: BubbleBean) {
  9811. Column() {
  9812. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  9813. .padding({
  9814. top: 10,
  9815. bottom: 10,
  9816. right: 10,
  9817. left: 10
  9818. })
  9819. .textAlign(TextAlign.Start)
  9820. .width(160)
  9821. .fontWeight(666)
  9822. .fontSize(16)
  9823. List() {
  9824. ForEach(dataBu.data, (item: string, index: number) => {
  9825. ListItem() {
  9826. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9827. Row() {
  9828. Column() {
  9829. Image($r('app.media.music_group'))
  9830. .height(28)
  9831. .fillColor(dataBu.color)
  9832. .alignSelf(ItemAlign.Center)
  9833. }
  9834. .width(32)
  9835. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  9836. .padding({
  9837. top: 10,
  9838. bottom: 10,
  9839. right: 10,
  9840. left: 10
  9841. })
  9842. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  9843. .fontSize(15)
  9844. }
  9845. }
  9846. .backgroundColor(Color.Transparent)
  9847. .margin({ top: 7, bottom: 7 })
  9848. }
  9849. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  9850. .animation({ duration: 500 }),
  9851. TransitionEffect.scale({ x: 0, y: 0 })))
  9852. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  9853. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  9854. .onClick(() => {
  9855. dataBu.onItemClick?.(index)
  9856. })
  9857. })
  9858. }
  9859. .width(150)
  9860. .divider({
  9861. strokeWidth: 1,
  9862. color: "#22FFFFFF"
  9863. })
  9864. }
  9865. .height(300)
  9866. .padding({
  9867. bottom: 30
  9868. })
  9869. }