LocalMusic.ets 334 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033
  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 { CommonConstants } from '../common/constants/CommonConstants';
  21. import Logger from '../common/util/Logger';
  22. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  23. import { Utility } from '../common/util/Utility';
  24. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  25. import { uniformTypeDescriptor } from '@kit.ArkData';
  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 { SettingPage } from '../pages/SettingPage';
  60. import { secondToTime } from '../common/util/CommUtils';
  61. import { CommonConstants2 } from '../common/util/CommonConstants2';
  62. import { hilog } from '@kit.PerformanceAnalysisKit';
  63. import { LazyDataSource } from '../common/util/LazyDataSource';
  64. import MediaTable from '../common/util/MediaTable';
  65. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  66. import ImageUtils from '../common/util/ImageUtils';
  67. import { ringtone } from '@kit.RingtoneKit';
  68. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  69. import { resourceManager } from '@kit.LocalizationKit';
  70. import { deviceInfo } from '@kit.BasicServicesKit';
  71. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  72. import { LrcParser } from '@sgaolei/lrc_parser';
  73. import app from '@system.app';
  74. import { TextNodeController } from './PipLyricTextBuilder';
  75. import { IndexerView } from './IndexerView';
  76. const TAG = 'LocalMusic';
  77. const DEFAULT_INDEX = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  78. //排序类型
  79. function getTypeOrder(type: number) {
  80. switch (type) {
  81. case CommonConstants.TYPE_IS_DIR:
  82. return 1; // First
  83. case CommonConstants.TYPE_IS_CSJAD:
  84. return 2; // Middle
  85. case CommonConstants.TYPE_LOCAL:
  86. return 3; // Last
  87. default:
  88. return 4; // Unknown types, if any, go last
  89. }
  90. }
  91. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  92. interface GeneratedObjectLiteralInterface_1 {
  93. assetId: string;
  94. title: string;
  95. artist: string;
  96. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  97. mediaUri: string;
  98. // 该字段大写,音频'AUDIO',视频'VIDEO'
  99. mediaType: string;
  100. mediaSize: number;
  101. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  102. startPosition: number;
  103. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  104. duration: number;
  105. albumCoverUri: string;
  106. albumTitle: string;
  107. appName: string;
  108. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  109. drmScheme: string;
  110. }
  111. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  112. const ITEM_HEIGHT: number = 58; // 列表项中高度
  113. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  114. //功能强大的音乐播放器
  115. @Preview
  116. @Component
  117. export struct LocalMusic {
  118. @StorageProp('themeColor') themeColor: string = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  119. themeMode: number=0;
  120. @State titleName: string = '首页'
  121. @State textStr: string = ''
  122. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  123. // private download_path: string = '';
  124. @Consume rootPath: string //音频根目录
  125. @Consume currentPath: string
  126. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  127. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  128. @State lockPath: string = ''
  129. @State favPath: string = ''
  130. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  131. @State historyPath: string = ''
  132. @State historyList: Array<VideoItem> = []
  133. @Consume isHistory: boolean
  134. static readonly HISTORY_MUSIC: string = 'music_historyList';
  135. private table: MediaTable = new MediaTable(getContext(this))
  136. @State isZero: boolean = false
  137. @State fileList: Array<string> = []
  138. @State dirList: Array<VideoItem> = []
  139. @Consume videoLocalList: Array<VideoItem>
  140. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  141. @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  142. @State artistList: Array<VideoItem> = []; //艺术家文件
  143. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  144. @State albumList: Array<VideoItem> = []; //专辑文件
  145. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  146. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  147. @State imageOpacities: number[] = [];
  148. @Consume isCanBack: boolean
  149. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  150. @State showSingleLyric: boolean = false
  151. @State sortType: number = 4 //默认排序方式
  152. @State isShowSimi:boolean = false //是否显示私密音频
  153. @State isShowFAV:boolean = true //是否显示我的收藏
  154. @State isShowTitleBar: boolean = true //是否显示分类导航条
  155. @State isShowAllBar: boolean = true //是否显示播放全部条
  156. @State isShowHistory:boolean = true //是否显示最近播放
  157. @State isCustomizeBg: boolean = false //自定义背景界面
  158. @State isGridMusic: boolean = false //是否网格布局
  159. @State isCircleBtn: boolean = false //是否圆形播放按钮
  160. @State twoFingerType: number = 3 //双支放大缩小的类型
  161. @State isScrollHide: boolean = false //是否滚动隐藏
  162. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  163. @State isStartAutoPlay: boolean = false //启动后自动播放
  164. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  165. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  166. @State isCoverTopBig: boolean = false//顶部大封面部分手机显示会和播放控制页重叠
  167. @State customizeBgPath: string | undefined = '';
  168. @State isDarkMode: boolean = false
  169. @State lyricTextWeight: number = 400
  170. @State lyricTextWeightPip: number = 400
  171. @State currentSwiperIndex: number = 0
  172. @State blurValue: number = 0 //背景模糊
  173. @State bgBrightness: number = 0 //背景亮度
  174. private listScroller: ListScroller = new ListScroller()
  175. private playListScroller: Scroller = new Scroller()
  176. @StorageProp('isLandscape') isLandscape: boolean = false;
  177. @StorageProp('topRectHeight') topRectHeight: number = px2vp(AppUtil.getStatusBarHeight());
  178. private listArea: Area = {
  179. width: 0,
  180. height: 0,
  181. position: {},
  182. globalPosition: {}
  183. }
  184. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  185. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  186. onColorModeChange() {
  187. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  188. if(this.isCustomizeBg){
  189. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  190. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  191. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  192. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  193. }else{
  194. if (!this.isDarkMode) {
  195. this.titleBarModel.setTitleBarBackground(this.themeColor)
  196. this.titleBarModel .setTitleBarBottomLineColor(this.themeColor)
  197. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  198. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  199. }else {
  200. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  201. this.titleBarModel .setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  202. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  203. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  204. }
  205. }
  206. }
  207. onModeChange() {
  208. this.isFavMusic = false
  209. if (this.modeType === 2 || this.modeType === 3) {
  210. this.titleBarModel.setRightIcon(null)
  211. } else {
  212. this.titleBarModel.setRightIcon(($r('app.media.add')))
  213. }
  214. LogUtil.info('onecold onModeChange = ' + this.modeType)
  215. switch (this.modeType) {
  216. case 0:
  217. this.getSortedFiles(this.currentPath)
  218. break
  219. case 1:
  220. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  221. this.updateListData(this.mediaKuList)
  222. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  223. break
  224. case 2:
  225. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  226. this.updateListData(this.artistList)
  227. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  228. break
  229. case 3:
  230. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  231. this.updateListData(this.albumList)
  232. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  233. break
  234. }
  235. }
  236. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  237. // @StorageLink('isPlay') isPlay: boolean = false;
  238. @StorageLink('isShowPlay') isShowPlay: boolean = false;
  239. @StorageProp('windowHeight') windowHeight: number = 0;
  240. @StorageLink('songList') songList: Array<VideoItem> = [];
  241. @State translateY: number = 0;
  242. @State isShowSheet: boolean = false;
  243. @State isShowSheetView: boolean = false;
  244. @State isShowTimeCloseView: boolean = false;
  245. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  246. @StorageLink('currIndex') curIndex: number = 0;
  247. @Consume isShowDrawer: boolean;
  248. @Consume offsetX: number;
  249. @State isFac: boolean = false;
  250. @State favList: Array<VideoItem>= []
  251. @Consume isFavMusic:boolean
  252. @State isClickedPLayAll: boolean = false;
  253. private scrollerForlist: ListScroller = new ListScroller();
  254. imagesF: ImageFrameInfo[] = [
  255. { src: $r("app.media.app_loading0") },
  256. { src: $r("app.media.app_loading1") },
  257. { src: $r("app.media.app_loading2") },
  258. { src: $r("app.media.app_loading3") },
  259. ]
  260. @State animationState: AnimationStatus = AnimationStatus.Initial
  261. // 缓存机制
  262. private cache: Map<string, Array<VideoItem>> = new Map();
  263. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  264. // 持久化缓存
  265. private async saveCacheToStorage() {
  266. const cacheArray = Array.from(this.cache.entries());
  267. const stringCacheArray = Array.from(this.stringCache.entries());
  268. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  269. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  270. }
  271. // 载入缓存
  272. private async loadCacheFromStorage() {
  273. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  274. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  275. if (cacheString) {
  276. const cacheArray: [string, Array<VideoItem>][] = JSON.parse(cacheString);
  277. this.cache = new Map(cacheArray);
  278. }
  279. if (stringCacheString) {
  280. const stringCacheArray: [string, string][] = JSON.parse(stringCacheString);
  281. this.stringCache = new Map(stringCacheArray);
  282. }
  283. }
  284. // 查找缓存
  285. private findCache(key: string): Array<VideoItem> | undefined {
  286. return this.cache.get(key);
  287. }
  288. // 查找字符串缓存
  289. private findStringCache(key: string): string | undefined {
  290. return this.stringCache.get(key);
  291. }
  292. // 添加缓存
  293. private addCache(key: string, value: Array<VideoItem>) {
  294. this.cache.set(key, value);
  295. }
  296. // 添加字符串缓存
  297. private addStringCache(key: string, value: string) {
  298. this.stringCache.set(key, value);
  299. }
  300. // 删除缓存
  301. private deleteCache(key: string) {
  302. this.cache.delete(key);
  303. this.saveCacheToStorage()
  304. }
  305. // 删除字符串缓存
  306. private deleteStringCache(key: string) {
  307. this.stringCache.delete(key);
  308. }
  309. // 多选机制
  310. @State selectedFiles: Array<VideoItem> = [];
  311. @State isMultiSelect: boolean = false;
  312. @State isAllSelected: boolean = false;
  313. @State appName: string = ''
  314. @State isHasDir: boolean = false
  315. @State packName: string = ''
  316. context = getContext(this);
  317. @State titleBarModel: TitleBar.Model = new TitleBar.Model()
  318. .setTitleTextStyle(FontStyle.Normal)
  319. .setTitleBarStyle(TitleBar.BarStyle.TRANSPARENT)
  320. .setLeftIcon($r('app.media.menu'))
  321. .setLeftIconWidth(25)
  322. .setLeftIconHeight(25)
  323. .setTitleName('首页')
  324. .setTitleFontSize(18)
  325. .setTitleFontColor(Color.White)
  326. .setTitleBarBackground(this.isDarkMode?$r('app.color.title_bar_bg'):this.themeColor)
  327. .setTitleBarBottomLineColor(this.isDarkMode?$r('app.color.title_bar_bg'):this.themeColor)
  328. .setLeftTitleStateNormalStyleColor(this.isDarkMode?$r('app.color.title_bar_bg'):this.themeColor)
  329. .setRightIcon($r('app.media.add'))
  330. .setOnRightClickListener(() => {
  331. this.showSheelDialog()
  332. })
  333. .setOnTitleClickListener(() => {
  334. this.showPupDialog()
  335. })
  336. .setOnLeftClickListener(() => {
  337. this.doSwipBack()
  338. })
  339. doSwipBack() {
  340. if (this.modeType !== 0 && this.isCanBack) {
  341. this.onModeChange()
  342. this.isCanBack = false
  343. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  344. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  345. setTimeout(() => {
  346. if(this.modeType ==2){
  347. if (this.isGridMusic) {
  348. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  349. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  350. } else {
  351. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  352. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  353. }
  354. }else if(this.modeType ==3){
  355. if (this.isGridMusic) {
  356. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  357. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  358. } else {
  359. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  360. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  361. }
  362. }
  363. }, 200)
  364. return
  365. }
  366. if (this.isHistory||this.isFavMusic) {
  367. this.isHistory = false
  368. this.getSortedFiles(this.currentPath)
  369. return
  370. }
  371. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  372. animateTo({ duration: 555 }, () => {
  373. // 动画闭包内控制Image组件的出现和消失
  374. this.isShowDrawer = true
  375. this.offsetX = 0
  376. })
  377. return
  378. }
  379. this.currentPath = Utility.getParentDirectory(this.currentPath)
  380. Logger.info('this.currentPath2 = ' + this.currentPath)
  381. this.getSortedFiles(this.currentPath)
  382. }
  383. // 组件生命周期
  384. aboutToAppear() {
  385. this.initSetting()
  386. this.topRectHeight = px2vp(AppUtil.getStatusBarHeight());
  387. Utility.getAppName(getContext(this)).then((appName: string) => {
  388. this.appName = appName
  389. })
  390. this.packName = AppUtil.getBundleName()
  391. this.loadCacheFromStorage(); // 加载缓存
  392. this.mkDownLoadDir()
  393. let eventMusic: emitter.InnerEvent = { eventId: 2 }
  394. // 监听广播事件(打开其他应用处理)
  395. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  396. this.saveVideoDatas([eventData.data?.message], true)
  397. });
  398. //侧滑广播接收时间
  399. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: 888 }
  400. // 监听广播事件(打开其他应用处理)
  401. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  402. this.doSwipBack()
  403. });
  404. //ScanFilePage广播接收时间
  405. let eventScanUpdate: emitter.InnerEvent = { eventId: 101 }
  406. // 监听ScanFilePage广播事件(更新数据库)
  407. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  408. this.doUpdateData()
  409. });
  410. let eventSetting: emitter.InnerEvent = { eventId: 333 }
  411. // 监听广播事件(通用设置配置更新)
  412. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  413. this.doChangeSetting()
  414. });
  415. let event: Callback<InterruptEvent> = (event) => {
  416. LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  417. this.savePlaybackPosition()
  418. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  419. this.pause();
  420. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  421. this.startPlayOrResumePlay();
  422. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  423. this.stop();
  424. }
  425. }
  426. this.mIjkMediaPlayer.on('audioInterrupt', event);
  427. // 音频设备断连回调处理
  428. // let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  429. // LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  430. // if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  431. // this.pause();
  432. // }
  433. // }
  434. // this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  435. this.makeWorker()
  436. //折叠屏的屏幕显示模式变化
  437. display.on('foldDisplayModeChange', (data) => {
  438. this.doChangeBarHeight()
  439. });
  440. display.on('foldStatusChange', (data) => {
  441. Logger.info('onecold foldStatusChange ')
  442. });
  443. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, false)
  444. // 读取 themeMode 并同步 currentColorMode
  445. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  446. this.applyThemeMode(this.themeMode)
  447. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  448. AppStorage.setOrCreate('themeColor', themeColor);
  449. this.themeColor = themeColor;
  450. this.doChangeSetting()
  451. this.windowClass.on('windowSizeChange', (size) => {
  452. // LogUtil.info('onecold windowSizeChange')
  453. this.doChangeBarHeight()
  454. let viewWidth = px2vp(size.width);
  455. let viewHeight = px2vp(size.height);
  456. if (viewWidth > viewHeight) {
  457. this.isLandscape = true;
  458. this.startAutoHide()
  459. // Logger.info('onecold 横屏 windowSizeChange isLandscape = ' + this.isLandscape)
  460. }else{
  461. this.isLandscape = false;
  462. this.isAutoHide = false
  463. // Logger.info('onecold 竖屏 windowSizeChange isLandscape = ' + this.isLandscape)
  464. }
  465. });
  466. this.eventHub.on('onStateChange', (fg: boolean) => {
  467. if (fg && this.curState === 'STARTED') {
  468. this.stopPip();
  469. }
  470. });
  471. }
  472. startAutoHide(){
  473. setTimeout(() => {
  474. this.isAutoHide = true
  475. }, 4000)
  476. }
  477. applyThemeMode(mode: number) {
  478. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  479. if (mode === 1) {
  480. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  481. } else if (mode === 2) {
  482. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  483. }
  484. AppStorage.setOrCreate('currentColorMode', colorMode)
  485. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  486. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  487. AppStorage.setOrCreate('themeMode', mode)
  488. this.isDarkMode=colorMode===ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  489. // 只有强制浅色/深色时才主动设置
  490. const context = getContext(this) as common.UIAbilityContext
  491. context.getApplicationContext().setColorMode(colorMode)
  492. }
  493. initSetting(){
  494. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  495. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  496. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  497. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, true)
  498. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  499. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  500. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  501. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  502. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  503. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  504. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  505. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  506. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  507. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 3)
  508. this.isCoverTop = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP, false)
  509. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, false)
  510. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, false)
  511. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  512. if (this.isSavePlayMode) {
  513. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  514. }
  515. if(this.isCustomizeBg){
  516. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  517. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  518. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  519. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  520. }else{
  521. if (!this.isDarkMode) {
  522. this.titleBarModel.setTitleBarBackground(this.themeColor)
  523. this.titleBarModel .setTitleBarBottomLineColor(this.themeColor)
  524. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  525. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  526. }else {
  527. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  528. this.titleBarModel .setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  529. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  530. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  531. }
  532. }
  533. }
  534. doChangeSetting(){
  535. this.initSetting()
  536. this.deleteCache(this.currentPath)
  537. if (this.modeType === 0) {
  538. this.getSortedFiles(this.currentPath)
  539. }
  540. }
  541. doChangeBarHeight() {
  542. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  543. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  544. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  545. this.setBarHeightNormal()
  546. }
  547. }
  548. onPageShow() {
  549. app.setImageCacheCount(100);
  550. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  551. app.setImageRawDataCacheSize(104857600);
  552. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  553. }
  554. //开启线程查看各个数据库
  555. makeWorker() {
  556. setTimeout(() => {
  557. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  558. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  559. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  560. // workerInstance.postMessage({
  561. // code: 1,
  562. // data1: this.context,
  563. // data2: this.rootPath,
  564. // data3: this.lockPath,
  565. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  566. // });
  567. PreferencesUtil.putSync('isFirstApp', false)
  568. } else {
  569. workerInstance.postMessage({ code: 2, data: this.context });
  570. workerInstance.postMessage({ code: 3, data: this.context });
  571. workerInstance.postMessage({ code: 4, data: this.context });
  572. this.getHistoryList(false)
  573. }
  574. }, 1000)
  575. workerInstance.onmessage = (e: MessageEvents): void => {
  576. switch (e.data.code) {
  577. case 101: //第一次扫描文件夹入库
  578. ToastUtil.showToast('刷新同步数据库成功!')
  579. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  580. this.doUpdateData()
  581. break;
  582. case 102: //查询媒体库列表
  583. this.mediaKuList = e.data.data
  584. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  585. Utility.doSortListAscending(this.mediaKuList)
  586. if (this.modeType === 1) {
  587. this.updateListData(this.mediaKuList)
  588. }
  589. break;
  590. case 103: //收到查询艺术家列表
  591. this.artistMap = e.data.data1;
  592. this.artistList = e.data.data2;
  593. break;
  594. case 104: //收到查询专辑列表
  595. this.albumMap = e.data.data1;
  596. this.albumList = e.data.data2
  597. break;
  598. }
  599. };
  600. // 在调用terminate后,执行onexit
  601. workerInstance.onexit = (code) => {
  602. console.log("main thread terminate");
  603. }
  604. //若Worker处于已销毁或正在销毁等非运行状态时,调用其功能接口,会抛出相应的错误。
  605. // 使用Worker模块时,需要在主线程中注册onerror接口,否则当worker线程出现异常时会发生jscrash问题。
  606. workerInstance.onerror = (err: ErrorEvent) => {
  607. console.log("onerror" + err.message);
  608. }
  609. }
  610. @State isFirstStartPlay:boolean = false
  611. //获取download_path
  612. async mkDownLoadDir() {
  613. const documentViewPicker = new picker.DocumentViewPicker()
  614. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  615. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  616. // this.rootPath = this.download_path
  617. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  618. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  619. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  620. Logger.info('onecold rootPath = ' + this.rootPath)
  621. Logger.info('onecold lockPath = ' + this.lockPath)
  622. if (!FileUtil.accessSync(this.lockPath)) {
  623. FileUtil.mkdirSync(this.lockPath)
  624. }
  625. if (!FileUtil.accessSync(this.favPath)) {
  626. FileUtil.mkdirSync(this.favPath)
  627. }
  628. if (!FileUtil.accessSync(this.historyPath)) {
  629. FileUtil.mkdirSync(this.historyPath)
  630. }
  631. this.getSortedFiles(this.rootPath).then(() => {
  632. this.isFavMusic = false
  633. //穿山甲
  634. // this.loadBannerAd(CSJUtil.getBannerID())
  635. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  636. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  637. if (ArrayUtil.isEmpty(this.songList)) {
  638. this.songList = this.getCurFileList()
  639. } else {
  640. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  641. }
  642. if (ArrayUtil.isNotEmpty(this.songList)) {
  643. this.isFirstStartPlay = true
  644. this.sonDataSource.pushArrayData(this.songList)
  645. if (this.currentSong === undefined) {
  646. this.isFirstStartPlay = false
  647. this.currentSong = this.songList[0]
  648. }
  649. this.videoUrl = this.currentSong.filePath
  650. this.name = this.currentSong.name
  651. this.cover = this.currentSong.pixelMapPath
  652. if(this.isStartAutoPlay){
  653. this.startPlayOrResumePlay()
  654. }
  655. } else {
  656. this.name = '空空如也'
  657. }
  658. })
  659. this.getFavList(false)
  660. }
  661. getFavList(isFavRefresh:boolean){
  662. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  663. this.favList = result
  664. if(isFavRefresh||this.isFavMusic){//如果是我的收藏,更新我的收藏数据
  665. this.videoLocalList = this.favList
  666. this.updateListData(this.videoLocalList)
  667. }
  668. })
  669. }
  670. getHistoryList(isRefresh:boolean){
  671. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  672. this.historyList = result
  673. // for (let i = 0; i < this.historyList.length; i++) {
  674. //
  675. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  676. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  677. // }
  678. if(isRefresh){
  679. this.videoLocalList = this.historyList
  680. this.updateListData(this.videoLocalList,true)
  681. }
  682. })
  683. }
  684. // 组件消失生命周期
  685. aboutToDisappear() {
  686. console.info('LifeCycleComponent aboutToDisappear');
  687. emitter.off(2);
  688. emitter.off(101);
  689. emitter.off(888);
  690. emitter.off(333);
  691. this.mDestroyPage = true;
  692. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  693. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  694. this.stop();
  695. }
  696. this.mIjkMediaPlayer.off('audioInterrupt');
  697. if (workerInstance) {
  698. workerInstance.terminate();
  699. }
  700. this.stopPip();
  701. this.destroyPipController()
  702. }
  703. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean) {
  704. this.isFavMusic = false
  705. if (isWorkerPost) {
  706. workerInstance.postMessage({ code: 2, data: this.context }); //刷新媒体库列表
  707. }
  708. if (this.modeType !== 0) {
  709. return
  710. }
  711. this.isCanBack = false
  712. this.currentPath = curPath
  713. this.titleBarModel.setTitleName(Utility.getFileDirName(this.currentPath, this.rootPath))
  714. if (curPath === this.rootPath) {
  715. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  716. } else {
  717. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  718. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  719. }
  720. }
  721. // Get the current file list and calculate its hash
  722. this.fileList = FileUtil.listFileSync(curPath);
  723. const currentHash = simpleHash(this.fileList);
  724. // Check cache
  725. const cachedValue = this.findCache(curPath);
  726. Logger.info('onecold cachedValue = ' + cachedValue)
  727. const cachedHash = this.findStringCache(curPath + '_hash');
  728. const cachedDirList = this.findCache(curPath + "_dirList");
  729. if (cachedValue !== undefined) {
  730. // this.videoLocalList = cachedValue;
  731. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  732. this.updateListData(cachedValue)
  733. }
  734. if (cachedDirList !== undefined) {
  735. this.dirList = cachedDirList
  736. }
  737. //通过当前hash值和缓存hash判断list有没有变化
  738. if (cachedValue && cachedHash === currentHash) {
  739. return;
  740. }
  741. this.fileList = FileUtil.listFileSync(curPath)
  742. let directories: Array<VideoItem> = [];
  743. let files: Array<VideoItem> = [];
  744. for (let i = 0; i < this.fileList.length; i++) {
  745. console.info(`The name of file: ${this.fileList[i]}`);
  746. let path = curPath + '/' + this.fileList[i]
  747. if (FileUtil.isDirectory(path)) {
  748. let item: VideoItem =
  749. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  750. '')
  751. if(this.isShowDir(item.name)){
  752. directories.push(item);
  753. }
  754. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  755. // Utility.doSortListAscending(directories)
  756. } else {
  757. if (this.currentPath === this.lockPath) {
  758. let item: VideoItem =
  759. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  760. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  761. files.push(item);
  762. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  763. // this.doSortListAscending(files)
  764. }
  765. }
  766. }
  767. }
  768. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  769. if (this.currentPath !== this.lockPath) {
  770. files = result;
  771. }
  772. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  773. Utility.doSortListAscending(files)
  774. if (this.currentPath === this.rootPath) {
  775. this.dirList = directories
  776. this.addCache(curPath + "_dirList", this.dirList);
  777. }
  778. //插入广告先注释掉
  779. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  780. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  781. // directories.push(adItem)
  782. // }
  783. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  784. this.videoLocalList = directories.concat(files);
  785. this.updateListData(this.videoLocalList)
  786. if (ArrayUtil.isNotEmpty(files)) {
  787. // 缓存结果
  788. this.addCache(curPath, this.videoLocalList);
  789. await this.saveCacheToStorage(); // 保存缓存至本地存储
  790. this.addStringCache(curPath + '_hash', currentHash);
  791. }
  792. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  793. // for (let i = 0; i < this.videoLocalList.length; i++) {
  794. //
  795. // console.info(`onecold gengxin 1: ${this.videoLocalList[i].pixelMapPath}`);
  796. //
  797. // }
  798. // this.setButtonStatus()
  799. if (isOpen) {
  800. if (destPath === undefined) {
  801. // 处理 destPath 为 undefined 的情况
  802. return
  803. }
  804. if (destPath.endsWith('.lrc')) {
  805. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  806. if (StrUtil.isNotEmpty(this.videoUrl)) {
  807. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  808. this.initLyric(lyricPath);
  809. }
  810. return
  811. }
  812. let item2 = new VideoItem(Utility.getMediaNameByUri(destPath), destPath, destPath, 0, 0, '')
  813. this.doPlay(item2)
  814. }
  815. });
  816. }
  817. //扫描文件夹入库
  818. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  819. const files = FileUtil.listFileSync(curPath);
  820. let mediaItems: VideoItem[] = [];
  821. Logger.info('onecold scanDirectory start ')
  822. for (const file of files) {
  823. const fPath = `${curPath}/${file}`;
  824. if (fPath === this.lockPath) {
  825. Logger.info(`Skipping locked path: ${fPath}`);
  826. continue;
  827. }
  828. if (FileUtil.isDirectory(fPath)) {
  829. // Recursively scan subdirectories
  830. const subDirItems = await this.scanDirectory(fPath);
  831. mediaItems = mediaItems.concat(subDirItems);
  832. } else {
  833. Logger.info('onecold scanDirectory filePath = ' + fPath)
  834. // Process media files
  835. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  836. let mediaItem: VideoItem =
  837. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, true);
  838. mediaItems.push(mediaItem);
  839. this.table.insert(mediaItem, (id: number) => {
  840. });
  841. }
  842. }
  843. }
  844. return mediaItems;
  845. }
  846. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  847. animateTo({ duration: 888 }, () => {
  848. this.opacityItem = 0;
  849. });
  850. setTimeout(() => {
  851. this.videoLocalList = mList;
  852. if (!noSort) {
  853. if (this.modeType === 0 || this.modeType === 1) {
  854. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  855. this.doSortType(this.sortType)
  856. }
  857. }
  858. this.dataSource.pushArrayData(this.videoLocalList)
  859. animateTo({ duration: 888 }, () => {
  860. this.opacityItem = 1;
  861. });
  862. this.setButtonStatus()
  863. }, 200);
  864. }
  865. //获取视频缩略图头像
  866. async updatePixelMaps(curPath: string) {
  867. console.info('updatePixelMaps: ', curPath);
  868. const updatedList = [...this.videoLocalList]; // 创建一个新的列表
  869. for (const videoItem of updatedList) {
  870. if (videoItem.type === CommonConstants.TYPE_LOCAL) {
  871. let pixelMap: image.PixelMap | undefined = undefined;
  872. const uri = videoItem.filePath;
  873. // 获取缩略图
  874. // if (Utility.isVideoByExtension(uri)) {
  875. // pixelMap = await Utility.getFetchFrameByTime(uri);
  876. // } else {
  877. // pixelMap = await Utility.getFetchMetadataFromFdSrcByPromise(uri);
  878. // }
  879. let name = await MD5.digestSync(uri)
  880. let imagePath = this.context.filesDir + FileUtil.separator + name
  881. console.info('onecold release success. name= ' + name);
  882. imagePath = fileUri.getUriFromPath(imagePath)
  883. videoItem.pixelMapPath = imagePath
  884. // videoItem.pixelMap = pixelMap;
  885. // videoItem.pixelMapToString = pixelMap ? await ImageUtil.pixelMapToBase64StrBig(pixelMap) : undefined;
  886. }
  887. }
  888. // console.info('updatePixelMaps完毕: ', updatedList.length);
  889. this.updateListData(updatedList)
  890. // this.videoLocalList = updatedList; // 重新赋值以触发更新
  891. // 缓存结果
  892. this.addCache(curPath, updatedList);
  893. await this.saveCacheToStorage(); // 保存缓存至本地存储
  894. }
  895. //排序模式和多选模式
  896. showPupDialog() {
  897. if (this.modeType === 2 || this.modeType === 3) {
  898. this.titleBarModel.setRightIcon(null)
  899. } else {
  900. this.titleBarModel.setRightIcon(($r('app.media.add')))
  901. }
  902. let dataBean = new BubbleBean()
  903. dataBean.data = ["首页", "媒体库", "艺术家", "专辑", "同步数据"]
  904. dataBean.color = this.themeColor
  905. dataBean.imageRes =
  906. [$r('app.media.home_press'), $r('app.media.kp_music'), $r('app.media.music_menu'), $r('app.media.llq'),
  907. $r('app.media.refresh')]
  908. let pup: XPopup;
  909. if (this.isDarkMode) {
  910. pup = XPopup.Builder()
  911. .setPopupPosition(PopupPosition.BOTTOM)
  912. .atView('pup_positon_music')
  913. .setBackgroundColor(Color.Black)
  914. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  915. .show()
  916. }else {
  917. pup = XPopup.Builder()
  918. .setPopupPosition(PopupPosition.BOTTOM)
  919. .atView('pup_positon_music')
  920. .setBackgroundColor(Color.White)
  921. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  922. .show()
  923. }
  924. dataBean.onItemClick = (i) => {
  925. XPopup.dismissTop()
  926. switch (i) {
  927. case 0: //首页
  928. this.modeType = 0
  929. this.getSortedFiles(this.currentPath)
  930. break
  931. case 1:
  932. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  933. this.modeType = 1
  934. this.updateListData(this.mediaKuList)
  935. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  936. break
  937. case 2:
  938. this.modeType = 2
  939. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  940. this.updateListData(this.artistList)
  941. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  942. break
  943. case 3:
  944. this.modeType = 3
  945. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  946. this.updateListData(this.albumList)
  947. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  948. break
  949. case 4: //同步数据
  950. workerInstance.postMessage({
  951. code: 1,
  952. data1: this.context,
  953. data2: this.rootPath,
  954. data3: this.lockPath,
  955. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  956. });
  957. break
  958. }
  959. }
  960. }
  961. getCurFileList(): Array<VideoItem> {
  962. let files: Array<VideoItem> = [];
  963. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  964. for (let i = 0; i < this.videoLocalList.length; i++) {
  965. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  966. files.push(this.videoLocalList[i]);
  967. }
  968. }
  969. }
  970. return files
  971. }
  972. setButtonStatus() {
  973. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  974. this.isZero = false
  975. } else {
  976. this.isZero = true
  977. }
  978. if (this.currentPath !== this.rootPath &&
  979. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  980. this.isHasDir = true //不为空,说明有子文件夹
  981. } else {
  982. this.isHasDir = false
  983. }
  984. }
  985. showRankDialog() {
  986. if (this.modeType === 2 || this.modeType === 3) {
  987. //动作面板
  988. DialogHelper.showBottomSheetDialog({
  989. title: "请选择排序模式",
  990. maskColor: Color.Transparent,
  991. // sheets: ["按名称升序", "按名称降序"],
  992. sheets:[
  993. {value:'按名称升序',fontColor: $r('app.color.text_color') },
  994. {value:'按名称降序',fontColor: $r('app.color.text_color') },
  995. ],
  996. backgroundColor:$r('app.color.bg_card'),
  997. height: '30%',
  998. transition: AnimationHelper.transitionInDown(555),
  999. onAction: (index) => {
  1000. switch (index) {
  1001. case 0:
  1002. Utility.doSortListAscending(this.videoLocalList)
  1003. break;
  1004. case 1:
  1005. Utility.doSortListDescending(this.videoLocalList)
  1006. break;
  1007. }
  1008. this.updateListData(this.videoLocalList)
  1009. }
  1010. })
  1011. return
  1012. }
  1013. //动作面板
  1014. DialogHelper.showBottomSheetDialog({
  1015. title: "请选择排序模式",
  1016. maskColor: Color.Transparent,
  1017. height: '75%',
  1018. // sheets: ["按艺术家升序", "按艺术家降序", "按专辑升序", "按专辑降序", "按名称升序", "按名称降序", "按添加时间升序","按添加时间降序"],
  1019. sheets:[
  1020. { value: "按艺术家升序", fontColor: $r('app.color.text_color') },
  1021. { value: "按艺术家降序", fontColor: $r('app.color.text_color') },
  1022. { value: "按专辑升序", fontColor: $r('app.color.text_color') },
  1023. { value: "按专辑降序", fontColor: $r('app.color.text_color') },
  1024. { value: "按名称升序", fontColor: $r('app.color.text_color') },
  1025. { value: "按名称降序", fontColor: $r('app.color.text_color') },
  1026. { value: "按添加时间升序", fontColor: $r('app.color.text_color') },
  1027. { value: "按添加时间降序", fontColor: $r('app.color.text_color') },
  1028. ],
  1029. backgroundColor: $r('app.color.bg_card'),
  1030. transition: AnimationHelper.transitionInDown(555),
  1031. onAction: (index) => {
  1032. this.doSortType(index)
  1033. this.updateListData(this.videoLocalList, true)
  1034. }
  1035. })
  1036. }
  1037. doSortType(index: number) {
  1038. switch (index) {
  1039. case 0:
  1040. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1041. // 类型排序优先级
  1042. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1043. if (typeOrder !== 0) {
  1044. return typeOrder;
  1045. }
  1046. // 处理艺术家可能为undefined的字符串比较
  1047. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1048. const artistB = b.artist?.trim() || '';
  1049. return artistA.localeCompare(artistB);
  1050. });
  1051. break;
  1052. case 1:
  1053. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1054. // 类型排序优先级
  1055. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1056. if (typeOrder !== 0) {
  1057. return typeOrder;
  1058. }
  1059. // 处理艺术家可能为undefined的字符串比较
  1060. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1061. const artistB = b.artist?.trim() || '';
  1062. return artistB.localeCompare(artistA);
  1063. });
  1064. break;
  1065. case 2:
  1066. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1067. // 类型排序优先级
  1068. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1069. if (typeOrder !== 0) {
  1070. return typeOrder;
  1071. }
  1072. // 处理专辑可能为undefined的字符串比较
  1073. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1074. const albumB = b.album?.trim() || '';
  1075. return albumA.localeCompare(albumB);
  1076. });
  1077. break;
  1078. case 3:
  1079. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1080. // 类型排序优先级
  1081. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1082. if (typeOrder !== 0) {
  1083. return typeOrder;
  1084. }
  1085. // 处理专辑可能为undefined的字符串比较
  1086. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1087. const albumB = b.album?.trim() || '';
  1088. return albumB.localeCompare(albumA);
  1089. });
  1090. break;
  1091. case 4:
  1092. Utility.doSortListAscending(this.videoLocalList)
  1093. break;
  1094. case 5:
  1095. Utility.doSortListDescending(this.videoLocalList)
  1096. break;
  1097. case 6:
  1098. this.videoLocalList.sort((a, b) => {
  1099. // First, sort by type
  1100. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1101. if (typeOrder !== 0) {
  1102. return typeOrder;
  1103. }
  1104. // If types are the same, sort by cTime in ascending order
  1105. return a.cTime.localeCompare(b.cTime);
  1106. });
  1107. break;
  1108. case 7:
  1109. this.videoLocalList.sort((a, b) => {
  1110. // First, sort by type
  1111. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1112. if (typeOrder !== 0) {
  1113. return typeOrder;
  1114. }
  1115. // If types are the same, sort by cTime in descending order
  1116. return b.cTime.localeCompare(a.cTime);
  1117. });
  1118. break;
  1119. }
  1120. }
  1121. showSheelDialog() {
  1122. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  1123. // this.showTips()
  1124. // return
  1125. // }
  1126. this.showAddDialog()
  1127. }
  1128. showAddDialog() {
  1129. if (this.modeType === 2 || this.modeType === 3) {
  1130. return
  1131. }
  1132. DialogHelper.showActionSheetDialog({
  1133. title: "请选择添加方式(建议歌词文件一起导入)",
  1134. // sheets: ["新建歌单", "手动导入", "自动导入"],
  1135. sheets:[
  1136. { value: "新建歌单", fontColor: $r('app.color.text_color') },
  1137. { value: "手动导入", fontColor: $r('app.color.text_color') },
  1138. { value: "自动导入", fontColor: $r('app.color.text_color') },
  1139. { value: "全选导入", fontColor: $r('app.color.text_color') },
  1140. ],
  1141. maskColor: Color.Transparent,
  1142. backgroundColor: $r('app.color.bg_card'),
  1143. transition: AnimationHelper.transitionInDown(555),
  1144. onAction: (index) => {
  1145. switch (index) {
  1146. case 0:
  1147. if (this.modeType === 0) {
  1148. this.showMkDialog()
  1149. } else {
  1150. ToastUtil.showToast('请切换到首页才能新建歌单!')
  1151. }
  1152. break;
  1153. case 1:
  1154. this.callFilePickerSelectFile()
  1155. break;
  1156. case 2:
  1157. this.showTips()
  1158. break;
  1159. case 3:
  1160. this.goSelectMusic()
  1161. break;
  1162. }
  1163. }
  1164. })
  1165. }
  1166. //拉起音频
  1167. goSelectMusic(){
  1168. if(DeviceUtil.getDeviceType()== resourceManager.DeviceType.DEVICE_TYPE_TABLET||
  1169. DeviceUtil.getDeviceType()== resourceManager.DeviceType.DEVICE_TYPE_PC||
  1170. DeviceUtil.getDeviceType()== resourceManager.DeviceType.DEVICE_TYPE_2IN1
  1171. ){
  1172. ToastUtil.showToast('暂时不支持该设备')
  1173. return
  1174. }
  1175. try {
  1176. let documentSelectOptions = new picker.DocumentSelectOptions();
  1177. documentSelectOptions.authMode = true
  1178. documentSelectOptions.multiAuthMode = true
  1179. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  1180. let documentPicker = new picker.DocumentViewPicker(this.context);
  1181. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  1182. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  1183. this.saveVideoDatas(documentSelectResult)
  1184. }
  1185. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' + JSON.stringify(documentSelectResult));
  1186. }).catch((err: BusinessError) => {
  1187. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  1188. });
  1189. } catch (error) {
  1190. let err: BusinessError = error as BusinessError;
  1191. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1192. }
  1193. }
  1194. async showTips() {
  1195. DialogHelper.showTipsDialog({
  1196. title: '使用提示:自动导入教程',
  1197. content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  1198. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  1199. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  1200. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  1201. onAction: (action) => {
  1202. if (action == DialogAction.TWO) {
  1203. PreferencesUtil.putSync('isFirstMusic', false)
  1204. router.pushUrl({
  1205. url: 'pages/ScanFilePage'
  1206. });
  1207. }
  1208. }
  1209. })
  1210. }
  1211. showMkDialog() {
  1212. DialogHelper.showTextInputDialog({
  1213. title: '新建歌单',
  1214. maskColor: Color.Transparent,
  1215. text: '',
  1216. transition: AnimationHelper.transitionInDown(666),
  1217. onChange: (text) => {
  1218. console.error("onChange: " + text);
  1219. },
  1220. onAction: (action, dialogId, content) => {
  1221. // ToastUtil.showToast('content = ' +content)
  1222. if (action == DialogAction.TWO) {
  1223. const newName = content
  1224. const newPath = this.currentPath + '/' + newName
  1225. FileUtil.mkdir(newPath, true).then(() => {
  1226. this.cache.delete(this.currentPath); // 删除目标路径缓存
  1227. this.getSortedFiles(this.currentPath)
  1228. }).catch((error: BusinessError) => {
  1229. console.error(error.message);
  1230. });
  1231. }
  1232. }
  1233. })
  1234. }
  1235. @State progress: number = 0;
  1236. async saveVideoDatas(uris: string[], isOpen?: boolean) {
  1237. if (ArrayUtil.isEmpty(uris)) {
  1238. return;
  1239. }
  1240. let newUris: string[] = [];
  1241. this.progress = 0
  1242. DialogHelper.showLoadingProgress({
  1243. progress: this.progress,
  1244. backCancel: false,
  1245. autoCancel: false,
  1246. loadColor: this.themeColor,
  1247. fontColor: this.themeColor
  1248. });
  1249. // 计算所有文件的总大小
  1250. let totalSize = 0;
  1251. for (let uri of uris) {
  1252. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  1253. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  1254. await fileIo.close(sourceFile.fd);
  1255. }
  1256. let totalRead = 0;
  1257. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  1258. Logger.info(TAG, 'destPath uri: ' + destPath);
  1259. for (let i = 0; i < uris.length; i++) {
  1260. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  1261. Logger.info(TAG, 'filePath uri: ' + filePath);
  1262. newUris.push(filePath);
  1263. try {
  1264. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  1265. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  1266. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  1267. const buffer = new ArrayBuffer(buffSize);
  1268. let len = await fileIo.read(sourceFile.fd, buffer);
  1269. while (len > 0) {
  1270. await fileIo.write(destFile.fd, buffer.slice(0, len));
  1271. totalRead += len;
  1272. // 计算总进度
  1273. this.progress = Math.floor((totalRead / totalSize) * 100);
  1274. DialogHelper.updateLoading('正在导入', this.progress);
  1275. len = await fileIo.read(sourceFile.fd, buffer);
  1276. }
  1277. await fileIo.close(sourceFile.fd);
  1278. await fileIo.close(destFile.fd);
  1279. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  1280. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  1281. let mediaItem: VideoItem =
  1282. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, true);
  1283. this.table.insert(mediaItem, (id: number) => {
  1284. // 删除目标路径缓存
  1285. this.cache.delete(this.currentPath);
  1286. this.getSortedFiles(this.currentPath, true, destPath, isOpen)
  1287. });
  1288. }
  1289. }
  1290. } catch (error) {
  1291. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  1292. }
  1293. }
  1294. DialogHelper.closeLoading()
  1295. this.isZero = false
  1296. // setTimeout(() => {
  1297. // // 删除目标路径缓存
  1298. // this.cache.delete(this.currentPath);
  1299. // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
  1300. // }, 500);
  1301. Logger.info(TAG, 'scan select video result:' + newUris)
  1302. }
  1303. //拉起音频
  1304. // goSelectMusic(){
  1305. //
  1306. // try {
  1307. // let audioSelectOptions = new picker.AudioSelectOptions();
  1308. // let audioPicker = new picker.AudioViewPicker(this.context);
  1309. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  1310. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  1311. // this.saveVideoDatas(audioSelectResult)
  1312. // }
  1313. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  1314. // }).catch((err: BusinessError) => {
  1315. //
  1316. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  1317. // });
  1318. // } catch (error) {
  1319. // let err: BusinessError = error as BusinessError;
  1320. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1321. // }
  1322. //
  1323. //
  1324. //
  1325. // }
  1326. goSelectImage(item:VideoItem) {
  1327. if (!item) {
  1328. return
  1329. }
  1330. let selectUris: Array<string> = [];
  1331. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  1332. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  1333. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; // 过滤选择媒体文件类型为IMAGE
  1334. photoSelectOptions.maxSelectNumber = 1; // 选择媒体文件的最大数目
  1335. photoPicker.select(photoSelectOptions).then(async (photoSelectResult: photoAccessHelper.PhotoSelectResult) => {
  1336. //用一个全局变量存储返回的uri
  1337. selectUris = photoSelectResult.photoUris;
  1338. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  1339. //使用fs.openSync接口,通过uri打开这个文件得到fd
  1340. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  1341. console.info('file fd: ' + file.fd);
  1342. let name = await MD5.digestSync(this.videoUrl)
  1343. let imagePath = this.context.filesDir + FileUtil.separator + name
  1344. imagePath = fileUri.getUriFromPath(imagePath)
  1345. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  1346. fileIo.copyFileSync(file.fd, file2.fd)
  1347. fileIo.closeSync(file);
  1348. fileIo.closeSync(file2);
  1349. if(item.filePath==this.currentSong?.filePath){
  1350. this.cover = imagePath
  1351. }
  1352. if (item) {
  1353. item.pixelMapPath = imagePath
  1354. }
  1355. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  1356. if (success) {
  1357. this.doUpdateData()
  1358. console.log(" onecold 更新音乐封面成功,数据库已同步");
  1359. } else {
  1360. console.error(" onecold 更新音乐封面数据库失败原因: " + error);
  1361. }
  1362. });
  1363. LogUtil.debug("onecold this.cover =" + this.cover)
  1364. }).catch((err: BusinessError) => {
  1365. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  1366. })
  1367. }
  1368. // 拉起picker选择文件管理器
  1369. async callFilePickerSelectFile(): Promise<void> {
  1370. try {
  1371. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  1372. // DocumentSelectOptions.multiAuthMode = true
  1373. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  1374. let documentPicker = new picker.DocumentViewPicker();
  1375. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  1376. Logger.info(TAG,
  1377. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  1378. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  1379. this.saveVideoDatas(DocumentSelectResult)
  1380. }
  1381. }).catch((err: BusinessError) => {
  1382. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  1383. });
  1384. } catch (err) {
  1385. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  1386. }
  1387. }
  1388. showWarnIsDeleteFile(item: VideoItem, index: string, filePath: string) {
  1389. //操作确认类弹出框
  1390. DialogHelper.showAlertDialog({
  1391. maskColor: Color.Transparent,
  1392. content: "确定要删除这个文件吗?",
  1393. backgroundColor: Color.Grey,
  1394. transition: AnimationHelper.transitionInUp(555),
  1395. onAction: (action) => {
  1396. if (action == DialogAction.ONE) {
  1397. // ToastUtil.showToast(`您点击了取消按钮`);
  1398. } else if (action == DialogAction.TWO) {
  1399. // ToastUtil.showToast(`您点击了确认按钮`);
  1400. this.doDelete(item, index + '', filePath)
  1401. }
  1402. }
  1403. })
  1404. }
  1405. //删除单个索引index的视频
  1406. doDelete(item: VideoItem, index: string, filePath: string) {
  1407. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1408. Logger.info(TAG, 'delete filePath = ' + filePath);
  1409. if (item.type === CommonConstants.TYPE_IS_DIR) {
  1410. //旧文件删除
  1411. this.table.deleteDataForParentPath(item.filePath, () => {
  1412. FileUtil.rmdir(filePath).then(() => {
  1413. this.videoLocalList.splice(Number(index), 1)
  1414. this.deleteCache(this.currentPath)
  1415. this.getSortedFiles(this.currentPath, true)
  1416. }).catch((error: BusinessError) => {
  1417. console.error(error.message);
  1418. });
  1419. });
  1420. } else {
  1421. this.table.deleteData(item, () => {
  1422. FileUtil.unlink(filePath)
  1423. .catch((error: BusinessError) => {
  1424. console.error(error.message);
  1425. // 可以根据 error.code 判断是否为"文件不存在",如需特殊处理
  1426. })
  1427. .finally(() => {
  1428. this.videoLocalList.splice(Number(index), 1)
  1429. this.deleteCache(this.currentPath)
  1430. this.getSortedFiles(this.currentPath, true)
  1431. });
  1432. });
  1433. }
  1434. }
  1435. }
  1436. //重命名的对话框
  1437. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  1438. DialogHelper.showTextInputDialog({
  1439. title: '重命名',
  1440. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  1441. maskColor: Color.Transparent,
  1442. backgroundColor: Color.Grey,
  1443. transition: AnimationHelper.transitionInDown(666),
  1444. onChange: (text) => {
  1445. console.error("onChange: " + text);
  1446. },
  1447. onAction: (action, dialogId, content) => {
  1448. // ToastUtil.showToast('content = ' +content)
  1449. if (action == DialogAction.TWO) {
  1450. const newName = content
  1451. const newPath = this.currentPath + '/' + newName
  1452. console.log("onecold item = " + item.type);
  1453. this.doReName(index, newName, filePath, newPath, item)
  1454. }
  1455. }
  1456. })
  1457. }
  1458. //剪切 移动到另个文件夹的对话框
  1459. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1460. Logger.info('onecold showCutDialog')
  1461. let mList: Array<string> = []
  1462. let rPath = this.rootPath
  1463. if (isCurrent) {
  1464. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1465. rPath = this.currentPath
  1466. } else {
  1467. mList = Utility.getNameList(this.dirList);
  1468. rPath = this.rootPath
  1469. }
  1470. let dataBean = new BubbleBean()
  1471. dataBean.data = mList
  1472. dataBean.color = this.themeColor
  1473. dataBean.onItemClick = (i) => {
  1474. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1475. Logger.info('newPath = ' + newPath)
  1476. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  1477. ToastUtil.showToast('移动成功')
  1478. this.table.deleteData(item, () => {
  1479. });
  1480. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1481. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1482. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1483. CommonConstants.TYPE_LOCAL, true);
  1484. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1485. this.table.insert(newItem, (id: number) => {
  1486. //加入数据库
  1487. });
  1488. }
  1489. this.cache.delete(this.currentPath); // 删除原路径缓存
  1490. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1491. this.getSortedFiles(this.currentPath, true)
  1492. }).catch((error: BusinessError) => {
  1493. console.error(error.message);
  1494. });
  1495. XPopup.dismissTop()
  1496. }
  1497. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1498. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1499. popupPosition = PopupPosition.TOP
  1500. }
  1501. if (index <= 3) {
  1502. popupPosition = PopupPosition.BOTTOM
  1503. }
  1504. let pup:XPopup
  1505. if(this.isDarkMode){
  1506. pup = XPopup.Builder()
  1507. .setPopupPosition(popupPosition)
  1508. .atView(id)
  1509. // .setHeight(this.isCoverOpacity()?100:420)
  1510. .setBackgroundColor(Color.Black)
  1511. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1512. .show()
  1513. }else {
  1514. pup = XPopup.Builder()
  1515. .setPopupPosition(popupPosition)
  1516. .atView(id)
  1517. // .setHeight(this.isCoverOpacity()?280:420)
  1518. .setBackgroundColor(Color.White)
  1519. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1520. .show()
  1521. }
  1522. }
  1523. //复制 到另个文件夹的对话框
  1524. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1525. Logger.info('onecoldv showCopyDialog')
  1526. let mList: Array<string> = []
  1527. let rPath = this.rootPath
  1528. if (isCurrent) {
  1529. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1530. rPath = this.currentPath
  1531. } else {
  1532. mList = Utility.getNameList(this.dirList);
  1533. rPath = this.rootPath
  1534. }
  1535. let dataBean = new BubbleBean()
  1536. dataBean.data = mList
  1537. dataBean.isCopy = true
  1538. dataBean.color = this.themeColor
  1539. dataBean.onItemClick = (i) => {
  1540. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1541. Logger.info('newPath = ' + newPath)
  1542. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  1543. ToastUtil.showToast('复制成功')
  1544. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1545. this.getSortedFiles(this.currentPath)
  1546. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1547. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1548. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1549. CommonConstants.TYPE_LOCAL, true);
  1550. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1551. this.table.insert(newItem, (id: number) => {
  1552. //加入数据库
  1553. });
  1554. }
  1555. }).catch((error: BusinessError) => {
  1556. console.error(error.message);
  1557. });
  1558. XPopup.dismissTop()
  1559. }
  1560. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1561. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1562. popupPosition = PopupPosition.TOP
  1563. }
  1564. if (index <= 3) {
  1565. popupPosition = PopupPosition.BOTTOM
  1566. }
  1567. let pup:XPopup
  1568. if (this.isDarkMode) {
  1569. pup = XPopup.Builder()
  1570. .setPopupPosition(popupPosition)
  1571. .atView(id)
  1572. .setMaxHeight('60%')
  1573. .setBackgroundColor(Color.Black)
  1574. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1575. .show();
  1576. }else {
  1577. pup = XPopup.Builder()
  1578. .setPopupPosition(popupPosition)
  1579. .atView(id)
  1580. .setMaxHeight('60%')
  1581. .setBackgroundColor(Color.White)
  1582. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1583. .show();
  1584. }
  1585. }
  1586. //重命名索引index的视频
  1587. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  1588. FileUtil.rename(oldPath, newPath).then(async () => {
  1589. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1590. if (info.type === CommonConstants.TYPE_IS_DIR) {
  1591. //如果是文件夹先删除源数据,再添加新数据
  1592. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  1593. if (success) {
  1594. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  1595. } else {
  1596. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  1597. }
  1598. });
  1599. this.scanDirectory(newPath)
  1600. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  1601. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  1602. if (success) {
  1603. console.log(" onecold 重命名成功,数据库已同步");
  1604. } else {
  1605. console.error(" onecold 重命名数据库失败原因: " + error);
  1606. }
  1607. });
  1608. }
  1609. let mediaItem: VideoItem =
  1610. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, true);
  1611. this.videoLocalList[index] = mediaItem;
  1612. }
  1613. this.cache.delete(this.currentPath)
  1614. this.getSortedFiles(this.currentPath, true)
  1615. }).catch((error: BusinessError) => {
  1616. console.error(error.message);
  1617. });
  1618. }
  1619. build() {
  1620. Scroll() {
  1621. Column() {
  1622. Column(){
  1623. Line().width('100%').height('100%')
  1624. }
  1625. .height(this.topRectHeight)
  1626. .backgroundColor(this.isCustomizeBg?Color.Transparent:(this.isDarkMode?$r('app.color.title_bar_bg'):this.themeColor))
  1627. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  1628. TitleBar({ model: $titleBarModel })
  1629. .id('pup_positon_music')
  1630. Stack() {
  1631. Column() {
  1632. XComponent({
  1633. id: 'xcomponentId',
  1634. type: 'surface',
  1635. libraryname: 'ijkplayer_napi',
  1636. controller: this.xcomponentController
  1637. })
  1638. .onLoad((event?: object) => {
  1639. if (!!event) {
  1640. this.initDelayPlay(event);
  1641. }
  1642. })
  1643. .onDestroy(() => {
  1644. })
  1645. .width('100%')// .width(this.videoWidth)
  1646. .aspectRatio(this.videoAspectRatio)
  1647. }
  1648. .aspectRatio(this.videoAspectRatio)
  1649. .justifyContent(FlexAlign.Center)
  1650. .backgroundColor(Color.Transparent)
  1651. .visibility(Visibility.Hidden)
  1652. .height(CommonConstants.FULL_PERCENT)
  1653. .width(CommonConstants.FULL_PERCENT)
  1654. Stack() {
  1655. Row() {
  1656. Blank()
  1657. .layoutWeight(1)
  1658. IndexerView(
  1659. {
  1660. indexArray: DEFAULT_INDEX,
  1661. selectedIndex: this.selectedIndex,
  1662. textSize: 12,
  1663. selectedColor: "#ff419ee5",
  1664. normalColor: "#ffa0a0a0",
  1665. floatSelectedTextColor: "#ffffff",
  1666. floatSelectedViewColor: "#ff419ee5",
  1667. onIndexChanged: (index) => {
  1668. this.listScroller.scrollToIndex(index)
  1669. }
  1670. })
  1671. .width(24)
  1672. .height("50%")
  1673. }.visibility(Visibility.None)
  1674. Column() {
  1675. this.tabTitle()
  1676. this.listViewTitle()
  1677. if(this.isGridMusic){
  1678. this.getGridView()
  1679. }else {
  1680. this.getListView()
  1681. }
  1682. }
  1683. .layoutWeight(1)
  1684. .height('100%')
  1685. }
  1686. .layoutWeight(1)
  1687. .height('100%')
  1688. Row() {
  1689. Button(this.isAllSelected ? '全不选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  1690. .width('35%')
  1691. .height(60)
  1692. .margin({ top: 10, bottom: 10, right: 6 })
  1693. .backgroundColor(this.themeColor)
  1694. .clickEffect({level:ClickEffectLevel.HEAVY})
  1695. .onClick(() => {
  1696. if (this.isAllSelected) {
  1697. // 全不选
  1698. this.selectedFiles = [];
  1699. } else {
  1700. // 全选
  1701. this.selectedFiles = [...this.getCurFileList()];
  1702. }
  1703. this.isAllSelected = !this.isAllSelected;
  1704. })
  1705. Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  1706. .width('35%')
  1707. .height(60)
  1708. .id('music_cut')
  1709. .margin({ top: 10, bottom: 10, right: 6 })
  1710. .clickEffect({level:ClickEffectLevel.HEAVY})
  1711. .backgroundColor(this.themeColor)
  1712. .onClick(() => {
  1713. this.showCutDialogForMultipleFiles(false, 'music_cut')
  1714. })
  1715. Button('移动', { type: ButtonType.Circle, stateEffect: true })
  1716. .width('35%')
  1717. .height(60)
  1718. .id('music_cut_current')
  1719. .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  1720. .margin({ top: 10, bottom: 10, right: 6 })
  1721. .backgroundColor(this.themeColor)
  1722. .clickEffect({level:ClickEffectLevel.HEAVY})
  1723. .onClick(() => {
  1724. this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  1725. })
  1726. Button('复制', { type: ButtonType.Circle, stateEffect: true })
  1727. .width('35%')
  1728. .height(60)
  1729. .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  1730. .margin({ top: 10, bottom: 10, right: 6 })
  1731. .backgroundColor(this.themeColor)
  1732. .clickEffect({level:ClickEffectLevel.HEAVY})
  1733. .onClick(() => {
  1734. this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  1735. })
  1736. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  1737. .width('35%')
  1738. .height(60)
  1739. .margin({ top: 10, bottom: 10, right: 6 })
  1740. .visibility(this.isFavMusic?Visibility.None:Visibility.Visible)
  1741. .backgroundColor(this.themeColor)
  1742. .clickEffect({level:ClickEffectLevel.HEAVY})
  1743. .onClick(() => {
  1744. this.showWarnIsDelete()
  1745. })
  1746. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  1747. .width('35%')
  1748. .height(60)
  1749. .margin({ top: 10, bottom: 10, right: 6 })
  1750. .backgroundColor(this.themeColor)
  1751. .clickEffect({level:ClickEffectLevel.HEAVY})
  1752. .onClick(() => {
  1753. this.selectedFiles = [];
  1754. this.isAllSelected = false
  1755. this.isMultiSelect = false
  1756. })
  1757. }
  1758. .width('100%')
  1759. .justifyContent(FlexAlign.Center)
  1760. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  1761. .opacity(this.isMultiSelect ? 1 : 0)
  1762. .animation({
  1763. duration: 666,
  1764. curve: 'ease-in-out' // 可选动画曲线
  1765. })
  1766. .position({ bottom:this.isPhoneLan()?130: 168 }) // 将 Row 固定在底部
  1767. // Column() {
  1768. // Button('导入音乐', { type: ButtonType.Capsule, stateEffect: true })
  1769. // .width('50%')
  1770. // .height(55)
  1771. // .margin({ top: 50, bottom: 40 })
  1772. // .backgroundColor(this.themeColor)
  1773. //
  1774. // .onClick(() => {
  1775. // this.showSheelDialog()
  1776. // })
  1777. //
  1778. // }
  1779. // .height('100%')
  1780. // .justifyContent(FlexAlign.Center)
  1781. // .opacity(this.isZero ? 1 : 0)
  1782. // .visibility(this.isZero && this.modeType === 0 ? Visibility.None : Visibility.None)
  1783. // .animation({
  1784. // duration: 666,
  1785. // curve: 'ease-in-out' // 可选动画曲线
  1786. // })
  1787. // .width('100%')
  1788. }
  1789. .width('100%')
  1790. .height('100%')
  1791. .alignContent(Alignment.Top)
  1792. Column() {
  1793. this.PlayController()
  1794. }
  1795. .hitTestBehavior(HitTestMode.Transparent)
  1796. .position({ bottom: 0 }) // 将 Row 固定在底部
  1797. .opacity(this.barBottomOpacity)
  1798. }
  1799. .width('100%')
  1800. .height('100%')
  1801. .backgroundImage(this.isCustomizeBg?this.customizeBgPath:$r('app.color.bottom_control_background'))
  1802. .backgroundImageSize(this.isCoverOpacity()?{width:'100%'}:{ height: '100%'})
  1803. .backgroundImagePosition(Alignment.Center)
  1804. .backdropBlur(this.blurValue)
  1805. .backgroundBrightness({rate:this.isCustomizeBg?0.1:0,lightUpDegree:this.bgBrightness})
  1806. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  1807. }
  1808. }
  1809. // 处理文件选择的函数
  1810. handleFileSelection(item: VideoItem, checked: boolean) {
  1811. if (checked) {
  1812. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  1813. this.selectedFiles.push(item);
  1814. }
  1815. } else {
  1816. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  1817. if (index > -1) {
  1818. this.selectedFiles.splice(index, 1);
  1819. }
  1820. }
  1821. }
  1822. showWarnIsDelete() {
  1823. //操作确认类弹出框
  1824. DialogHelper.showAlertDialog({
  1825. content: "确定要删除这些文件吗?",
  1826. transition: AnimationHelper.transitionInUp(666),
  1827. maskColor: Color.Transparent,
  1828. backgroundColor: Color.Grey,
  1829. onAction: (action) => {
  1830. if (action == DialogAction.ONE) {
  1831. // ToastUtil.showToast(`您点击了取消按钮`);
  1832. } else if (action == DialogAction.TWO) {
  1833. // ToastUtil.showToast(`您点击了确认按钮`);
  1834. this.deleteMultipleFiles()
  1835. }
  1836. }
  1837. })
  1838. }
  1839. //多选删除文件
  1840. deleteMultipleFiles() {
  1841. if (ArrayUtil.isNotEmpty(this.selectedFiles)) {
  1842. this.selectedFiles.forEach((item) => {
  1843. Logger.info(TAG, 'delete filePath = ' + item.filePath);
  1844. if (item.type === CommonConstants.TYPE_IS_DIR) {
  1845. this.table.deleteDataForParentPath(item.filePath, () => {
  1846. FileUtil.rmdir(item.filePath).then(() => {
  1847. this.videoLocalList = this.videoLocalList.filter(v => v !== item);
  1848. this.selectedFiles = [];
  1849. this.isMultiSelect = false
  1850. this.isAllSelected = false
  1851. this.cache.delete(this.currentPath);
  1852. this.getSortedFiles(this.currentPath, true);
  1853. }).catch((error: Error) => {
  1854. console.error(error.message);
  1855. });
  1856. });
  1857. } else {
  1858. this.table.deleteData(item, () => {
  1859. FileUtil.unlink(item.filePath).catch((error: Error) => {
  1860. console.error(error.message);
  1861. }).finally(()=>{
  1862. this.videoLocalList = this.videoLocalList.filter(v => v !== item);
  1863. this.selectedFiles = [];
  1864. this.isMultiSelect = false
  1865. this.isAllSelected = false
  1866. this.cache.delete(this.currentPath);
  1867. this.getSortedFiles(this.currentPath, true);
  1868. });
  1869. });
  1870. }
  1871. });
  1872. }
  1873. }
  1874. //多选移动文件
  1875. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  1876. Logger.info('onecold showCutDialogForMultipleFiles')
  1877. let mList: Array<string> = []
  1878. let rPath = this.rootPath
  1879. if (isCurrent) {
  1880. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1881. rPath = this.currentPath
  1882. } else {
  1883. mList = Utility.getNameList(this.dirList);
  1884. rPath = this.rootPath
  1885. }
  1886. let dataBean = new BubbleBean();
  1887. dataBean.data = mList;
  1888. dataBean.color = this.themeColor
  1889. dataBean.onItemClick = (i) => {
  1890. const newDirPath = rPath + '/' + mList[i];
  1891. // Logger.info('newDirPath = ' + newDirPath)
  1892. this.selectedFiles.forEach((item) => {
  1893. const newPath = newDirPath + '/' + item.fileName;
  1894. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  1895. ToastUtil.showToast('移动成功');
  1896. this.table.deleteData(item, () => {
  1897. this.cache.delete(this.currentPath); // 删除原路径缓存
  1898. this.cache.delete(newDirPath); // 删除目标路径缓存
  1899. this.getSortedFiles(this.currentPath, true);
  1900. });
  1901. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1902. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1903. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1904. CommonConstants.TYPE_LOCAL, true);
  1905. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1906. this.table.insert(newItem, (id: number) => {
  1907. //加入数据库
  1908. });
  1909. }
  1910. }).catch((error: Error) => {
  1911. console.error(error.message);
  1912. });
  1913. });
  1914. this.isMultiSelect = false
  1915. this.selectedFiles = [];
  1916. this.isAllSelected = false
  1917. XPopup.dismissTop();
  1918. };
  1919. let pup:XPopup
  1920. if (this.isDarkMode) {
  1921. pup = XPopup.Builder()
  1922. .setPopupPosition(PopupPosition.TOP)
  1923. .atView(viewId)
  1924. .setBackgroundColor(Color.Black)
  1925. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1926. .show();
  1927. }else {
  1928. pup = XPopup.Builder()
  1929. .setPopupPosition(PopupPosition.TOP)
  1930. .atView(viewId)
  1931. .setBackgroundColor(Color.White)
  1932. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1933. .show();
  1934. }
  1935. }
  1936. doFav(item:VideoItem){
  1937. LogUtil.info('onecold doFav isFav=' +item.isFav)
  1938. let isFav = 0
  1939. if(Utility.getIsFav(this.favList,item)){
  1940. isFav = 0
  1941. }else{
  1942. isFav = 1
  1943. }
  1944. this.table.updateIsFavByFilePath(item.filePath,isFav, async (result: boolean) => {
  1945. if(result){
  1946. if(isFav===1){
  1947. ToastUtil.showToast('收藏成功');
  1948. }else{
  1949. ToastUtil.showToast('取消收藏成功');
  1950. }
  1951. this.deleteCache(this.currentPath)
  1952. this.getFavList(false)
  1953. if(this.modeType===0&&!this.isFavMusic){
  1954. LogUtil.info('onecold doFav currentPath ='+ this.currentPath)
  1955. this.getSortedFiles(this.currentPath)
  1956. }
  1957. workerInstance.postMessage({ code: 2, data: this.context });
  1958. workerInstance.postMessage({ code: 3, data: this.context });
  1959. workerInstance.postMessage({ code: 4, data: this.context });
  1960. }
  1961. })
  1962. }
  1963. //多选复制文件
  1964. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  1965. console.log('onecold showCopyDialogForMultipleFiles');
  1966. let mList: Array<string> = []
  1967. let rPath = this.rootPath
  1968. if (isCurrent) {
  1969. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1970. rPath = this.currentPath
  1971. } else {
  1972. mList = Utility.getNameList(this.dirList);
  1973. rPath = this.rootPath
  1974. }
  1975. let dataBean = new BubbleBean();
  1976. dataBean.data = mList;
  1977. dataBean.isCopy = true
  1978. dataBean.color = this.themeColor
  1979. dataBean.onItemClick = (i) => {
  1980. const newDirPath = rPath + '/' + mList[i];
  1981. // Logger.info('newDirPath = ' + newDirPath)
  1982. this.selectedFiles.forEach((item) => {
  1983. const newPath = newDirPath + '/' + item.fileName;
  1984. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  1985. ToastUtil.showToast('复制成功');
  1986. this.cache.delete(newDirPath); // 删除目标路径缓存
  1987. this.getSortedFiles(this.currentPath);
  1988. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1989. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1990. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1991. CommonConstants.TYPE_LOCAL, true);
  1992. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1993. this.table.insert(newItem, (id: number) => {
  1994. //加入数据库
  1995. });
  1996. }
  1997. }).catch((error: Error) => {
  1998. console.error(error.message);
  1999. });
  2000. });
  2001. this.isMultiSelect = false
  2002. this.selectedFiles = [];
  2003. this.isAllSelected = false
  2004. XPopup.dismissTop();
  2005. };
  2006. let pup:XPopup
  2007. if (this.isDarkMode) {
  2008. pup = XPopup.Builder()
  2009. .setPopupPosition(PopupPosition.TOP)
  2010. .atView(viewId)
  2011. .setBackgroundColor(Color.Black)
  2012. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2013. .show();
  2014. }else {
  2015. pup = XPopup.Builder()
  2016. .setPopupPosition(PopupPosition.TOP)
  2017. .atView(viewId)
  2018. .setBackgroundColor(Color.White)
  2019. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2020. .show();
  2021. }
  2022. }
  2023. @Builder
  2024. private DirItem(item: VideoItem, index?: number) {
  2025. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2026. Row() {
  2027. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  2028. $r('app.media.music_group'))
  2029. .height(this.twoFingerType==3?55:this.twoFingerType==2?35:30)
  2030. .width(this.twoFingerType==3?55:this.twoFingerType==2?35:30)
  2031. .fillColor(this.themeColor)
  2032. // .fontSize(33)
  2033. .alt($r('app.media.music_group'))
  2034. .borderRadius('100%')
  2035. .clip(true)
  2036. .margin({ left: 20, top: 8, bottom: 8 })
  2037. Column() {
  2038. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  2039. .fontSize(this.twoFingerType==1?12:this.twoFingerType==2?15:18)
  2040. .maxLines(1)// .width('88%')
  2041. .animation({
  2042. duration: 555,
  2043. curve: 'ease-in-out',
  2044. })
  2045. .transition({
  2046. type: TransitionType.Insert,
  2047. opacity: 0,
  2048. translate: { x: 160 }
  2049. })
  2050. .margin({ left: 10, right: 20 })
  2051. .fontColor($r('app.color.text_color'))
  2052. Row() {
  2053. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  2054. .fontSize(this.twoFingerType==1?11:this.twoFingerType==2?12:14)
  2055. .padding({ top: 8 })
  2056. .visibility(this.modeType === 2? Visibility.Visible : Visibility.None)
  2057. .fontColor($r('app.color.text_color'))
  2058. .margin({ left: 10 })
  2059. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  2060. .fontSize(this.twoFingerType==1?11:this.twoFingerType==2?12:14)
  2061. .padding({ top: 8 })
  2062. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2063. .fontColor($r('app.color.text_color'))
  2064. .margin({ left: 10 })
  2065. Blank()
  2066. }
  2067. }
  2068. .height('100%')
  2069. .layoutWeight(1)
  2070. .justifyContent(FlexAlign.Center)
  2071. .alignItems(HorizontalAlign.Start)
  2072. Blank()
  2073. Image($r('app.media.arrow_right'))
  2074. .height(25)
  2075. .margin({ right: 10 })
  2076. .alignSelf(ItemAlign.Center)
  2077. .id(item.filePath)
  2078. }
  2079. }
  2080. .backgroundColor(Color.Transparent)
  2081. .height(this.twoFingerType==3?ITEM_HEIGHT_BIG:this.twoFingerType==2?ITEM_HEIGHT:ITEM_HEIGHT_SMALL)
  2082. .width('100%')
  2083. .visibility(this.isShowDir(item.name)?Visibility.Visible:Visibility.None)
  2084. .opacity(this.opacityItem) // 绑定透明度
  2085. }
  2086. isShowDir(dirName:string){
  2087. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  2088. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  2089. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  2090. if(dirName ===undefined)
  2091. return true
  2092. if(dirName === LocalMusic.STR_LOCK_VIDEO){
  2093. return this.isShowSimi
  2094. }
  2095. if(dirName === LocalMusic.STR_FAC_VIDEO){
  2096. return this.isShowFAV
  2097. }
  2098. if(dirName === LocalMusic.STR_HISTORY_MUSIC){
  2099. return this.isShowHistory
  2100. }
  2101. return true
  2102. }
  2103. @State opacityItem: number = 1; // 控制透明度的状态变量
  2104. @Builder
  2105. private MusicItem(item: VideoItem, index?: number) {
  2106. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2107. Row() {
  2108. Stack() {
  2109. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  2110. .fillColor(this.themeColor)
  2111. .height(this.twoFingerType==3?55:this.twoFingerType==2?35:30)
  2112. .width(this.twoFingerType==3?55:this.twoFingerType==2?35:30)
  2113. .alt($r('app.media.music_red'))
  2114. .borderRadius('100%')
  2115. .clip(true)
  2116. .opacity(this.opacityItem)// 绑定透明度
  2117. .margin({ left: 20 })
  2118. }
  2119. .width('15%')
  2120. Column() {
  2121. Column() {
  2122. Text(item.name)
  2123. .fontSize(this.twoFingerType==1?12:this.twoFingerType==2?15:18)
  2124. .maxLines(1)
  2125. .animation({
  2126. duration: 555,
  2127. curve: 'Linear',
  2128. })
  2129. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2130. $r('app.color.text_color'))
  2131. .margin({ left:this.twoFingerType==3?18: 10 })
  2132. Row() {
  2133. Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
  2134. .fontSize(this.twoFingerType==1?11:this.twoFingerType==2?12:14)
  2135. .padding({ top: 8 })
  2136. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2137. $r('app.color.text_color'))
  2138. .margin({ left:this.twoFingerType==3?18: 10})
  2139. Blank()
  2140. Text(item.size)
  2141. .fontSize(this.twoFingerType==1?11:this.twoFingerType==2?12:14)
  2142. .padding({ top: 8 })
  2143. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  2144. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2145. $r('app.color.text_color'))
  2146. .margin({ left: 10 })
  2147. }
  2148. }
  2149. .height('100%')
  2150. .width('100%')
  2151. .justifyContent(FlexAlign.Center)
  2152. .alignItems(HorizontalAlign.Start)
  2153. }
  2154. .height('100%')
  2155. .width('65%')
  2156. Column() {
  2157. Checkbox({ name: 'checkbox' + index })
  2158. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  2159. .selectedColor(this.themeColor)
  2160. .shape(CheckBoxShape.CIRCLE)
  2161. .opacity(this.isMultiSelect ? 1 : 0)
  2162. .animation({
  2163. duration: 666,
  2164. curve: 'Smooth' // 可选动画曲线
  2165. })
  2166. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2167. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  2168. .margin({ left: 20, top: 8, bottom: 8 })
  2169. .width(22)
  2170. .height(22)
  2171. ImageAnimator()
  2172. .images(this.imagesF)// 动画数组
  2173. .duration(1000)// 持续
  2174. .state(this.animationState)// 动画状态
  2175. .fillMode(FillMode.Forwards)
  2176. .width(18)
  2177. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  2178. Visibility.None)
  2179. .height(18)
  2180. .iterations(-1) // 播放次数
  2181. }
  2182. .width('18%')
  2183. }
  2184. }
  2185. .backgroundColor(Color.Transparent)
  2186. .width('100%')
  2187. .height(this.twoFingerType==3?ITEM_HEIGHT_BIG:this.twoFingerType==2?ITEM_HEIGHT:ITEM_HEIGHT_SMALL)
  2188. }
  2189. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  2190. @Builder
  2191. tabTitle() {
  2192. Column() {
  2193. // 使用 Stack 布局来实现绝对定位效果
  2194. Stack() {
  2195. // 背景动画容器
  2196. Row() {
  2197. ForEach(this.tabs, (i: string, index) => {
  2198. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2199. Flex()
  2200. .backgroundColor(this.isDarkMode?$r('app.color.tab_item_bg'):this.themeColor)
  2201. .borderRadius(20)
  2202. .padding(10)
  2203. .margin(6)
  2204. .width('100%')
  2205. .height('100%')
  2206. .visibility(this.modeType === index ? Visibility.Visible : Visibility.None)
  2207. .opacity(this.modeType === index ? 1 : 0)
  2208. .animation({
  2209. duration: 666,
  2210. playMode: PlayMode.Normal,
  2211. curve: 'ease-in-out'
  2212. });
  2213. }
  2214. .layoutWeight(1)
  2215. .margin({ left: this.currentBreakpoint !== BreakpointTypeEnum.SM?50:5,
  2216. right: this.currentBreakpoint !== BreakpointTypeEnum.SM?50:5, bottom: 1 });
  2217. });
  2218. }
  2219. .width('100%')
  2220. .height(50);
  2221. // 导航栏容器
  2222. Row() {
  2223. ForEach(this.tabs, (item: string, index) => {
  2224. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2225. Text(item)
  2226. .fontSize(16)
  2227. .fontColor(this.modeType === index ? Color.White : $r('app.color.text_color'))
  2228. .padding(15)
  2229. .onClick(() => {
  2230. this.modeType = index;
  2231. this.onModeChange();
  2232. });
  2233. }
  2234. .layoutWeight(1)
  2235. .stateStyles({
  2236. pressed: { opacity: 0.6 } // 按压反馈
  2237. });
  2238. });
  2239. }
  2240. .width('100%')
  2241. .height(this.topBarHeight)
  2242. .opacity(this.barOpacity)
  2243. .backgroundColor(Color.Transparent);
  2244. }
  2245. .width('100%')
  2246. .height(this.topBarHeight)
  2247. .opacity(this.barOpacity)
  2248. Line().width('100%').height(1).backgroundColor($r('app.color.index_background'))
  2249. .opacity(this.barOpacity)
  2250. .visibility(this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  2251. }
  2252. .visibility(this.isShowTitleBar?Visibility.Visible:Visibility.None)
  2253. }
  2254. @Builder
  2255. listViewTitle() {
  2256. Column() {
  2257. Row({ space: 8 }) {
  2258. Row({ space: 8 }) {
  2259. Image($r("app.media.hm_playlist"))
  2260. .width(25)
  2261. .margin({ left: 8 })
  2262. .fillColor(this.themeColor)
  2263. Text(`共找到${this.artistList.length}位艺术家`)
  2264. .fontColor($r('app.color.text_color'))
  2265. .fontSize(14)
  2266. .opacity(this.opacityItem)
  2267. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  2268. Text(`共找到${this.albumList.length}张专辑`)
  2269. .fontColor($r('app.color.text_color'))
  2270. .opacity(this.opacityItem)
  2271. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2272. .fontSize(14)
  2273. }
  2274. .layoutWeight(1)
  2275. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  2276. Row() {
  2277. TextInput({
  2278. placeholder: this.modeType === 2 ? '输入艺术家名称...' : '输入专辑名称...',
  2279. text: this.searchText
  2280. })
  2281. .height(35)
  2282. .onChange((value: string) => {
  2283. this.onSearchInput(value);
  2284. })
  2285. .layoutWeight(1)
  2286. Text(`取消`)
  2287. .margin({ left: 10, right: 10 })
  2288. .fontColor($r('app.color.text_color'))
  2289. .fontSize(16)
  2290. .onClick(() => {
  2291. this.isSearchMode = false
  2292. this.searchText = ''
  2293. if (this.modeType === 2) {
  2294. this.updateListData(this.artistList)
  2295. } else {
  2296. this.updateListData(this.albumList)
  2297. }
  2298. })
  2299. }
  2300. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  2301. .animation({
  2302. duration: 666,
  2303. curve: 'ease-in-out' // 可选动画曲线
  2304. })
  2305. Blank()
  2306. Image($r("app.media.search"))
  2307. .width(25)
  2308. .visibility(this.modeType === 2 || this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2309. .animation({
  2310. duration: 666,
  2311. curve: 'ease-in-out' // 可选动画曲线
  2312. })// .opacity(this.opacityItem)
  2313. .fillColor(this.themeColor)
  2314. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  2315. .onClick(() => {
  2316. this.isSearchMode = true
  2317. })
  2318. Image($r("app.media.top_rank"))
  2319. .width(25)// .opacity(this.opacityItem)
  2320. .fillColor(this.themeColor)
  2321. .animation({
  2322. duration: 666,
  2323. curve: 'ease-in-out' // 可选动画曲线
  2324. })
  2325. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  2326. .onClick(() => {
  2327. this.showRankDialog()
  2328. })
  2329. Image(this.isGridMusic?$r('app.media.list'):$r("app.media.grid"))
  2330. .width(25)
  2331. .animation({
  2332. duration: 666,
  2333. curve: 'ease-in-out' // 可选动画曲线
  2334. })
  2335. .fillColor(this.themeColor)
  2336. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  2337. .onClick(() => {
  2338. this.isGridMusic = !this.isGridMusic
  2339. })
  2340. }
  2341. .visibility(((this.modeType === 2 || this.modeType === 3) && !this.isCanBack) ? Visibility.Visible :
  2342. Visibility.None)
  2343. .width('100%')
  2344. .padding(10)
  2345. .height(50)
  2346. .border({
  2347. width: { bottom: 1 },
  2348. color: this.isCustomizeBg?Color.Transparent:'#12ec5c87'
  2349. })
  2350. Row({ space: 8 }) {
  2351. Row({ space: 8 }) {
  2352. Image($r("app.media.hm_play"))
  2353. .width(25)
  2354. .margin({ left: 8 })
  2355. .fillColor(this.themeColor)
  2356. Text(`播放全部`)
  2357. .fontColor($r('app.color.text_color'))
  2358. .fontSize(14)
  2359. .animation({
  2360. duration: 666,
  2361. curve: 'ease-in-out' // 可选动画曲线
  2362. })
  2363. Text(`(${Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length}首)`)
  2364. .fontColor($r('app.color.text_color'))
  2365. .fontSize(14)
  2366. .opacity(this.opacityItem)
  2367. .animation({
  2368. duration: 666,
  2369. curve: 'ease-in-out' // 可选动画曲线
  2370. })
  2371. }
  2372. .clickEffect({level:ClickEffectLevel.LIGHT})
  2373. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  2374. .animation({
  2375. duration: 666,
  2376. curve: 'ease-in-out' // 可选动画曲线
  2377. })
  2378. .backgroundColor(this.isClickedPLayAll ? $r('app.color.button_click') : Color.Transparent)
  2379. .onTouch((event: TouchEvent) => {
  2380. if (event.type === TouchType.Down) {
  2381. this.isClickedPLayAll = true;
  2382. } else if (event.type === TouchType.Up || event.type === TouchType.Cancel) {
  2383. this.isClickedPLayAll = false;
  2384. }
  2385. })
  2386. .onClick(() => {
  2387. // ToastUtil.showToast('当前的手机的折叠状态 ='+DisplayUtil.getFoldStatus())
  2388. if (this.modeType === 0) {
  2389. if (ArrayUtil.isNotEmpty(this.getCurFileList())) {
  2390. this.doPlay(this.getCurFileList()[0])
  2391. }
  2392. } else {
  2393. if (ArrayUtil.isNotEmpty(this.mediaKuList)) {
  2394. this.doPlay(this.mediaKuList[0])
  2395. }
  2396. }
  2397. })
  2398. Row() {
  2399. TextInput({ placeholder: '输入名称...', text: this.searchText })
  2400. .height(35)
  2401. .onChange((value: string) => {
  2402. this.onSearchInput(value);
  2403. })
  2404. .layoutWeight(1)
  2405. Text(`取消`)
  2406. .margin({ left: 10, right: 10 })
  2407. .fontColor($r('app.color.text_color'))
  2408. .fontSize(16)
  2409. .onClick(() => {
  2410. this.isSearchMode = false
  2411. this.searchText = ''
  2412. this.updateListData(this.mediaKuList)
  2413. })
  2414. }
  2415. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  2416. .animation({
  2417. duration: 666,
  2418. curve: 'ease-in-out' // 可选动画曲线
  2419. })
  2420. Blank()
  2421. Image($r("app.media.search"))
  2422. .width(25)// .visibility(this.modeType===1?Visibility.Visible:Visibility.None)
  2423. .animation({
  2424. duration: 666,
  2425. curve: 'ease-in-out' // 可选动画曲线
  2426. })// .opacity(this.opacityItem)
  2427. .fillColor(this.themeColor)
  2428. .clickEffect({level:ClickEffectLevel.LIGHT})
  2429. .onClick(() => {
  2430. this.isSearchMode = true
  2431. })
  2432. Image($r("app.media.refresh"))
  2433. .fillColor(this.themeColor)
  2434. .width(25)
  2435. .visibility(this.isHistory || this.isCanBack || this.isSearchMode ? Visibility.None : Visibility.Visible)
  2436. .animation({
  2437. duration: 666,
  2438. curve: 'ease-in-out' // 可选动画曲线
  2439. })
  2440. .clickEffect({level:ClickEffectLevel.LIGHT})
  2441. .onClick(() => {
  2442. if(this.isFavMusic){
  2443. this.getFavList(true)
  2444. }else{
  2445. this.deleteCache(this.currentPath)
  2446. this.getSortedFiles(this.currentPath)
  2447. }
  2448. })
  2449. Image($r("app.media.top_rank"))
  2450. .width(25)
  2451. .visibility(this.isHistory || this.isSearchMode ? Visibility.None :
  2452. Visibility.Visible)// .opacity(this.opacityItem)
  2453. .animation({
  2454. duration: 666,
  2455. curve: 'ease-in-out' // 可选动画曲线
  2456. })
  2457. .fillColor(this.themeColor)
  2458. .clickEffect({level:ClickEffectLevel.HEAVY})
  2459. .onClick(() => {
  2460. this.showRankDialog()
  2461. })
  2462. Image(this.isMultiSelect ? $r("app.media.cancel_multi") : $r("app.media.top_flower"))
  2463. .width(24)
  2464. .visibility(this.isHistory || this.isSearchMode ? Visibility.None : Visibility.Visible)
  2465. .animation({
  2466. duration: 666,
  2467. curve: 'ease-in-out' // 可选动画曲线
  2468. })
  2469. .fillColor(this.themeColor)
  2470. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  2471. .onClick(() => {
  2472. this.isMultiSelect = !this.isMultiSelect
  2473. })
  2474. SymbolGlyph($r('sys.symbol.trash'))
  2475. .fontColor([this.themeColor])
  2476. .fontSize(25)
  2477. .effectStrategy(1)
  2478. .visibility(this.isHistory ? Visibility.Visible : Visibility.None)
  2479. .animation({
  2480. duration: 666,
  2481. curve: 'ease-in-out' // 可选动画曲线
  2482. })
  2483. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  2484. .onClick(() => {
  2485. this.clearVideoHistory() //清空播放记录
  2486. })
  2487. Image(this.isGridMusic?$r('app.media.list'):$r("app.media.grid"))
  2488. .width(24)
  2489. .animation({
  2490. duration: 666,
  2491. curve: 'ease-in-out' // 可选动画曲线
  2492. })
  2493. .fillColor(this.themeColor)
  2494. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  2495. .onClick(() => {
  2496. this.isGridMusic = !this.isGridMusic
  2497. })
  2498. }
  2499. .width('100%')
  2500. .padding(10)
  2501. .height(50)
  2502. .visibility(this.modeType === 0 || this.modeType === 1 || this.isCanBack ? Visibility.Visible : Visibility.None)
  2503. .border({
  2504. width: { bottom: 1 },
  2505. color: this.isCustomizeBg?Color.Transparent:'#12ec5c87'
  2506. })
  2507. }
  2508. .height(this.topBarHeight)
  2509. .opacity(this.barOpacity)
  2510. .visibility(this.isShowAllBar?Visibility.Visible:Visibility.None)
  2511. }
  2512. //搜索功能的实现
  2513. @State searchText: string = ''; // 用户输入内容
  2514. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  2515. @State isSearchMode: boolean = false
  2516. // 实时搜索逻辑(带防抖)
  2517. private onSearchInput(value: string) {
  2518. this.searchText = value.trim();
  2519. let mSearchList: Array<VideoItem> = []
  2520. switch (this.modeType) {
  2521. case 0:
  2522. mSearchList = this.videoLocalList
  2523. break;
  2524. case 1:
  2525. mSearchList = this.mediaKuList
  2526. break;
  2527. case 2:
  2528. mSearchList = this.artistList
  2529. break;
  2530. case 3:
  2531. mSearchList = this.albumList
  2532. break;
  2533. }
  2534. // 新增条件判断:空输入时显示所有数据
  2535. if (this.searchText === '') {
  2536. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  2537. } else {
  2538. this.filteredList = mSearchList.filter((item: VideoItem) => {
  2539. return item.name.toLowerCase().includes(this.searchText.toLowerCase());
  2540. });
  2541. }
  2542. this.updateListData(this.filteredList);
  2543. // this.isSearchMode = false; // 根据业务需求决定是否启用
  2544. }
  2545. @State dragItem: number = -1
  2546. @State scaleItem: number = -1
  2547. @State neighborItem: number = -1
  2548. @State neighborScale: number = -1
  2549. @State offsetY: number = 0
  2550. private dragRefOffset: number = 0
  2551. private ITEM_INTV: number = 78
  2552. scaleSelect(item: number): number {
  2553. if (this.scaleItem === item) {
  2554. return 1.05
  2555. } else if (this.neighborItem === item) {
  2556. return this.neighborScale
  2557. } else {
  2558. return 1
  2559. }
  2560. }
  2561. itemMove(index: number, newIndex: number): void {
  2562. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  2563. return;
  2564. }
  2565. let tmp = this.videoLocalList.splice(index, 1);
  2566. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  2567. this.dataSource.pushArrayData(this.videoLocalList)
  2568. }
  2569. // Grid布局的开始
  2570. private dragRefOffSetX: number = 0;
  2571. private dragRefOffSetY: number = 0;
  2572. private FIX_VP_X: number = 180;
  2573. private FIX_VP_Y: number = 84;
  2574. isDraggable(index: number): boolean {
  2575. return index >= 0;
  2576. }
  2577. getRowEnd(item: number) {
  2578. if (item.toString() === '0') {
  2579. return 1;
  2580. } else {
  2581. return 0;
  2582. }
  2583. }
  2584. // [Start itemMove_start]
  2585. // itemMoveGrid(index: number, newIndex: number): void {
  2586. // if (!this.isDraggable(newIndex)) {
  2587. // return;
  2588. // }
  2589. // let tmp = this.videoLocalList.splice(index, 1);
  2590. // this.videoLocalList.splice(newIndex, 0, tmp[0]);
  2591. // // this.bigItemIndex = this.videoLocalList.findIndex((item) => item === 0);
  2592. // }
  2593. isInLeft(index: number) {
  2594. return index % 2 == 0;
  2595. }
  2596. down(index: number): void {
  2597. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  2598. return;
  2599. }
  2600. this.offsetY -= this.FIX_VP_Y;
  2601. this.dragRefOffSetY += this.FIX_VP_Y;
  2602. this.itemMove(index, index + 1);
  2603. }
  2604. up(index: number): void {
  2605. if (!this.isDraggable(index - 2)) {
  2606. return;
  2607. }
  2608. this.offsetY += this.FIX_VP_Y;
  2609. this.dragRefOffSetY -= this.FIX_VP_Y;
  2610. this.itemMove(index, index - 1);
  2611. }
  2612. left(index: number): void {
  2613. if (this.isInLeft(index)) {
  2614. return;
  2615. }
  2616. if (!this.isDraggable(index - 1)) {
  2617. return;
  2618. }
  2619. this.offsetX += this.FIX_VP_X;
  2620. this.dragRefOffSetX -= this.FIX_VP_X;
  2621. this.itemMove(index, index - 1)
  2622. }
  2623. right(index: number): void {
  2624. if (!this.isInLeft(index)) {
  2625. return;
  2626. }
  2627. if (!this.isDraggable(index + 1)) {
  2628. return;
  2629. }
  2630. this.offsetX -= this.FIX_VP_X;
  2631. this.dragRefOffSetX += this.FIX_VP_X;
  2632. this.itemMove(index, index + 1)
  2633. }
  2634. private scroller: Scroller = new Scroller();
  2635. @State startIndex:number = 0
  2636. @State endIndex:number = 0
  2637. @State scaleValue:number = 1
  2638. @State pinchValue:number = 1
  2639. @Builder
  2640. getGridView(){
  2641. Grid(this.scroller) {
  2642. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  2643. GridItem() {
  2644. Stack({ alignContent: Alignment.Center }) {
  2645. this.MusicItemGrid(item,index)
  2646. }
  2647. }
  2648. // .transition(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }))
  2649. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  2650. TransitionEffect.scale({ x: 0, y: 0 }) ))
  2651. .clickEffect({level:ClickEffectLevel.LIGHT})
  2652. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  2653. .zIndex(this.dragItem === index ? 1 : 0)
  2654. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  2655. .hitTestBehavior(this.isDraggable(this.videoLocalList.indexOf(item)) ? HitTestMode.Default : HitTestMode.None)
  2656. //长按拖动代码
  2657. .gesture(
  2658. GestureGroup(GestureMode.Sequence,
  2659. LongPressGesture({ repeat: true })
  2660. .onAction(() => {
  2661. this.getUIContext().animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  2662. this.scaleItem = index;
  2663. })
  2664. })
  2665. .onActionEnd(() => {
  2666. this.getUIContext().animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  2667. this.scaleItem = -1;
  2668. })
  2669. }),
  2670. PanGesture({ fingers: 1, direction: null, distance: 0 })
  2671. .onActionStart(() => {
  2672. this.dragItem = index;
  2673. this.dragRefOffSetX = 0;
  2674. this.dragRefOffSetY = 0;
  2675. })
  2676. .onActionUpdate((event: GestureEvent) => {
  2677. this.offsetX = event.offsetX - this.dragRefOffSetX;
  2678. this.offsetY = event.offsetY - this.dragRefOffSetY;
  2679. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  2680. let index = this.videoLocalList.indexOf(item);
  2681. if (this.offsetY >= this.FIX_VP_Y / 2 && (this.offsetX <= 44 && this.offsetX >= -44)) {
  2682. this.down(index);
  2683. } else if (this.offsetY <= -this.FIX_VP_Y / 2 && (this.offsetX <= 44 && this.offsetX >= -44)) {
  2684. this.up(index);
  2685. } else if (this.offsetX >= this.FIX_VP_X / 2 && (this.offsetY <= 50 && this.offsetY >= -50)) {
  2686. this.right(index);
  2687. } else if (this.offsetX <= -this.FIX_VP_Y / 2 && (this.offsetY <= 50 && this.offsetY >= -50)) {
  2688. this.left(index);
  2689. }
  2690. })
  2691. // if (this.offsetY > this.FIX_VP_Y * 0.7) {
  2692. // this.scroller.scrollToIndex(index + 10, true,ScrollAlign.CENTER);
  2693. // }
  2694. })
  2695. .onActionEnd(() => {
  2696. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  2697. this.dragItem = -1;
  2698. })
  2699. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150 }, () => {
  2700. this.scaleItem = -1;
  2701. })
  2702. })
  2703. )
  2704. .onCancel(() => {
  2705. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  2706. this.dragItem = -1;
  2707. })
  2708. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150 }, () => {
  2709. this.scaleItem = -1;
  2710. })
  2711. })
  2712. )
  2713. // [End gesture_start]
  2714. // [EndExclude GridItem_start]
  2715. }, (item: VideoItem) => item.filePath)
  2716. }
  2717. .width('94%')
  2718. .height('100%')
  2719. .editMode(true)
  2720. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  2721. .animation({ duration: 500, curve: Curve.Ease }))
  2722. .margin({ bottom: this.isCoverOpacity() ? 80 : 175 })
  2723. .layoutWeight(1)
  2724. .scrollBar(BarState.Off)
  2725. .supportAnimation(true)
  2726. .cachedCount(3)
  2727. // .columnsTemplate('1fr '.repeat(this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM ? 2 : 5))
  2728. .columnsTemplate(this.twoFingerType==3?'repeat(auto-fit, 160)':this.twoFingerType==2?'repeat(auto-fit, 110)':'repeat(auto-fit, 80)')
  2729. .rowsGap(this.twoFingerType==3?10:this.twoFingerType==2?5:1)
  2730. .visibility(this.isGridMusic?Visibility.Visible:Visibility.None)
  2731. .scale({x:this.scaleValue,y:this.scaleValue,z:1})
  2732. .gesture(PinchGesture({ fingers: 2 })
  2733. .onActionEnd((event: GestureEvent)=>{
  2734. this.setGridTwoFingers()
  2735. })
  2736. .onActionUpdate(e=>{
  2737. this.scaleValue = this.pinchValue*e.scale
  2738. })
  2739. .onActionStart(e => {
  2740. }))
  2741. .enableScrollInteraction(true)
  2742. // 滚轴滑动,记录下滑动时的起始位置和终点位置
  2743. .onScrollIndex((start: number, end: number) => {
  2744. this.startIndex = start
  2745. this.endIndex = end
  2746. })
  2747. .onScrollFrameBegin((offset: number) => {
  2748. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  2749. if(this.isPhoneLan()){
  2750. this.setBarHeightHide(offset)
  2751. }else if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  2752. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  2753. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  2754. if(this.isScrollHide){
  2755. this.setBarHeightHide2(offset)
  2756. }else{
  2757. this.setBarHeightNormal()
  2758. }
  2759. }else{
  2760. this.setBarHeightHide(offset)
  2761. }
  2762. return { offsetRemain: offset };
  2763. })
  2764. }
  2765. setGridTwoFingers(){
  2766. this.pinchValue = this.scaleValue;
  2767. Logger.info('this.pinchValue = '+this.pinchValue);
  2768. if(this.pinchValue >=1){
  2769. this.twoFingerType ++
  2770. Logger.info('this.twoFingerType1 = '+this.twoFingerType);
  2771. if(this.twoFingerType > 3){
  2772. this.twoFingerType = 3
  2773. }
  2774. }else{
  2775. this.twoFingerType --
  2776. Logger.info('this.twoFingerType2 = '+this.twoFingerType);
  2777. if(this.twoFingerType < 1){
  2778. this.twoFingerType = 3
  2779. this.isGridMusic = false
  2780. }
  2781. }
  2782. this.pinchValue = 1;
  2783. this.scaleValue = 1;
  2784. }
  2785. @State longItemFilePath:string =''
  2786. @State tempLyricContent:string = ''
  2787. @Builder
  2788. private MusicItemGrid(item: VideoItem, index: number) {
  2789. Button({ type: ButtonType.Normal, stateEffect: false }) {
  2790. Stack() {
  2791. Column() {
  2792. Image(StrUtil.isEmpty(item.pixelMapPath) ?Utility.getMusisBg2(index) : item.pixelMapPath)
  2793. .height(this.getGridHeight())
  2794. .width(this.getGridWight())
  2795. .alt($r('app.media.ic_avatar6'))
  2796. .clip(true)
  2797. .borderRadius({
  2798. topLeft: 12,
  2799. topRight : 12,
  2800. bottomLeft: 0,
  2801. bottomRight: 0
  2802. })
  2803. .draggable(false)
  2804. .opacity(this.opacityItem)// 绑定透明度
  2805. .animation({ curve: Curve.Sharp, duration: 300 })
  2806. .margin({ left: this.currentBreakpoint !== BreakpointTypeEnum.SM?40:20 ,
  2807. right: this.currentBreakpoint !== BreakpointTypeEnum.SM?40:20})
  2808. Column() {
  2809. Text(item.name.startsWith('.')?item.name.replace(/\./g, ''):item.name)
  2810. .fontSize(this.twoFingerType==1?14:this.twoFingerType==2?16:18)
  2811. .maxLines(1)
  2812. .fontWeight(FontWeight.Bold)
  2813. .textOverflow({overflow: TextOverflow.MARQUEE}) //超长滚动
  2814. .animation({
  2815. duration: 555,
  2816. curve: 'Linear',
  2817. })
  2818. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2819. $r('app.color.text_color'))
  2820. Column(){
  2821. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  2822. .fontSize(11)
  2823. .fontSize(this.twoFingerType==1?10:this.twoFingerType==2?12:14)
  2824. .visibility(this.modeType===2&&!this.isCanBack?Visibility.Visible:Visibility.None)
  2825. .fontColor($r('app.color.text_color'))
  2826. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  2827. .fontSize(11)
  2828. .fontSize(this.twoFingerType==1?10:this.twoFingerType==2?12:14)
  2829. .visibility(this.modeType===3&&!this.isCanBack?Visibility.Visible:Visibility.None)
  2830. .fontColor($r('app.color.text_color'))
  2831. Text(StrUtil.isEmpty(item.artist) ? 'Unknown' : item.artist )
  2832. .fontSize(11)
  2833. .fontSize(this.twoFingerType==1?10:this.twoFingerType==2?12:14)
  2834. .maxLines(1)
  2835. .margin({top:2})
  2836. .visibility(item.type==CommonConstants.TYPE_IS_ARTIST
  2837. ||item.type==CommonConstants.TYPE_IS_ALBUM
  2838. ||item.type==CommonConstants.TYPE_IS_DIR?Visibility.None:Visibility.Visible)
  2839. .fontWeight(FontWeight.Medium)
  2840. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor:
  2841. $r('app.color.text_color'))
  2842. }
  2843. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  2844. }
  2845. .bindPopup(this.longItemFilePath === item.filePath, {
  2846. builder: this.MenuBuilder(item,index,item.filePath),
  2847. placement: Placement.Top,
  2848. // autoCancel: true,
  2849. mask: {color:'#33000000'},
  2850. // popupColor: Color.Yellow,
  2851. enableArrow: false,//是否显示箭头
  2852. showInSubWindow: false,
  2853. onStateChange: (e) => {
  2854. if (!e.isVisible) {
  2855. this.longItemFilePath = ''
  2856. this.tempLyricContent = ''
  2857. }
  2858. }
  2859. })
  2860. .gesture(LongPressGesture()
  2861. .onAction(async () => {
  2862. //如果是专辑和艺术家的首页,不能长按
  2863. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2864. return
  2865. //如果是我的收藏 最近播放等也不能长按
  2866. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2867. item.name === LocalMusic.STR_HISTORY_MUSIC
  2868. )
  2869. return
  2870. this.longItemFilePath = item.filePath
  2871. this.tempLyricContent = await this.getLyricContent(item)
  2872. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2873. })
  2874. .onActionEnd((event: GestureEvent) => {
  2875. })
  2876. )
  2877. .height(this.twoFingerType==3?60:this.twoFingerType==2?55:42)
  2878. .width(this.getGridWight())
  2879. .justifyContent(FlexAlign.Center)
  2880. .margin({ left: this.currentBreakpoint !== BreakpointTypeEnum.SM?40:20 ,
  2881. right: this.currentBreakpoint !== BreakpointTypeEnum.SM?40:20})
  2882. }
  2883. .width(this.getGridWight())
  2884. .borderRadius(12)
  2885. .backgroundImage(item.pixelMapPath)
  2886. .backgroundImageSize({ height: '100%',width:'100%' })
  2887. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  2888. .animation({ curve: Curve.Sharp, duration: 300 })
  2889. Checkbox({ name: 'checkbox' + index })
  2890. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  2891. .selectedColor(this.themeColor)
  2892. .shape(CheckBoxShape.CIRCLE)
  2893. .opacity(this.isMultiSelect ? 1 : 0)
  2894. .animation({
  2895. duration: 666,
  2896. curve: 'Smooth' // 可选动画曲线
  2897. })
  2898. .visibility(this.isMultiSelect&&item.type!==CommonConstants.TYPE_IS_DIR?Visibility.Visible:Visibility.None)
  2899. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  2900. .margin({ left: 20, top: 8, bottom: 8 })
  2901. .width(38)
  2902. .height(38)
  2903. }
  2904. }
  2905. .backgroundColor(Color.Transparent)
  2906. .width('100%')
  2907. .padding({top:15})
  2908. .height(this.getGridAllHeight())
  2909. .onClick(() => {
  2910. if(this.isMultiSelect&&item.type!==CommonConstants.TYPE_IS_DIR){
  2911. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  2912. this.handleFileSelection(item, !isChecked);
  2913. }else{
  2914. this.doPlay(item, index)
  2915. }
  2916. })
  2917. }
  2918. getGridAllHeight(){
  2919. let heightG = 222
  2920. switch (this.twoFingerType){
  2921. case 1:
  2922. heightG = 118
  2923. break;
  2924. case 2:
  2925. heightG = 168
  2926. break;
  2927. case 3:
  2928. heightG = 222
  2929. break;
  2930. }
  2931. return heightG
  2932. }
  2933. getGridHeight(){
  2934. let heightG = 150
  2935. switch (this.twoFingerType){
  2936. case 1:
  2937. heightG = 55
  2938. break;
  2939. case 2:
  2940. heightG = 100
  2941. break;
  2942. case 3:
  2943. heightG = 150
  2944. break;
  2945. }
  2946. return heightG
  2947. }
  2948. getGridWight(){
  2949. let wightG = 158
  2950. switch (this.twoFingerType){
  2951. case 1:
  2952. wightG = 80
  2953. break;
  2954. case 2:
  2955. wightG = 110
  2956. break;
  2957. case 3:
  2958. wightG = 158
  2959. break;
  2960. }
  2961. return wightG
  2962. }
  2963. @Builder
  2964. MenuBuilder(item: VideoItem,index: number,filePath:string) {
  2965. Scroll(){
  2966. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  2967. Menu() {
  2968. MenuItem({
  2969. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList,item)?$r('sys.symbol.heart_fill'):$r('sys.symbol.heart')),
  2970. content: Utility.getIsFav(this.favList,item)?'取消收藏':'收藏' })
  2971. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  2972. .onClick(() => {
  2973. if(item){
  2974. this.doFav(item)
  2975. }
  2976. this.longItemFilePath = ''
  2977. })
  2978. MenuItem({ symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  2979. content: '下一首播放' })
  2980. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  2981. .onClick(() => {
  2982. this.addToNextPlay(item);
  2983. this.longItemFilePath = ''
  2984. })
  2985. MenuItem({ symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  2986. content: '编辑信息' })
  2987. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  2988. height:this.isCoverOpacity()?'95%': '88%',
  2989. dragBar: true,
  2990. showClose: true,
  2991. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  2992. title: { title: '编辑信息' }
  2993. })
  2994. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  2995. .onClick(() => {
  2996. this.isShowEdit = !this.isShowEdit;
  2997. })
  2998. MenuItem({
  2999. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  3000. content: $r('app.string.rename')
  3001. })
  3002. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  3003. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3004. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  3005. .onClick(() => {
  3006. this.showReNameDialog(item, index + '', filePath)
  3007. this.longItemFilePath = ''
  3008. })
  3009. MenuItem({
  3010. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  3011. content: $r('app.string.delete')
  3012. })
  3013. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  3014. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3015. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  3016. .onClick(() => {
  3017. this.showWarnIsDeleteFile(item, index + '', filePath)
  3018. this.longItemFilePath = ''
  3019. })
  3020. MenuItem({
  3021. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  3022. content: $r('app.string.share')
  3023. })
  3024. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3025. .onClick(() => {
  3026. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  3027. this.longItemFilePath = ''
  3028. })
  3029. }
  3030. .font({ size: 15, weight: FontWeight.Normal })
  3031. }
  3032. .width(180)
  3033. }
  3034. .height(item.type === CommonConstants.TYPE_IS_DIR ?'22%':'40%')
  3035. }
  3036. private listMaxScrollOffsetY: number = 0
  3037. @State selectedIndex: number = -1
  3038. setlistTwoFingers() {
  3039. this.pinchValue = this.scaleValue;
  3040. Logger.info('this.pinchValue = ' + this.pinchValue);
  3041. if (this.pinchValue >= 1) {
  3042. this.twoFingerType++
  3043. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  3044. if (this.twoFingerType > 3) {
  3045. this.twoFingerType = 1
  3046. this.isGridMusic = true
  3047. }
  3048. } else {
  3049. this.twoFingerType--
  3050. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  3051. if (this.twoFingerType < 1) {
  3052. this.twoFingerType = 1
  3053. }
  3054. }
  3055. this.pinchValue = 1;
  3056. this.scaleValue = 1;
  3057. }
  3058. @Builder
  3059. getListView() {
  3060. List({ scroller: this.listScroller }) {
  3061. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3062. ListItem() {
  3063. Column() {
  3064. if (item.type === CommonConstants.TYPE_IS_DIR
  3065. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  3066. this.DirItem(item, index)
  3067. } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
  3068. //穿山甲
  3069. // if (this.isShowAd) {
  3070. // Row() {
  3071. // NodeContainer(this.bannerAd.getAdComponent())
  3072. // .width('92%')
  3073. // .height(this.mAdSlot.getAcceptHeight())
  3074. // .alignSelf(ItemAlign.Center)
  3075. // .align(Alignment.Center)
  3076. // // .margin({left:10})
  3077. // Image($r('app.media.close'))
  3078. // .height(15)
  3079. // .aspectRatio(1)
  3080. // .visibility(Visibility.None)
  3081. // .margin({ right: 15 })// .position({ x:20 })
  3082. // .onClick(() => {
  3083. // this.isShowAd = false
  3084. // })
  3085. // Blank()
  3086. // }
  3087. // .opacity(this.opacityItem) // 绑定透明度
  3088. //
  3089. // }
  3090. } else {
  3091. this.MusicItem(item, index)
  3092. }
  3093. }
  3094. .shadow(this.scaleItem === index ? {
  3095. radius: 70,
  3096. color: '#15000000',
  3097. offsetX: 0,
  3098. offsetY: 0
  3099. } :
  3100. {
  3101. radius: 0,
  3102. color: '#15000000',
  3103. offsetX: 0,
  3104. offsetY: 0
  3105. })
  3106. .animation({ curve: Curve.Sharp, duration: 300 })
  3107. }
  3108. // .transition(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }))
  3109. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  3110. TransitionEffect.scale({ x: 0, y: 0 }) ))
  3111. .clickEffect({level:ClickEffectLevel.LIGHT})
  3112. .swipeAction((
  3113. (this.modeType==0||this.modeType==1 ||((this.modeType==3||this.modeType==2)&&this.isCanBack))
  3114. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  3115. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath) } : {}) //左滑
  3116. .onClick(() => {
  3117. if(this.isMultiSelect&&item.type!==CommonConstants.TYPE_IS_DIR){
  3118. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3119. this.handleFileSelection(item, !isChecked);
  3120. }else{
  3121. this.doPlay(item, index)
  3122. }
  3123. })
  3124. //拖动List关键代码开始
  3125. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  3126. .zIndex(this.dragItem === index ? 1 : 0)
  3127. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  3128. .gesture(
  3129. GestureGroup(GestureMode.Sequence,
  3130. LongPressGesture({ repeat: true })
  3131. .onAction((event?: GestureEvent) => {
  3132. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3133. this.scaleItem = index
  3134. })
  3135. })
  3136. .onActionEnd(() => {
  3137. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3138. this.scaleItem = -1
  3139. })
  3140. }),
  3141. PanGesture({ fingers: 1, direction: null, distance: 0 })
  3142. .onActionStart(() => {
  3143. this.dragItem = index // 记录当前拖动项索引
  3144. this.dragRefOffset = 0 // 重置偏移基准
  3145. })
  3146. .onActionUpdate((event: GestureEvent) => {
  3147. this.offsetY = event.offsetY - this.dragRefOffset;
  3148. this.neighborItem = -1;
  3149. let indexA = this.videoLocalList.indexOf(item);
  3150. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  3151. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  3152. let value: number = 0;
  3153. if (this.offsetY < 0) {
  3154. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  3155. this.neighborItem = indexA - 1;
  3156. this.neighborScale = 1 - value / 20;
  3157. } else if (this.offsetY > 0) {
  3158. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  3159. this.neighborItem = indexA + 1;
  3160. this.neighborScale = 1 - value / 20;
  3161. }
  3162. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  3163. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3164. this.offsetY -= this.ITEM_INTV;
  3165. this.dragRefOffset += this.ITEM_INTV;
  3166. this.itemMove(indexA, indexA + 1);
  3167. });
  3168. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  3169. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3170. this.offsetY += this.ITEM_INTV;
  3171. this.dragRefOffset -= this.ITEM_INTV;
  3172. this.itemMove(indexA, indexA - 1);
  3173. });
  3174. }
  3175. let curListOffset = this.listScroller.currentOffset()
  3176. // 获取手指信息
  3177. let fingerInfo = event.fingerList[0]
  3178. let clickPercentY =
  3179. (fingerInfo.globalY - Number(this.listArea.globalPosition.y)) / Number(this.listArea.height)
  3180. if (clickPercentY > 0.8 && !this.listScroller.isAtEnd()) {
  3181. let scrollVelocity = clickPercentY > 0.9 ? 4 : 2
  3182. if (this.listMaxScrollOffsetY - curListOffset.yOffset > scrollVelocity + 5) {
  3183. this.listScroller.scrollTo({xOffset: 0, yOffset: curListOffset.yOffset += scrollVelocity})
  3184. }
  3185. } else if (clickPercentY < 0.2 && curListOffset.yOffset >= 0) {
  3186. let scrollVelocity = clickPercentY < 0.1 ? 4 : 2
  3187. if (curListOffset.yOffset > scrollVelocity + 5) {
  3188. this.listScroller.scrollTo({xOffset: 0, yOffset: curListOffset.yOffset -= scrollVelocity})
  3189. }
  3190. }
  3191. })
  3192. .onActionEnd((event: GestureEvent) => {
  3193. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3194. this.dragItem = -1
  3195. this.neighborItem = -1
  3196. })
  3197. animateTo({
  3198. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  3199. }, () => {
  3200. this.scaleItem = -1
  3201. })
  3202. })
  3203. )
  3204. .onCancel(() => {
  3205. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3206. this.dragItem = -1
  3207. this.neighborItem = -1
  3208. })
  3209. animateTo({
  3210. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  3211. }, () => {
  3212. this.scaleItem = -1
  3213. })
  3214. })
  3215. ) //拖动List关键代码结束
  3216. }, (item: VideoItem) => item.filePath)
  3217. }
  3218. .scale({x:this.scaleValue,y:this.scaleValue,z:1})
  3219. .gesture(PinchGesture({ fingers: 2 })
  3220. .onActionEnd((event: GestureEvent)=>{
  3221. this.setlistTwoFingers()
  3222. })
  3223. .onActionUpdate(e=>{
  3224. this.scaleValue = this.pinchValue*e.scale
  3225. })
  3226. .onActionStart(e => {
  3227. }))
  3228. // .divider({ strokeWidth: 1, color: this.isDarkMode? '#333333':'#ffe9f0f0' })
  3229. .margin({ bottom: this.isCoverOpacity() ? 80 : 166 })
  3230. .cachedCount(6)
  3231. .borderRadius(20)
  3232. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3233. .animation({ duration: 500, curve: Curve.Ease }))
  3234. .layoutWeight(1)
  3235. .onScrollIndex((start) => {
  3236. this.selectedIndex = start
  3237. })
  3238. .visibility(this.isGridMusic?Visibility.None:Visibility.Visible)
  3239. .lanes(
  3240. new BreakpointType<number>({
  3241. sm: 1,
  3242. md: 2,
  3243. lg: 3,
  3244. xl: 4,
  3245. xxl: 4
  3246. }).getValue(this.currentBreakpoint),
  3247. new BreakpointType<number>({
  3248. sm: 0,
  3249. md: 12,
  3250. lg: 16,
  3251. xl: 18,
  3252. xxl: 20
  3253. }).getValue(this.currentBreakpoint)
  3254. )
  3255. .onAreaChange((oldValue: Area, newValue: Area) => {
  3256. this.listArea = newValue
  3257. if(this.twoFingerType==3){
  3258. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  3259. }else if(this.twoFingerType==2){
  3260. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  3261. }else if(this.twoFingerType==1){
  3262. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  3263. }
  3264. })
  3265. .onScrollFrameBegin((offset: number) => {
  3266. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  3267. if(this.isPhoneLan()){
  3268. this.setBarHeightHide(offset)
  3269. }else if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  3270. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  3271. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  3272. if(this.isScrollHide){
  3273. this.setBarHeightHide2(offset)
  3274. }else{
  3275. this.setBarHeightNormal()
  3276. }
  3277. }else{
  3278. this.setBarHeightHide(offset)
  3279. }
  3280. return { offsetRemain: offset };
  3281. })
  3282. }
  3283. setBarHeightNormal(){
  3284. this.hideDone = false;
  3285. this.getUIContext().animateTo({
  3286. duration: 300
  3287. }, () => {
  3288. this.bottomBarHeight = 55 + 0;
  3289. this.topBarHeight = 50 + 0;
  3290. this.barOpacity = 1;
  3291. this.barBottomOpacity = 1
  3292. this.currentYOffset = 0;
  3293. this.isHiding = false;
  3294. });
  3295. }
  3296. setBarHeightHide(offset: number){
  3297. if (offset > 0 && !this.hideDone) {
  3298. this.currentYOffset += offset;
  3299. if (this.currentYOffset <= 100) {
  3300. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  3301. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  3302. this.barOpacity = 1 - this.currentYOffset / 100;
  3303. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  3304. } else {
  3305. this.topBarHeight = 0;
  3306. this.bottomBarHeight = 0;
  3307. this.barBottomOpacity = 0
  3308. this.barOpacity = 0;
  3309. this.hideDone = true;
  3310. }
  3311. this.isHiding = true;
  3312. }
  3313. if (offset < 0 && this.isHiding) {
  3314. this.hideDone = false;
  3315. this.getUIContext().animateTo({
  3316. duration: 300
  3317. }, () => {
  3318. this.bottomBarHeight = 55 + 0;
  3319. this.topBarHeight = 50 + 0;
  3320. this.barOpacity = 1;
  3321. this.barBottomOpacity = 1
  3322. this.currentYOffset = 0;
  3323. this.isHiding = false;
  3324. });
  3325. }
  3326. }
  3327. //这个方法没隐藏bottomBar,只隐藏topbar
  3328. setBarHeightHide2(offset: number){
  3329. if (offset > 0 && !this.hideDone) {
  3330. this.currentYOffset += offset;
  3331. if (this.currentYOffset <= 100) {
  3332. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  3333. this.barOpacity = 1 - this.currentYOffset / 100;
  3334. } else {
  3335. this.topBarHeight = 0;
  3336. this.barOpacity = 0;
  3337. this.hideDone = true;
  3338. }
  3339. this.isHiding = true;
  3340. }
  3341. if (offset < 0 && this.isHiding) {
  3342. this.hideDone = false;
  3343. this.getUIContext().animateTo({
  3344. duration: 300
  3345. }, () => {
  3346. this.topBarHeight = 50 + 0;
  3347. this.barOpacity = 1;
  3348. this.currentYOffset = 0;
  3349. this.isHiding = false;
  3350. });
  3351. }
  3352. }
  3353. private doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean) {
  3354. switch (item.type) {
  3355. case CommonConstants.TYPE_IS_DIR:
  3356. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  3357. this.showVerifyDialog()
  3358. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  3359. this.titleBarModel.setTitleName('最近播放')
  3360. //加载动画效果
  3361. this.updateListData(this.historyList,true)
  3362. // this.videoLocalList = this.historyList
  3363. if (ArrayUtil.isEmpty(this.historyList)) {
  3364. ToastUtil.showToast('最近播放记录空空如也')
  3365. }
  3366. this.isHistory = true
  3367. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3368. } else if(item.name === LocalMusic.STR_FAC_VIDEO){
  3369. this.titleBarModel.setTitleName('我的收藏')
  3370. //加载动画效果
  3371. this.updateListData(this.favList)
  3372. if(ArrayUtil.isEmpty(this.favList)){
  3373. ToastUtil.showToast('无音乐收藏记录')
  3374. }
  3375. this.isFavMusic = true
  3376. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3377. }else {
  3378. this.currentPath = item.filePath
  3379. this.getSortedFiles(this.currentPath)
  3380. }
  3381. break;
  3382. case CommonConstants.TYPE_IS_ARTIST:
  3383. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  3384. let offsetA = 0
  3385. if (this.isGridMusic) {
  3386. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  3387. let cur = this.scroller.currentOffset()
  3388. if (cur && typeof cur.yOffset === 'number') {
  3389. offsetA = cur.yOffset
  3390. }
  3391. }
  3392. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  3393. } else {
  3394. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  3395. let cur = this.listScroller.currentOffset()
  3396. if (cur && typeof cur.yOffset === 'number') {
  3397. offsetA = cur.yOffset
  3398. }
  3399. }
  3400. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  3401. }
  3402. let mList = this.artistMap.get(item.name)
  3403. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  3404. Utility.doSortListAscending(mList)
  3405. this.isCanBack = true
  3406. this.titleBarModel.setTitleName(item.name)
  3407. this.updateListData(mList)
  3408. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3409. }
  3410. break;
  3411. case CommonConstants.TYPE_IS_ALBUM:
  3412. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  3413. let offset = 0
  3414. if (this.isGridMusic) {
  3415. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  3416. let cur = this.scroller.currentOffset()
  3417. if (cur && typeof cur.yOffset === 'number') {
  3418. offset = cur.yOffset
  3419. }
  3420. }
  3421. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  3422. } else {
  3423. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  3424. let cur = this.listScroller.currentOffset()
  3425. if (cur && typeof cur.yOffset === 'number') {
  3426. offset = cur.yOffset
  3427. }
  3428. }
  3429. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  3430. }
  3431. let albumList = this.albumMap.get(item.name)
  3432. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  3433. Utility.doSortListAscending(albumList)
  3434. this.isCanBack = true
  3435. this.titleBarModel.setTitleName(item.name)
  3436. this.updateListData(albumList)
  3437. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3438. this.mScrollMap.set(item.name, this.selectedIndex)
  3439. }
  3440. break;
  3441. case CommonConstants.TYPE_IS_CSJAD:
  3442. return
  3443. break;
  3444. case CommonConstants.TYPE_LOCAL:
  3445. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  3446. this.stop();
  3447. }
  3448. if (isFromSonPlayList) { //点击来自右下角的播放列表
  3449. this.currentSong = item
  3450. if (index !== undefined) {
  3451. this.curIndex = index
  3452. }
  3453. } else {
  3454. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  3455. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  3456. this.songList = globalVideoList
  3457. this.sonDataSource.pushArrayData(this.songList)
  3458. this.currentSong = globalVideoList[this.curIndex]
  3459. }
  3460. this.videoUrl = this.currentSong.filePath
  3461. this.name = this.currentSong.name
  3462. this.cover = this.currentSong.pixelMapPath
  3463. this.artist = this.currentSong.artist
  3464. LogUtil.info('this.currentSong.duration ='+this.currentSong.duration)
  3465. LogUtil.info('this.currentSong.sampleRate ='+this.currentSong.sampleRate)
  3466. LogUtil.info('this.currentSongmimeType ='+this.currentSong.mimeType)
  3467. this.startPlayOrResumePlay()
  3468. break;
  3469. }
  3470. }
  3471. @Builder
  3472. PlayController() {
  3473. Column() {
  3474. Line().width('100%').height(1).backgroundColor($r('app.color.index_background'))
  3475. .visibility(this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  3476. Row() {
  3477. Row() {
  3478. RotatingCover({ songLabel: this.currentSong?.pixelMapPath })
  3479. Column() {
  3480. Text(this.currentSong?.name)
  3481. .fontSize(13)
  3482. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3483. .maxLines(1)
  3484. .fontColor($r('app.color.text_color'))
  3485. .fontWeight(500)
  3486. Row() {
  3487. Text(this.currentSong?.artist)
  3488. .margin({ top: 2 })
  3489. .fontSize(11)
  3490. .fontColor($r('app.color.text_color'))
  3491. }
  3492. }
  3493. .alignItems(HorizontalAlign.Start)
  3494. .margin({ right: 22 })
  3495. }
  3496. .layoutWeight(1)
  3497. .onClick(() => {
  3498. if (ArrayUtil.isNotEmpty(this.songList)) {
  3499. this.isShowPlay = true;
  3500. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  3501. this.initLyric(lyricPath);
  3502. } else {
  3503. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  3504. }
  3505. })
  3506. Row() {
  3507. Image($r('app.media.hm_previous'))
  3508. .height(24)
  3509. .width(24)
  3510. .clickEffect({level:ClickEffectLevel.HEAVY})
  3511. .margin({ left: 8, right: 16 })
  3512. .fillColor(this.themeColor)
  3513. .displayPriority(2)
  3514. .onClick(() => {
  3515. if (ArrayUtil.isNotEmpty(this.songList)) {
  3516. this.playPrevious()
  3517. } else {
  3518. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  3519. }
  3520. })
  3521. //播放进度条
  3522. Stack() {
  3523. Progress({
  3524. value: Math.floor(this.progressValue),
  3525. type: ProgressType.Ring,
  3526. })
  3527. .color(this.themeColor)// 进度条前景色为灰色
  3528. .backgroundColor($r('app.color.index_background'))
  3529. .height(36)
  3530. .aspectRatio(CommonConstants.ASPECT_RATIO)
  3531. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ? $r('app.media.hm_pause') : $r('app.media.hm_play2'))
  3532. .height(32)
  3533. .width(32)
  3534. .displayPriority(3)
  3535. .clickEffect({level:ClickEffectLevel.HEAVY})
  3536. .fillColor(this.themeColor)
  3537. .onClick(() => {
  3538. if (ArrayUtil.isNotEmpty(this.songList)) {
  3539. this.playOrPause()
  3540. } else {
  3541. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  3542. }
  3543. })
  3544. }
  3545. Image($r('app.media.hm_next'))
  3546. .height(24)
  3547. .width(24)
  3548. .margin({
  3549. right: 16,
  3550. left: 16
  3551. })
  3552. .fillColor(this.themeColor)
  3553. .clickEffect({level:ClickEffectLevel.HEAVY})
  3554. .displayPriority(2)
  3555. .onClick(() => {
  3556. if (ArrayUtil.isNotEmpty(this.songList)) {
  3557. this.playNext()
  3558. } else {
  3559. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  3560. }
  3561. })
  3562. Image($r('app.media.hm_playlist'))
  3563. .height(24)
  3564. .width(24)
  3565. .displayPriority(1)
  3566. .clickEffect({level:ClickEffectLevel.HEAVY})
  3567. .fillColor(this.themeColor)
  3568. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  3569. height: '95%',
  3570. dragBar: true,
  3571. showClose: true,
  3572. blurStyle: BlurStyle.Thin,
  3573. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3574. backgroundColor: Color.Transparent,
  3575. title: {
  3576. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  3577. + `(${this.songList.length}首)`
  3578. }
  3579. })
  3580. .onClick(() => {
  3581. if (ArrayUtil.isNotEmpty(this.songList)) {
  3582. this.isShowSheet = !this.isShowSheet;
  3583. this.isFrontWhite = false
  3584. LogUtil.info('onecold scrollToIndex = '+this.curIndex)
  3585. setTimeout(() => {
  3586. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  3587. }, 123)
  3588. } else {
  3589. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  3590. }
  3591. })
  3592. }
  3593. }
  3594. .width('100%')
  3595. .height(this.bottomBarHeight)
  3596. .justifyContent(FlexAlign.Center)
  3597. .hitTestBehavior(HitTestMode.Transparent)
  3598. .backgroundColor(this.isCustomizeBg?Color.Transparent:$r('app.color.bottom_control_background'))
  3599. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  3600. // modalTransition: ModalTransition.DEFAULT,
  3601. transition: AnimationHelper.transitionInDown(666),
  3602. backgroundColor: 'rgba(0, 0, 0, 0.9)',
  3603. })
  3604. .padding({
  3605. left: 16,
  3606. right: 16
  3607. })
  3608. Line().width('100%').height(25).backgroundColor($r('app.color.bottom_control_background'))
  3609. // .visibility(this.isPhoneLan()?Visibility.None:this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  3610. .visibility(this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  3611. }
  3612. .clickEffect({level:ClickEffectLevel.HEAVY})
  3613. }
  3614. @State isFrontWhite: boolean = false
  3615. //播放列表布局
  3616. @Builder
  3617. PlayListSheet() {
  3618. Column() {
  3619. this.PlayList()
  3620. }
  3621. .width('100%')
  3622. .height('100%')
  3623. }
  3624. @State titleStr: string = ''
  3625. @State ablumStr: string = ''
  3626. @State artistStr: string = ''
  3627. @State lyricConStr: string = ''
  3628. @State currentEditItem: string = ''
  3629. doUpdateData() {
  3630. setTimeout(() => {
  3631. if (this.modeType === 0) {
  3632. this.deleteCache(this.currentPath)
  3633. this.getSortedFiles(this.currentPath)
  3634. }
  3635. workerInstance.postMessage({ code: 2, data: this.context });
  3636. workerInstance.postMessage({ code: 3, data: this.context });
  3637. workerInstance.postMessage({ code: 4, data: this.context });
  3638. }, 999)
  3639. }
  3640. //编辑信息
  3641. doEdit(item:VideoItem) {
  3642. if (!item) {
  3643. return
  3644. }
  3645. if (StrUtil.isEmpty(this.titleStr)) {
  3646. ToastUtil.showToast('标题不能为空')
  3647. return
  3648. }
  3649. this.table.updateMediaInfo(item.filePath, this.titleStr, this.artistStr, this.ablumStr,
  3650. (success: boolean, error?: string) => {
  3651. this.isShowEdit = false
  3652. if (success) {
  3653. console.log(" onecold 编辑信息成功,数据库已同步");
  3654. ToastUtil.showToast('保存成功')
  3655. this.isShowMoreView = false
  3656. this.name = this.titleStr
  3657. if (item.filePath==this.currentSong?.filePath) {
  3658. this.currentSong.name = this.titleStr
  3659. this.artist = this.artistStr
  3660. this.currentSong.artist = this.artistStr
  3661. this.currentSong.album = this.ablumStr
  3662. }
  3663. this.doUpdateData()
  3664. } else {
  3665. ToastUtil.showToast('保存失败' + error?.toString())
  3666. console.error(" onecold 编辑信息数据库失败原因: " + error);
  3667. }
  3668. });
  3669. let doChangeLyric = false
  3670. if(item.filePath==this.currentSong?.filePath){
  3671. if(this.lyricConStr !== this.lyricContent){
  3672. doChangeLyric = true
  3673. }
  3674. }else if(this.lyricConStr !== this.tempLyricContent){
  3675. doChangeLyric = true
  3676. }
  3677. if (doChangeLyric) {
  3678. let lyricPath = item.filePath.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  3679. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  3680. let isJiaMi = false;
  3681. let realLyricPath = lyricPath
  3682. if (FileUtil.accessSync(jiaMilyricPath)) {
  3683. isJiaMi = true
  3684. realLyricPath = jiaMilyricPath
  3685. console.info("onecold doEdit找到加密本地歌词 ");
  3686. } else {
  3687. isJiaMi = false
  3688. realLyricPath = lyricPath
  3689. console.info("onecold doEdit本地歌词 ");
  3690. }
  3691. this.saveDataToFile(this.lyricConStr, realLyricPath, isJiaMi)
  3692. }
  3693. }
  3694. updateLyricToDB(){
  3695. }
  3696. @Builder
  3697. editSheet(item:VideoItem) {
  3698. Scroll() {
  3699. Column() {
  3700. this.editDetail(item)
  3701. }
  3702. }
  3703. .width('100%')
  3704. .height('100%')
  3705. }
  3706. @Builder
  3707. editDetail(item:VideoItem) {
  3708. Column() {
  3709. if (item) {
  3710. Row() {
  3711. Stack() {
  3712. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') :
  3713. item.pixelMapPath)
  3714. .fillColor(this.themeColor)
  3715. .height(33)
  3716. .width(33)
  3717. .borderRadius('100%')
  3718. .clip(true)
  3719. .opacity(this.opacityItem)// 绑定透明度
  3720. .margin({ left: 20 })
  3721. }
  3722. .width('15%')
  3723. Row() {
  3724. Column() {
  3725. Text(item.name)
  3726. .fontSize(14)
  3727. .maxLines(1)
  3728. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3729. .animation({
  3730. duration: 555,
  3731. curve: 'Linear',
  3732. })
  3733. .fontColor(this.themeColor)
  3734. .margin({ left: 10 })
  3735. Row() {
  3736. Text(item.artist)
  3737. .fontSize(11)
  3738. .maxLines(1)
  3739. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3740. .padding({ top: 8 })
  3741. .fontColor(this.themeColor)
  3742. .margin({ left: 10 })
  3743. }
  3744. }
  3745. .height('100%')
  3746. .width(100)
  3747. .visibility(this.isDarkMode?Visibility.None:Visibility.Visible)
  3748. .justifyContent(FlexAlign.Center)
  3749. .alignItems(HorizontalAlign.Start)
  3750. Button('本地封面')
  3751. .fontColor(Color.White)
  3752. .fontSize(12)
  3753. .height(38)
  3754. .width(88)
  3755. .backgroundColor(this.themeColor)
  3756. .stateEffect(true)
  3757. .margin({ right: 5, left: 12 })
  3758. .onClick(async () => {
  3759. this.goSelectImage(item)
  3760. })
  3761. Button('获取封面')
  3762. .fontColor(Color.White)
  3763. .fontSize(12)
  3764. .height(38)
  3765. .width(88)
  3766. .backgroundColor(this.themeColor)
  3767. .stateEffect(true)
  3768. .margin({ right: 12, left: 5 })
  3769. .onClick(async () => {
  3770. this.doSearchCover(item)
  3771. })
  3772. }
  3773. .height('100%')
  3774. .justifyContent(FlexAlign.Start)
  3775. .layoutWeight(1)
  3776. }
  3777. .width('100%')
  3778. .height(58)
  3779. Row() {
  3780. Text('标题:')
  3781. .fontSize(14)
  3782. .fontColor($r('app.color.text_color'))
  3783. .margin({ left: 22 })
  3784. TextInput({ text: item.name })
  3785. .height(40)
  3786. .maxLines(1)
  3787. .fontSize(14)
  3788. .layoutWeight(1)
  3789. .fontColor($r('app.color.text_color'))
  3790. .margin({ right: 20, left: 10 })
  3791. .onChange((val: string) => {
  3792. this.titleStr = val
  3793. })
  3794. }
  3795. .width('100%')
  3796. .margin({ top: 10, bottom: 10 })
  3797. .justifyContent(FlexAlign.Start)
  3798. Row() {
  3799. Text('艺术家:')
  3800. .fontSize(14)
  3801. .fontColor($r('app.color.text_color'))
  3802. .margin({ left: 22 })
  3803. TextInput({ text: item.artist })
  3804. .height(40)
  3805. .maxLines(1)
  3806. .fontSize(14)
  3807. .layoutWeight(1)
  3808. .fontColor($r('app.color.text_color'))
  3809. .margin({ right: 20, left: 10 })
  3810. .onChange((val: string) => {
  3811. this.artistStr = val
  3812. })
  3813. }
  3814. .width('100%')
  3815. .margin({ top: 10, bottom: 10 })
  3816. .justifyContent(FlexAlign.Start)
  3817. Row() {
  3818. Text('专辑名:')
  3819. .fontSize(14)
  3820. .fontColor($r('app.color.text_color'))
  3821. .margin({ left: 22 })
  3822. TextInput({ text: item.album })
  3823. .height(40)
  3824. .maxLines(1)
  3825. .fontSize(14)
  3826. .layoutWeight(1)
  3827. .fontColor($r('app.color.text_color'))
  3828. .margin({ right: 20, left: 10 })
  3829. .onChange((val: string) => {
  3830. this.ablumStr = val
  3831. })
  3832. }
  3833. .width('100%')
  3834. .margin({ top: 10, bottom: 10 })
  3835. .justifyContent(FlexAlign.Start)
  3836. Row() {
  3837. Text('歌词:')
  3838. .fontSize(14)
  3839. .fontColor($r('app.color.text_color'))
  3840. .margin({ left: 22 })
  3841. TextArea({ text:item.filePath===this.currentSong?.filePath? this.lyricContent : this.tempLyricContent })
  3842. .type(TextAreaType.NORMAL)
  3843. .height(275)
  3844. .fontSize(14)
  3845. .layoutWeight(1)
  3846. .fontColor($r('app.color.text_color'))
  3847. .margin({ right: 20, left: 10 })
  3848. .onChange((val: string) => {
  3849. this.lyricConStr = val
  3850. })
  3851. }
  3852. .width('100%')
  3853. .margin({ top: 10, bottom: 10 })
  3854. .justifyContent(FlexAlign.Start)
  3855. Row() {
  3856. Button('保存')
  3857. .fontColor(Color.White)
  3858. .layoutWeight(1)
  3859. .height(50)
  3860. .width(100)
  3861. .backgroundColor(this.themeColor)
  3862. .stateEffect(true)
  3863. .margin({ right: 20, bottom: 20 })
  3864. .onClick(async () => {
  3865. this.doEdit(item)
  3866. })
  3867. Button('取消')
  3868. .fontColor(Color.White)
  3869. .layoutWeight(1)
  3870. .height(50)
  3871. .width(100)
  3872. .backgroundColor(this.themeColor)
  3873. .stateEffect(true)
  3874. .margin({ left: 20, bottom: 20 })
  3875. .onClick(async () => {
  3876. this.isShowEdit = false
  3877. })
  3878. }
  3879. .margin({
  3880. left: 38,
  3881. right: 38,
  3882. top: 10,
  3883. bottom: 10
  3884. })
  3885. .width(250)
  3886. .height(60)
  3887. }
  3888. }
  3889. .margin({ bottom: 20 })
  3890. }
  3891. @Builder
  3892. detailSheet() {
  3893. Scroll() {
  3894. Column() {
  3895. this.songDetail()
  3896. }
  3897. }
  3898. .width('100%')
  3899. .height('100%')
  3900. }
  3901. @Builder
  3902. songDetail() {
  3903. Column() {
  3904. if (this.currentSong) {
  3905. Row() {
  3906. Stack() {
  3907. Image(StrUtil.isEmpty(this.currentSong.pixelMapPath) ? $r('app.media.music_red') :
  3908. this.currentSong.pixelMapPath)
  3909. .fillColor(this.themeColor)
  3910. .height(33)
  3911. .width(33)
  3912. .borderRadius('100%')
  3913. .clip(true)
  3914. .opacity(this.opacityItem)// 绑定透明度
  3915. .margin({ left: 20 })
  3916. }
  3917. .width('15%')
  3918. Column() {
  3919. Column() {
  3920. Text(this.currentSong.name)
  3921. .fontSize(14)
  3922. .maxLines(1)
  3923. .animation({
  3924. duration: 555,
  3925. curve: 'Linear',
  3926. })
  3927. .fontColor($r('app.color.text_color'))
  3928. .margin({ left: 10 })
  3929. Row() {
  3930. Text(StrUtil.isEmpty(this.currentSong.artist) ? this.currentSong.cTime :
  3931. this.currentSong.artist + ' ' + this.currentSong?.album)
  3932. .fontSize(11)
  3933. .padding({ top: 8 })
  3934. .fontColor($r('app.color.text_color'))
  3935. .margin({ left: 10 })
  3936. }
  3937. }
  3938. .height('100%')
  3939. .width('100%')
  3940. .justifyContent(FlexAlign.Center)
  3941. .alignItems(HorizontalAlign.Start)
  3942. }
  3943. .height('100%')
  3944. }
  3945. .width('100%')
  3946. .height(58)
  3947. .justifyContent(FlexAlign.SpaceBetween)
  3948. Row() {
  3949. Text('歌手名:')
  3950. .fontSize(14)
  3951. .fontColor(Color.White)
  3952. .margin({ left: 22 })
  3953. Text(this.currentSong?.artist ? this.currentSong.artist : '未知歌手')
  3954. .fontSize(14)
  3955. .fontColor(Color.White)
  3956. .margin({ left: 10 })
  3957. .layoutWeight(1)
  3958. }
  3959. .width('100%')
  3960. .margin({ top: 10, bottom: 10 })
  3961. .justifyContent(FlexAlign.Start)
  3962. Row() {
  3963. Text('专辑名:')
  3964. .fontSize(14)
  3965. .fontColor(Color.White)
  3966. .margin({ left: 22 })
  3967. Text(this.currentSong?.album ? this.currentSong.album : '未知专辑')
  3968. .fontSize(14)
  3969. .margin({ left: 10 })
  3970. .fontColor(Color.White)
  3971. .layoutWeight(1)
  3972. }
  3973. .width('100%')
  3974. .margin({ top: 10, bottom: 10 })
  3975. .justifyContent(FlexAlign.Start)
  3976. Row() {
  3977. Text('时长:')
  3978. .fontSize(14)
  3979. .fontColor(Color.White)
  3980. .margin({ left: 22 })
  3981. Text(this.totalTime)
  3982. .fontSize(14)
  3983. .margin({ left: 10 })
  3984. .fontColor(Color.White)
  3985. .layoutWeight(1)
  3986. }
  3987. .width('100%')
  3988. .margin({ top: 10, bottom: 10 })
  3989. .justifyContent(FlexAlign.Start)
  3990. Row() {
  3991. Text('采样率:')
  3992. .fontSize(14)
  3993. .fontColor(Color.White)
  3994. .margin({ left: 22 })
  3995. Text(Utility.convertToKHz(this.currentSong.sampleRate))
  3996. .fontSize(14)
  3997. .margin({ left: 10 })
  3998. .fontColor(Color.White)
  3999. .layoutWeight(1)
  4000. }
  4001. .width('100%')
  4002. .margin({ top: 10, bottom: 10 })
  4003. .justifyContent(FlexAlign.Start)
  4004. Row() {
  4005. Text('音轨数:')
  4006. .fontSize(14)
  4007. .fontColor(Color.White)
  4008. .margin({ left: 22 })
  4009. Text(this.currentSong.trackCount)
  4010. .fontSize(14)
  4011. .margin({ left: 10 })
  4012. .fontColor(Color.White)
  4013. .layoutWeight(1)
  4014. }
  4015. .width('100%')
  4016. .margin({ top: 10, bottom: 10 })
  4017. .justifyContent(FlexAlign.Start)
  4018. Row() {
  4019. Text('格式:')
  4020. .fontSize(14)
  4021. .fontColor(Color.White)
  4022. .margin({ left: 22 })
  4023. Text(Utility.formatMimeType(this.currentSong.mimeType))
  4024. .fontSize(14)
  4025. .margin({ left: 10 })
  4026. .fontColor(Color.White)
  4027. .layoutWeight(1)
  4028. }
  4029. .width('100%')
  4030. .margin({ top: 10, bottom: 10 })
  4031. .justifyContent(FlexAlign.Start)
  4032. Row() {
  4033. Text('文件大小:')
  4034. .fontSize(14)
  4035. .fontColor(Color.White)
  4036. .margin({ left: 22 })
  4037. Text(this.currentSong.size)
  4038. .fontSize(14)
  4039. .margin({ left: 10 })
  4040. .fontColor(Color.White)
  4041. .layoutWeight(1)
  4042. }
  4043. .width('100%')
  4044. .margin({ top: 10, bottom: 10 })
  4045. .justifyContent(FlexAlign.Start)
  4046. Row() {
  4047. Text('文件名:')
  4048. .fontSize(14)
  4049. .fontColor(Color.White)
  4050. .margin({ left: 22 })
  4051. Text(this.currentSong.fileName)
  4052. .fontSize(14)
  4053. .margin({ left: 10 })
  4054. .fontColor(Color.White)
  4055. .layoutWeight(1)
  4056. }
  4057. .width('100%')
  4058. .margin({ top: 10, bottom: 10 })
  4059. .justifyContent(FlexAlign.Start)
  4060. Row() {
  4061. Text('修改时间:')
  4062. .fontSize(14)
  4063. .fontColor(Color.White)
  4064. .margin({ left: 22 })
  4065. Text(this.currentSong.cTime)
  4066. .fontSize(14)
  4067. .margin({ left: 10 })
  4068. .fontColor(Color.White)
  4069. .layoutWeight(1)
  4070. }
  4071. .width('100%')
  4072. .margin({ top: 10, bottom: 10 })
  4073. .justifyContent(FlexAlign.Start)
  4074. Row() {
  4075. Text('存放目录:')
  4076. .fontSize(14)
  4077. .fontColor(Color.White)
  4078. .margin({ left: 22 })
  4079. Text(this.currentSong.filePath)
  4080. .fontSize(12)
  4081. .margin({ left: 10 })
  4082. .fontColor(Color.White)
  4083. .layoutWeight(1)
  4084. }
  4085. .margin({ top: 10, bottom: 10 })
  4086. .width('100%')
  4087. .justifyContent(FlexAlign.Start)
  4088. }
  4089. }
  4090. .margin({ bottom: 20 })
  4091. }
  4092. //定时关闭布局
  4093. @Builder
  4094. TimeCloseSheet() {
  4095. Scroll() {
  4096. Column() {
  4097. this.TimeClose()
  4098. }
  4099. }
  4100. .width('100%')
  4101. .height('100%')
  4102. }
  4103. //倒计时关闭音乐,退出App功能实现。
  4104. @State selectedMinutes: number = 0 // 0表示未开启
  4105. @State remainingSeconds: number = 0
  4106. @State isCustomSuccess: boolean = false //设置自定义成功
  4107. // 预设时间选项
  4108. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  4109. private formatTime(seconds: number): string {
  4110. const mins = Math.floor(seconds / 60)
  4111. const secs = seconds % 60
  4112. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  4113. }
  4114. // 开始倒计时
  4115. private handleTimeSelect(minutes: number) {
  4116. if (minutes === this.selectedMinutes) {
  4117. this.stopCountdown();
  4118. this.selectedMinutes = 0;
  4119. return;
  4120. }
  4121. this.selectedMinutes = minutes;
  4122. this.remainingSeconds = minutes * 60;
  4123. this.startCountdown(); // 新增调用
  4124. }
  4125. @Builder
  4126. TimeClose() {
  4127. Column() {
  4128. // 倒计时显示区域
  4129. Text(this.selectedMinutes > 0 ?
  4130. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  4131. "定时关闭未开启")
  4132. .fontSize(17)
  4133. .fontColor($r('app.color.text_color'))
  4134. .margin({ top: 2 });
  4135. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  4136. ForEach(this.presetTimes, (minutes: number) => {
  4137. // 单行时间选项容器
  4138. Row() {
  4139. // 文字描述区域
  4140. Text(this.getDisplayText(minutes))
  4141. .fontSize(15)
  4142. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  4143. $r('app.color.text_color'))// 选中态颜色变化
  4144. .textAlign(TextAlign.Start)
  4145. .layoutWeight(1); // 占据剩余空间
  4146. // 复选框区域
  4147. Checkbox()
  4148. .select(minutes === this.selectedMinutes ? true : minutes === -1 ? this.isCustomSuccess : false)// 绑定选中状态
  4149. .selectedColor(this.themeColor)// 主题色
  4150. .shape(CheckBoxShape.CIRCLE)
  4151. .size({ width: 24, height: 24 })
  4152. .margin({ left: 20 })
  4153. }
  4154. .width('100%')
  4155. .padding(10)
  4156. .backgroundColor(minutes === this.selectedMinutes ?$r('app.color.timeColor_bg') :$r('app.color.bottom_control_background')) // 选中背景高亮
  4157. .borderRadius(12)
  4158. .margin({ bottom: 6 })
  4159. .onClick(() => this.handleSelect(minutes)); // 确保点击触发选择
  4160. });
  4161. }
  4162. .width('100%')
  4163. .padding(16)
  4164. }
  4165. }
  4166. // 获取显示文本
  4167. private getDisplayText(minutes: number): string {
  4168. if (minutes === -1) {
  4169. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  4170. }
  4171. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  4172. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  4173. }
  4174. // 处理选择事件
  4175. private handleSelect(minutes: number): void {
  4176. if (minutes === -1) { // 自定义
  4177. // 弹出自定义时间对话框
  4178. DialogHelper.showTextInputDialog({
  4179. title: '自定义时间',
  4180. maskColor: Color.Transparent,
  4181. inputType: InputType.Number,
  4182. text: '',
  4183. onChange: (text) => {
  4184. console.error("onChange: " + text);
  4185. },
  4186. onAction: (action, dialogId, content) => {
  4187. if (action == DialogAction.TWO) {
  4188. this.handleTimeSelect(Number(content)); // 改为调用统一方法
  4189. this.isCustomSuccess = true
  4190. ToastUtil.showToast("设置成功," + this.selectedMinutes + "分钟后定时关闭");
  4191. }
  4192. }
  4193. });
  4194. } else {
  4195. this.isCustomSuccess = false
  4196. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  4197. }
  4198. }
  4199. // 添加定时器引用
  4200. private timerId: number = -1;
  4201. // 启动/重置倒计时
  4202. private startCountdown() {
  4203. // 清除旧定时器
  4204. if (this.timerId !== -1) {
  4205. clearInterval(this.timerId);
  4206. }
  4207. // 创建新定时器
  4208. if (this.selectedMinutes > 0) {
  4209. this.timerId = setInterval(() => {
  4210. if (this.remainingSeconds === 15) {
  4211. this.showConfirmationDialog();
  4212. }
  4213. if (this.remainingSeconds > 0) {
  4214. this.remainingSeconds -= 1;
  4215. } else {
  4216. this.stopCountdown();
  4217. this.handleTimeout();
  4218. }
  4219. }, 1000);
  4220. }
  4221. }
  4222. // 15倒计时后再次提示显示确认是否关闭App对话框
  4223. private showConfirmationDialog() {
  4224. DialogHelper.showAlertDialog({
  4225. backgroundColor: $r('app.color.btn_green'),
  4226. title: '确认关闭',
  4227. maskColor: Color.Transparent,
  4228. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  4229. borderStyle: BorderStyle.Dashed,
  4230. primaryButton: '暂不关闭',
  4231. secondaryButton: '确定',
  4232. onAction: (action) => {
  4233. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  4234. this.stopCountdown();
  4235. this.selectedMinutes = 0
  4236. } else if (action == DialogAction.TWO) {
  4237. }
  4238. }
  4239. })
  4240. }
  4241. // 停止倒计时
  4242. private stopCountdown() {
  4243. if (this.timerId !== -1) {
  4244. clearInterval(this.timerId);
  4245. this.timerId = -1;
  4246. }
  4247. }
  4248. // 超时处理
  4249. private handleTimeout() {
  4250. // 执行播放器关闭逻辑
  4251. this.selectedMinutes = 0;
  4252. this.isCustomSuccess = false;
  4253. ToastUtil.showToast(" 定时关闭已完成");
  4254. this.stop(); // 假设存在的播放器实例
  4255. //退出APP
  4256. const mContext = getContext(this) as common.UIAbilityContext
  4257. mContext.terminateSelf();
  4258. AvSessionController.getInstance(true).unregisterSessionListener()
  4259. }
  4260. //倒计时关闭音乐,退出App功能实现结束。
  4261. //播放列表的拖动List 重新排序
  4262. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  4263. //左滑操作 移动文件 重命名 删除等操作
  4264. @Builder
  4265. sonButton(item: VideoItem, index: number, filePath: string) {
  4266. Row() {
  4267. //加入下一首播放
  4268. Button() {
  4269. Image($r('app.media.next_to_play'))
  4270. .fillColor(Color.White)
  4271. .width(20)
  4272. }
  4273. .width(40)
  4274. .height(40)
  4275. .type(ButtonType.Circle)
  4276. .backgroundColor(this.themeColor)
  4277. .margin(5)
  4278. .onClick(() => {
  4279. this.addToNextPlay(item);
  4280. })
  4281. Button() {
  4282. Image($r('app.media.close'))
  4283. .fillColor(Color.White)
  4284. .width(20)
  4285. }
  4286. .width(40)
  4287. .height(40)
  4288. .type(ButtonType.Circle)
  4289. .backgroundColor(this.themeColor)
  4290. .margin(5)
  4291. .onClick(() => {
  4292. this.songList.splice(Number(index), 1)
  4293. this.sonDataSource.pushArrayData(this.songList)
  4294. })
  4295. Button() {
  4296. Image($r('app.media.share2'))
  4297. .fillColor(Color.White)
  4298. .width(20)
  4299. }
  4300. .width(40)
  4301. .height(40)
  4302. .type(ButtonType.Circle)
  4303. .backgroundColor(this.themeColor)
  4304. .margin(5)
  4305. .onClick(() => {
  4306. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  4307. })
  4308. }
  4309. }
  4310. itemMoveSon(index: number, newIndex: number): void {
  4311. if (newIndex < 0 || newIndex >= this.songList.length) {
  4312. return;
  4313. }
  4314. let tmp = this.songList.splice(index, 1);
  4315. this.songList.splice(newIndex, 0, tmp[0]);
  4316. this.sonDataSource.pushArrayData(this.songList)
  4317. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  4318. }
  4319. @Builder
  4320. PlayList() {
  4321. List({ scroller: this.playListScroller }) {
  4322. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  4323. ListItem() {
  4324. this.MusicItemSon(item, index)
  4325. }
  4326. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  4327. .animation({
  4328. duration: 666,
  4329. curve: 'ease-in-out' // 可选动画曲线
  4330. })
  4331. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  4332. TransitionEffect.scale({ x: 0, y: 0 }) ))
  4333. .clickEffect({level:ClickEffectLevel.MIDDLE})
  4334. //拖动List关键代码开始
  4335. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  4336. .zIndex(this.dragItem === index ? 1 : 0)
  4337. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  4338. .gesture(
  4339. GestureGroup(GestureMode.Sequence,
  4340. LongPressGesture({ repeat: true })
  4341. .onAction((event?: GestureEvent) => {
  4342. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  4343. this.scaleItem = index
  4344. })
  4345. })
  4346. .onActionEnd(() => {
  4347. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  4348. this.scaleItem = -1
  4349. })
  4350. }),
  4351. PanGesture({ fingers: 1, direction: null, distance: 0 })
  4352. .onActionStart(() => {
  4353. this.dragItem = index // 记录当前拖动项索引
  4354. this.dragRefOffset = 0 // 重置偏移基准
  4355. })
  4356. .onActionUpdate((event: GestureEvent) => {
  4357. this.offsetY = event.offsetY - this.dragRefOffset;
  4358. this.neighborItem = -1;
  4359. let indexA = this.songList.indexOf(item);
  4360. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  4361. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  4362. let value: number = 0;
  4363. if (this.offsetY < 0) {
  4364. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  4365. this.neighborItem = indexA - 1;
  4366. this.neighborScale = 1 - value / 20;
  4367. } else if (this.offsetY > 0) {
  4368. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  4369. this.neighborItem = indexA + 1;
  4370. this.neighborScale = 1 - value / 20;
  4371. }
  4372. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  4373. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4374. this.offsetY -= this.ITEM_INTV;
  4375. this.dragRefOffset += this.ITEM_INTV;
  4376. this.itemMoveSon(indexA, indexA + 1);
  4377. });
  4378. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  4379. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4380. this.offsetY += this.ITEM_INTV;
  4381. this.dragRefOffset -= this.ITEM_INTV;
  4382. this.itemMoveSon(indexA, indexA - 1);
  4383. });
  4384. }
  4385. })
  4386. .onActionEnd((event: GestureEvent) => {
  4387. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4388. this.dragItem = -1
  4389. this.neighborItem = -1
  4390. })
  4391. animateTo({
  4392. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  4393. }, () => {
  4394. this.scaleItem = -1
  4395. })
  4396. })
  4397. )
  4398. .onCancel(() => {
  4399. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4400. this.dragItem = -1
  4401. this.neighborItem = -1
  4402. })
  4403. animateTo({
  4404. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  4405. }, () => {
  4406. this.scaleItem = -1
  4407. })
  4408. })
  4409. ) //拖动List关键代码结束
  4410. .onClick(() => {
  4411. this.doPlay(item, index, true)
  4412. })
  4413. }, (item: VideoItem) => item.filePath)
  4414. }
  4415. .width('100%')
  4416. .height('100%')
  4417. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4418. // .animation({ duration: 500, curve: Curve.Ease }))
  4419. .cachedCount(10)
  4420. .scale({x:this.scaleValue,y:this.scaleValue,z:1})
  4421. .gesture(PinchGesture({ fingers: 2 })
  4422. .onActionEnd((event: GestureEvent)=>{
  4423. this.setlistTwoFingers()
  4424. })
  4425. .onActionUpdate(e=>{
  4426. this.scaleValue = this.pinchValue*e.scale
  4427. })
  4428. .onActionStart(e => {
  4429. }))
  4430. .padding({
  4431. bottom: 0
  4432. })
  4433. }
  4434. @Builder
  4435. private MusicItemSon(item: VideoItem, index?: number) {
  4436. Button({ type: ButtonType.Normal, stateEffect: true }) {
  4437. Row() {
  4438. Stack() {
  4439. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  4440. .height(this.twoFingerType==3?55:this.twoFingerType==2?35:30)
  4441. .width(this.twoFingerType==3?55:this.twoFingerType==2?35:30)
  4442. .alt($r('app.media.music_red'))
  4443. .fillColor(this.themeColor)
  4444. .borderRadius('100%')
  4445. .clip(true)
  4446. .margin({ left: 20 })
  4447. }
  4448. .width('15%')
  4449. Column() {
  4450. Column() {
  4451. Text(item.name)
  4452. .fontSize(this.twoFingerType==1?12:this.twoFingerType==2?15:18)
  4453. .fontColor(this.curIndex === index ? this.themeColor :
  4454. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  4455. .maxLines(1)
  4456. .margin({ left:this.twoFingerType==3?18: 10 })
  4457. Row() {
  4458. Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
  4459. .fontSize(this.twoFingerType==1?11:this.twoFingerType==2?12:14)
  4460. .padding({ top: 8 })
  4461. .fontColor(this.curIndex === index ? this.themeColor :
  4462. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  4463. .margin({ left:this.twoFingerType==3?18: 10 })
  4464. Blank()
  4465. Text(item.size)
  4466. .fontSize(this.twoFingerType==1?11:this.twoFingerType==2?12:14)
  4467. .padding({ top: 8 })
  4468. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  4469. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  4470. this.isFrontWhite ? $r('app.color.playlistText_color') : $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. .width('65%')
  4481. Column() {
  4482. ImageAnimator()
  4483. .images(this.imagesF)// 动画数组
  4484. .duration(1000)// 持续
  4485. .state(this.animationState)// 动画状态
  4486. .fillMode(FillMode.Forwards)
  4487. .width(18)
  4488. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  4489. Visibility.None)
  4490. .height(18)
  4491. .iterations(-1) // 播放次数
  4492. }
  4493. .width('20%')
  4494. }
  4495. }
  4496. .backgroundColor(Color.Transparent)
  4497. .width('100%')
  4498. .height(this.twoFingerType==3?ITEM_HEIGHT_BIG:this.twoFingerType==2?ITEM_HEIGHT:ITEM_HEIGHT_SMALL)
  4499. .shadow(this.scaleItem === index ? {
  4500. radius: 70,
  4501. color: '#15000000',
  4502. offsetX: 0,
  4503. offsetY: 0
  4504. } :
  4505. {
  4506. radius: 0,
  4507. color: '#15000000',
  4508. offsetX: 0,
  4509. offsetY: 0
  4510. })
  4511. .animation({ curve: Curve.Sharp, duration: 300 })
  4512. }
  4513. @Builder
  4514. MusicPlayBuilder() {
  4515. Column() {
  4516. this.IjkMusicPlayerView()
  4517. }
  4518. .height('100%')
  4519. .width('100%')
  4520. .onDisAppear(() => {
  4521. this.translateY = 0;
  4522. })
  4523. .translate({ y: this.translateY })
  4524. .gesture(
  4525. PanGesture(this.panOption)
  4526. .onActionUpdate((event?: GestureEvent) => {
  4527. if (event) {
  4528. this.translateY = event.offsetY;
  4529. if (this.translateY < 0) {
  4530. this.translateY = 0;
  4531. return;
  4532. }
  4533. }
  4534. })
  4535. .onActionEnd(() => {
  4536. if (this.translateY > this.windowHeight / 2) {
  4537. this.isShowPlay = false;
  4538. } else {
  4539. this.getUIContext().animateTo({
  4540. duration: 300,
  4541. curve: Curve.Smooth
  4542. }, () => {
  4543. this.translateY = 0;
  4544. })
  4545. }
  4546. })
  4547. )
  4548. }
  4549. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  4550. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  4551. HeightBreakpoint.HEIGHT_LG;
  4552. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  4553. @State topBarHeight: number = 50
  4554. @State barOpacity: number = 1
  4555. @State barBottomOpacity: number = 1
  4556. private hideDone: boolean = false;
  4557. @State currentYOffset: number = 0;
  4558. @State bottomBarHeight: number = 55;
  4559. private isHiding: boolean = false;
  4560. //是否是Pura X外屏,或者小屏幕
  4561. isPuraWP() {
  4562. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  4563. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  4564. }
  4565. //是否是Pura X外屏,或者小屏幕,手机横屏
  4566. isCoverOpacity() {
  4567. if (this.isPuraWP()) {
  4568. return true
  4569. }
  4570. if (this.isPhoneLan()) {
  4571. return true
  4572. }
  4573. if (deviceInfo.marketName.includes('Pura X')
  4574. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  4575. return true
  4576. }
  4577. return false
  4578. }
  4579. //是不是手机横屏
  4580. isPhoneLan() {
  4581. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  4582. && this.currentBreakpoint !== BreakpointTypeEnum.SM) {
  4583. if (DisplayUtil.getFoldStatus() === 0 ) {
  4584. return true
  4585. }
  4586. }
  4587. return false
  4588. }
  4589. @Builder
  4590. IjkMusicPlayerView() {
  4591. Column() {
  4592. // Stack({ alignContent: Alignment.Center }) {
  4593. //
  4594. //
  4595. //
  4596. // Image($r('app.media.icon_load'))
  4597. // .objectFit(ImageFit.Auto)
  4598. // .width('120px')
  4599. // .height('120px')
  4600. // .visibility(this.loadingVisible)
  4601. // .border({ width: 0 })
  4602. // .borderStyle(BorderStyle.Dashed)
  4603. //
  4604. //
  4605. // }
  4606. Column() {
  4607. Column() {
  4608. //播放标题
  4609. Column() {
  4610. this.PlayTitle()
  4611. }
  4612. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  4613. .width('100%')
  4614. .margin({ top: 0 })
  4615. .height(PlayConstants.HEIGHT)
  4616. .visibility(DeviceUtil.getDeviceType()==resourceManager.DeviceType.DEVICE_TYPE_2IN1?
  4617. Visibility.Visible:this.isShowPlayPageBack?Visibility.Visible:Visibility.None)
  4618. // .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM
  4619. // ?Visibility.Visible:Visibility.Visible)
  4620. Swiper() {
  4621. this.CoverInfo()
  4622. this.PlayerLyrics()
  4623. }
  4624. .onChange((index:number)=>{
  4625. this.currentSwiperIndex = index
  4626. })
  4627. .indicator(false)
  4628. // .indicator(this.currentBreakpoint === BreakpointTypeEnum.SM ?
  4629. // new DotIndicator()
  4630. // .top(this.isCoverOpacity()?0:10)
  4631. //
  4632. // .selectedColor($r('app.color.select_swiper'))
  4633. // .color($r('app.color.slider_track')):false
  4634. // )
  4635. .displayCount(new BreakpointType({
  4636. sm: 1,
  4637. md: 2,
  4638. lg: 2,
  4639. xl: 2,
  4640. xxl: 2
  4641. }).getValue(this.currentBreakpoint))
  4642. .clip(false)
  4643. .loop(false)
  4644. .autoPlay(false)
  4645. // .interval(8000)
  4646. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  4647. .height('100%')
  4648. .hitTestBehavior(HitTestMode.Transparent)
  4649. Image($r('app.media.icon_replay'))
  4650. .objectFit(ImageFit.Auto)
  4651. .width('120px')
  4652. .height('120px')
  4653. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  4654. .border({ width: 0 })
  4655. .visibility(Visibility.None)
  4656. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  4657. .onClick(() => {
  4658. this.startPlayOrResumePlay();
  4659. })
  4660. }
  4661. .width(CommonConstants.FULL_PERCENT)
  4662. .height(CommonConstants.FULL_PERCENT)
  4663. .justifyContent(FlexAlign.End)
  4664. }
  4665. .justifyContent(FlexAlign.End)
  4666. .margin({ bottom: 8 })
  4667. }
  4668. // .backgroundImage(this.imageLabelBg)
  4669. .backgroundImage(this.isPuraWP()&&this.currentSwiperIndex===0?(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover):this.imageLabelBg)
  4670. .backgroundImageSize(this.isPuraWP()?{ width: '100%' }:{ height: '150%', width: '100%' })
  4671. // .backgroundImagePosition(Alignment.Center)
  4672. .animation({
  4673. duration: 666,
  4674. curve: 'ease-in-out' // 可选动画曲线
  4675. })
  4676. .backgroundBlurStyle(this.isPuraWP()&&this.currentSwiperIndex===0?BlurStyle.NONE:BlurStyle.BACKGROUND_ULTRA_THICK)
  4677. .hitTestBehavior(HitTestMode.Transparent)
  4678. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  4679. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  4680. .backgroundBrightness({rate:this.isPuraWP()?0.1:0,lightUpDegree:-0.1})
  4681. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  4682. .onClick( ()=>{
  4683. this.isAutoHide = false
  4684. this.startAutoHide()
  4685. })
  4686. }
  4687. @State progressValue: number = 0;
  4688. @State currentTime: string = "00:00";
  4689. @State totalTime: string = "00:00";
  4690. @State loadingVisible: Visibility = Visibility.None;
  4691. @State replayVisible: Visibility = Visibility.None;
  4692. @State slideEnable: boolean = false;
  4693. @State aspRatio: number = 0.5;
  4694. @State mContext: object | undefined = undefined;
  4695. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  4696. @State mFirst: boolean = true;
  4697. @State mDestroyPage: boolean = false;
  4698. @State playSpeed: number = 1;
  4699. @State oldSeconds: number = 0;
  4700. @State isSeekTo: boolean = false;
  4701. @State isCurrentTime: boolean = false;
  4702. @State videoWidth: string = '100%';
  4703. @State videoHeight: string = '100%';
  4704. @State initAspectRatio: number = 1;
  4705. @State videoAspectRatio: number = this.initAspectRatio;
  4706. private videoUrl: string = '';
  4707. private last: number = 0;
  4708. @State videoParentAspectRatio: number = this.initAspectRatio;
  4709. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  4710. @State CONTROL_PlayStatus: number = PlayStatus.INIT;
  4711. @State PROGRESS_MAX_VALUE: number = 100;
  4712. @State updateProgressTimer: number = 0;
  4713. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  4714. @State name: string = '';
  4715. // @State loop: boolean = false;
  4716. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  4717. @State multiple: string = '1.0X';
  4718. xcomponentController: XComponentController = new XComponentController()
  4719. private panOptionBright: PanGestureOptions =
  4720. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  4721. private panOptionVolume: PanGestureOptions =
  4722. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  4723. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  4724. //手势的音量控制和亮度控制
  4725. private positionX: number = PlayConstants.POSITION_X;
  4726. private positionY: number = PlayConstants.POSITION_Y;
  4727. private windowClass: window.Window = globalThis.windowClass
  4728. @State volume: number = 0.5;
  4729. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  4730. @State bright: number = PlayConstants.BRIGHT;
  4731. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  4732. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  4733. @State screenWidth: number = 0
  4734. @State screenHeight: number = 0
  4735. @State statusBarHeight: number = 0
  4736. @State isYesFull: boolean = false
  4737. private seekValue: number = 0
  4738. @State isVideoLock: boolean = false; // Whether the video playback is locked
  4739. eventHub = getContext().eventHub;
  4740. //投播组件
  4741. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  4742. private castController: avSession.AVCastController | undefined = undefined;
  4743. @State isCastPlaying: boolean = false;
  4744. @State currentTime2: number = 0;
  4745. @State currentStringTime: string = '00:00';
  4746. @State duration: number = 0;
  4747. @State isReady: boolean = false;
  4748. @State durationTime: number = 0;
  4749. @State durationStringTime: string = '00:00';
  4750. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  4751. // @State isPlaying: boolean = false;
  4752. private castSeek: boolean = false;
  4753. private castItem: avSession.AVQueueItem | undefined = undefined;
  4754. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  4755. @State imageLabel: PixelMap | Resource = CommonConstants.musicBgList[0];
  4756. @State imageLabelBg: PixelMap | Resource = CommonConstants.musicBgList[0];
  4757. @State rotateAngle2: number = 0
  4758. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  4759. @State cover: string | undefined = '';
  4760. @State artist: string | undefined = ''
  4761. // 1.初始化controller
  4762. private lyricController: LyricController = new LyricController()
  4763. private lyricControllerXF: LyricController = new LyricController()//悬浮歌词控制器
  4764. private parser = new LyricParser()
  4765. @State randomColor: string = 'rgb(0,0,0)'
  4766. @State randomShakenX: number = 0
  4767. @State randomShakenY: number = 0
  4768. @State lyricTextSize: number = 24
  4769. @State lyricContent: string = ''
  4770. @State isDebug: boolean = false
  4771. @State isHightLightCenter: boolean = true
  4772. /**
  4773. * 初始化歌词加载与展示逻辑
  4774. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  4775. * @param isToast 是否弹出Toast提示(可选)获取在线歌词为true
  4776. * @param isApi2 是否使用API2获取歌词(可选)
  4777. *
  4778. * 主要流程:
  4779. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  4780. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  4781. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  4782. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  4783. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  4784. * 6. 解析失败或读取失败时,清空歌词显示。
  4785. *
  4786. * 注意事项:
  4787. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  4788. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  4789. * - 歌词内容解析后通过lyricController驱动UI渲染。
  4790. */
  4791. async initLyric(lyricPath: string, isToast?: boolean, isApi2?: boolean) {
  4792. if (StrUtil.isEmpty(lyricPath)) {
  4793. return
  4794. }
  4795. this.initPipLyricSetting()
  4796. this.lyricContent = ''
  4797. this.lyricController
  4798. .setTextSize(this.currentLyricSize)
  4799. .setCacheSize(4)
  4800. .setTextColor("#DDDDDD")
  4801. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  4802. .setEmptyHint("")
  4803. .setAnimationDuration(1000)
  4804. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  4805. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 2)
  4806. this.setBlurDegree(this.blurDegree,false)
  4807. this.setLyricAlignMode(this.currentLyricAlignMode,false)
  4808. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18),false)
  4809. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23),false)
  4810. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 52))
  4811. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'),false)
  4812. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'),false)
  4813. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  4814. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  4815. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight',400)
  4816. this.lyricController.setTextWeight(this.lyricTextWeight)
  4817. this.showSingleLyric = false
  4818. this.timeOffset = 0
  4819. this.lyricController.setLyric(null)
  4820. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  4821. LogUtil.debug("onecold lyricPath =" + lyricPath)
  4822. const neiqianLrc = LrcParser.getLyrics(this.videoUrl); //获取内嵌歌词
  4823. if (StrUtil.isNotEmpty(neiqianLrc) && !isToast) {
  4824. LogUtil.debug("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  4825. //赋值给this.lyricContent,播控中心才可以显示歌词
  4826. this.lyricContent = neiqianLrc
  4827. // 将文件内容按行分割成字符串数组
  4828. let lines = neiqianLrc.split('\n').map(line => line.trim());
  4829. // 3.解析歌词
  4830. let lyric = this.parser.parse(lines);
  4831. // 4.设置歌词
  4832. this.lyricController.setLyric(lyric);
  4833. this.lyricControllerXF.setLyric(lyric)
  4834. return
  4835. }
  4836. if (isToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  4837. && !Utility.isVideoByExtension(this.videoUrl))) {
  4838. if (this.currentSong !== undefined) {
  4839. // ToastUtil.showShort('正在为你搜索在线歌词!')
  4840. //判断是不是赞助会员,是会员的话才开启歌词功能
  4841. // if (!this.isDebug) {
  4842. // if (!Utility.isNoble()) {
  4843. // LogUtil.debug("onecold 不是赞助会员")
  4844. // return
  4845. // }
  4846. // if(!Utility.isPassInstallTime(33)){
  4847. // LogUtil.debug("onecold not pass time")
  4848. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  4849. // return
  4850. // }
  4851. // }
  4852. let artist = this.currentSong?.artist
  4853. if (artist === undefined) {
  4854. artist = ''
  4855. }
  4856. if (isApi2 === undefined) {
  4857. isApi2 = false
  4858. }
  4859. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  4860. // LogUtil.debug("onecold res =" + res)
  4861. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  4862. if (StrUtil.isNotEmpty(res)) {
  4863. this.lyricContent = res
  4864. let lines = res.split('\n').map(line => line.trim());
  4865. // 3.解析歌词
  4866. let lyric = this.parser.parse(lines);
  4867. // 4.设置歌词
  4868. this.lyricController.setLyric(lyric);
  4869. this.lyricControllerXF.setLyric(lyric)
  4870. this.showSingleLyric = true
  4871. // 4.保存歌词文件lyric到本地
  4872. this.saveDataToFile(res, jiaMilyricPath, true)
  4873. } else {
  4874. this.lyricController.setLyric(null)
  4875. this.lyricControllerXF.setLyric(null)
  4876. if (isToast) {
  4877. ToastUtil.showShort('未获取到歌词!')
  4878. }
  4879. }
  4880. } else {
  4881. this.lyricController.setLyric(null)
  4882. this.lyricControllerXF.setLyric(null)
  4883. if (isToast) {
  4884. ToastUtil.showShort('未获取到歌词!')
  4885. }
  4886. }
  4887. })
  4888. } else {
  4889. this.lyricController.setLyric(null)
  4890. this.lyricControllerXF.setLyric(null)
  4891. if (isToast) {
  4892. ToastUtil.showShort('未获取到歌词!')
  4893. }
  4894. }
  4895. return
  4896. }
  4897. try {
  4898. let isJiaMi = false;
  4899. let realLyricPath = lyricPath
  4900. if (FileUtil.accessSync(jiaMilyricPath)) {
  4901. isJiaMi = true
  4902. realLyricPath = jiaMilyricPath
  4903. console.info("onecold 找到加密本地歌词 ");
  4904. } else {
  4905. isJiaMi = false
  4906. realLyricPath = lyricPath
  4907. console.info("onecold 找到本地歌词 ");
  4908. }
  4909. // 3.读取文件内容并指定编码为 UTF-8
  4910. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_WRITE);
  4911. let arrayBuffer = new ArrayBuffer(4096);
  4912. fs.read(file.fd, arrayBuffer)
  4913. .then((readLen: number) => {
  4914. console.info("read file data succeed");
  4915. // let buf = buffer.from(arrayBuffer, 0, readLen);
  4916. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  4917. // 检查 buf 是否为空
  4918. if (buf.length === 0) {
  4919. throw new Error("Buffer is empty after reading the file");
  4920. }
  4921. try {
  4922. // 检测文件编码
  4923. let detectedEncoding = chardet.detect(buf);
  4924. console.info("Detected encoding: " + detectedEncoding);
  4925. // 使用检测到的编码解码,解决中文乱码问题
  4926. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  4927. let fileContent = textDecoder.decode(buf);
  4928. console.info(`onecold The content of file1: ${fileContent}`);
  4929. //解密
  4930. if (isJiaMi) {
  4931. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  4932. }
  4933. console.info(`onecold The content of file2: ${fileContent}`);
  4934. this.lyricContent = fileContent
  4935. // 将文件内容按行分割成字符串数组
  4936. let lines = fileContent.split('\n').map(line => line.trim());
  4937. console.info(`onecold The content of file: ${fileContent}`);
  4938. // 3.解析歌词
  4939. let lyric = this.parser.parse(lines);
  4940. // 4.设置歌词
  4941. this.lyricController.setLyric(lyric);
  4942. this.lyricControllerXF.setLyric(lyric)
  4943. this.showSingleLyric = true
  4944. console.info(`The content of file: ${fileContent}`);
  4945. } catch (chardetError) {
  4946. console.error("chardet.detect failed with error: " + chardetError.message);
  4947. this.lyricController.setLyric(null);
  4948. this.lyricControllerXF.setLyric(null)
  4949. }
  4950. })
  4951. .catch((err: BusinessError) => {
  4952. this.lyricController.setLyric(null)
  4953. this.lyricControllerXF.setLyric(null)
  4954. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  4955. })
  4956. .catch((err: Error) => {
  4957. this.lyricController.setLyric(null)
  4958. this.lyricControllerXF.setLyric(null)
  4959. console.error("read file 2 data failed with error message: " + err.message);
  4960. })
  4961. .finally(() => {
  4962. fs.closeSync(file);
  4963. });
  4964. } catch (error) {
  4965. this.lyricController.setLyric(null)
  4966. this.lyricControllerXF.setLyric(null)
  4967. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  4968. }
  4969. }
  4970. //初始化悬浮歌词的自定义设置
  4971. initPipLyricSetting(){
  4972. this.lyricControllerXF
  4973. .setTextSize(this.currentLyricSize)
  4974. .setCacheSize(4)
  4975. .setTextColor("#DDDDDD")
  4976. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  4977. .setEmptyHint("")
  4978. .setAnimationDuration(1000)
  4979. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  4980. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 2)
  4981. this.setBlurDegree(this.blurDegreePip,true)
  4982. this.setLyricAlignMode(this.currentLyricAlignModePip,true)
  4983. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18),true)
  4984. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23),true)
  4985. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 52))
  4986. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'),true)
  4987. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'),true)
  4988. this.lyricControllerXF.setHightLightCenter(true)
  4989. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip',400)
  4990. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  4991. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  4992. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  4993. if(this.pipBgIndex ===0 ){
  4994. if(this.cover){
  4995. this.pipBg = this.cover
  4996. }else{
  4997. this.pipBg = this.imageColor
  4998. }
  4999. this.nodeController.updateBgColor(this.pipBg,this.lyricControllerXF)
  5000. }
  5001. }
  5002. //根据item返回歌词内容
  5003. async getLyricContent(item: VideoItem): Promise<string> {
  5004. try {
  5005. let filePath = item.filePath;
  5006. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  5007. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  5008. let isJiaMi = false;
  5009. let realLyricPath = lyricPath;
  5010. if (FileUtil.accessSync(jiaMilyricPath)) {
  5011. isJiaMi = true;
  5012. realLyricPath = jiaMilyricPath;
  5013. console.info("onecold 找到加密本地歌词");
  5014. } else {
  5015. console.info("onecold 找到本地歌词");
  5016. }
  5017. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_WRITE);
  5018. let arrayBuffer = new ArrayBuffer(4096);
  5019. const readLen = await fs.read(file.fd, arrayBuffer);
  5020. console.info("read file data succeed");
  5021. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  5022. if (buf.length === 0) {
  5023. throw new Error("Buffer is empty after reading the file");
  5024. }
  5025. let detectedEncoding = chardet.detect(buf);
  5026. console.info("Detected encoding: " + detectedEncoding);
  5027. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  5028. let fileContent = textDecoder.decode(buf);
  5029. console.info(`onecold The content of file1: ${fileContent}`);
  5030. if (isJiaMi) {
  5031. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  5032. }
  5033. console.info(`onecold The content of file2: ${fileContent}`);
  5034. fs.closeSync(file);
  5035. return fileContent;
  5036. } catch (error) {
  5037. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  5038. return '';
  5039. }
  5040. }
  5041. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  5042. if (StrUtil.isEmpty(filePath)) {
  5043. return
  5044. }
  5045. try {
  5046. //将content进行加密
  5047. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  5048. let lyricContent = ''
  5049. if (isJiaMi) {
  5050. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  5051. } else {
  5052. lyricContent = content
  5053. }
  5054. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  5055. // 清空文件内容
  5056. await fileIo.truncate(file.fd, 0);
  5057. await fileIo.write(file.fd, lyricContent);
  5058. await fileIo.close(file);
  5059. console.log('onecold lyric file Data saved successfully.');
  5060. } catch (error) {
  5061. console.error('onecold lyric file Failed to save data:', error);
  5062. }
  5063. }
  5064. /**
  5065. * Get largest proportion color of an image.
  5066. */
  5067. getImageColor() {
  5068. if (!this.context) {
  5069. return;
  5070. }
  5071. let bg = Utility.getMusisBg()
  5072. this.imageLabel = bg
  5073. ColorConversion.setSysBarLightBackground(true);
  5074. this.context.resourceManager.getMediaContent(bg)
  5075. .then((value: Uint8Array) => {
  5076. let buffer = value.buffer as ArrayBuffer;
  5077. image.createImageSource(buffer).createPixelMap().then((pixelMap) => {
  5078. effectKit.createColorPicker(pixelMap, (error, colorPicker) => {
  5079. if (error) {
  5080. Logger.error('Failed to create color picker.');
  5081. } else {
  5082. let color = colorPicker.getLargestProportionColor();
  5083. let colorArr = ColorConversion.dealColor(color.red, color.green, color.blue);
  5084. this.imageColor = `rgba(${colorArr[0]}, ${colorArr[1]}, ${colorArr[2]}, 1)`;
  5085. }
  5086. })
  5087. let headFilter = effectKit.createEffect(pixelMap);
  5088. if (headFilter !== null) {
  5089. headFilter.blur(15);
  5090. headFilter.getEffectPixelMap().then((value) => {
  5091. this.imageLabelBg = value;
  5092. })
  5093. }
  5094. })
  5095. .catch((error: BusinessError) => {
  5096. Logger.error(`${error.code} + ${error.message}`)
  5097. })
  5098. })
  5099. .catch((error: BusinessError) => {
  5100. Logger.error(`${error.code} + ${error.message}`)
  5101. })
  5102. }
  5103. setImageColor(cover: string) {
  5104. if (!this.context) {
  5105. return;
  5106. }
  5107. if (cover === undefined) {
  5108. return;
  5109. }
  5110. ImageUtil.imagePathToPixelMap(cover).then((value) => {
  5111. let headFilter = effectKit.createEffect(value);
  5112. if (headFilter !== null) {
  5113. headFilter.blur(15);
  5114. headFilter.getEffectPixelMap().then((value) => {
  5115. this.imageLabelBg = value;
  5116. })
  5117. }
  5118. }).catch((error: BusinessError) => {
  5119. Logger.error(`${error.code} + ${error.message}`)
  5120. })
  5121. }
  5122. setImageColor2(cover: string) {
  5123. if (!this.context) {
  5124. return;
  5125. }
  5126. if (cover === undefined) {
  5127. return;
  5128. }
  5129. LogUtils.getInstance().LOGI("setImageColor2--> cover ==" + cover);
  5130. ImageUtils.getImageDealData(getContext(this), cover, this.videoUrl).then((data) => {
  5131. this.imageColor = data.imageColor;
  5132. if (data.blurPixelMap) {
  5133. this.imageLabelBg = data.blurPixelMap;
  5134. }
  5135. })
  5136. }
  5137. // 定义开始旋转的方法
  5138. // 定时器用于一百毫秒执行一次旋转角度
  5139. @State timer: number = 0
  5140. @State rotateAngle: number = 0
  5141. //封面旋转动画
  5142. animationRoFun() {
  5143. if (this.isPlaying && !this.isCoverRectangle) {
  5144. this.timer = setInterval(() => {
  5145. this.rotateAngle += 1
  5146. }, 100)
  5147. this.startRotation()
  5148. } else {
  5149. clearInterval(this.timer)
  5150. this.stopRotation()
  5151. }
  5152. }
  5153. // 定义开始旋转的方法
  5154. startRotation() {
  5155. if (this.isPlaying) {
  5156. animateTo({
  5157. duration: 777,
  5158. iterations: 1,
  5159. curve: Curve.Linear
  5160. }, () => {
  5161. this.rotateAngle2 = 0
  5162. })
  5163. }
  5164. }
  5165. // 回调,暂停和播放按钮回调,下一首和上一首
  5166. playChange() {
  5167. // if(this.isCoverRectangle){
  5168. // return
  5169. // }
  5170. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  5171. this.setIsPlaying(true)
  5172. this.animationState = AnimationStatus.Running
  5173. } else {
  5174. this.setIsPlaying(false)
  5175. this.animationState = AnimationStatus.Paused
  5176. }
  5177. }
  5178. // 定义停止旋转的方法
  5179. stopRotation() {
  5180. if (this.isCoverRectangle) {
  5181. this.rotateAngle = 0
  5182. } else {
  5183. //唱针以左上角为点选择逆时针40度
  5184. animateTo({
  5185. duration: 1000,
  5186. curve: Curve.Linear,
  5187. iterations: 1,
  5188. }, () => {
  5189. this.rotateAngle2 = -40;
  5190. });
  5191. }
  5192. }
  5193. @Builder
  5194. private LyricsTopItem() {
  5195. Row() {
  5196. Stack() {
  5197. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  5198. .height(55)
  5199. .width(55)
  5200. .alt(this.imageLabel)
  5201. .borderRadius(8)
  5202. .clickEffect({level:ClickEffectLevel.HEAVY})
  5203. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  5204. }
  5205. .width('18%')
  5206. Column() {
  5207. Column() {
  5208. Text(this.name)
  5209. .fontSize(16)
  5210. .maxLines(1)
  5211. .fontWeight(FontWeight.Bolder)
  5212. .fontColor(this.currentLyricColor)
  5213. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  5214. Row() {
  5215. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  5216. .fontSize(13)
  5217. .fontWeight(FontWeight.Bold)
  5218. .padding({ top: 8 })
  5219. .fontColor(this.currentLyricColor)
  5220. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  5221. Blank()
  5222. }
  5223. }
  5224. .height('100%')
  5225. .width('100%')
  5226. .justifyContent(FlexAlign.Center)
  5227. .alignItems(HorizontalAlign.Start)
  5228. }
  5229. .height('100%')
  5230. .width('65%')
  5231. Column() {
  5232. Image($r('app.media.lyric'))
  5233. .width(28)
  5234. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5235. .margin({ right: 30 })
  5236. .clickEffect({level:ClickEffectLevel.HEAVY})
  5237. .onClick(() => {
  5238. this.isLyricSetting = !this.isLyricSetting;
  5239. })
  5240. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  5241. height: this.isCoverOpacity() ? '95%' : '88%',
  5242. dragBar: true,
  5243. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  5244. showClose: true,
  5245. blurStyle: BlurStyle.Thin,
  5246. backgroundColor: Color.Transparent,
  5247. // title: { title: $r('app.string.lyric_setting') }
  5248. })
  5249. }
  5250. .width('18%')
  5251. }
  5252. .width('82%')
  5253. .height(58)
  5254. .justifyContent(FlexAlign.SpaceBetween)
  5255. }
  5256. //歌词显示
  5257. @Builder
  5258. PlayerLyrics() {
  5259. Column() {
  5260. Column() {
  5261. this.LyricsTopItem()
  5262. }
  5263. .height(this.isPuraWP() ? 15 : 58)
  5264. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  5265. Visibility.None: Visibility.Visible)
  5266. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  5267. .width("100%")
  5268. Column() {
  5269. LyricView2({
  5270. controller: this.lyricController,
  5271. enableSeek: true,
  5272. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  5273. seekLineColor: "#80ffffff", // 滑动定位线颜色
  5274. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  5275. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  5276. if(!this.isPlaying){
  5277. this.startPlayOrResumePlay()
  5278. }else{
  5279. this.isSeekTo = true;
  5280. this.mDestroyPage = false;
  5281. this.showLoadIng();
  5282. this.seekTo(position + "");
  5283. this.isSeekTo = false;
  5284. }
  5285. return true
  5286. }
  5287. })
  5288. .width("100%")
  5289. .layoutWeight(1)
  5290. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan() ? 40 :10 })
  5291. }
  5292. .position({
  5293. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  5294. (this.isPuraWP() ? 58 : 99)
  5295. })
  5296. .justifyContent(FlexAlign.Center)
  5297. .height(this.isCoverOpacity() ? '95%' : '80%')
  5298. }
  5299. }
  5300. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  5301. @Builder
  5302. BottomControl() {
  5303. Column() {
  5304. //播放 暂停,下一首,上一首
  5305. Row() {
  5306. Row({ space: 33 }) {
  5307. Button({type:ButtonType.Circle,stateEffect:true}){
  5308. //更多功能
  5309. Image($r('app.media.menu'))
  5310. .width(24)
  5311. .clickEffect({level:ClickEffectLevel.MIDDLE})
  5312. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  5313. height: this.isCoverOpacity() ? '95%' : '93%',
  5314. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  5315. dragBar: true,
  5316. showClose: true,
  5317. blurStyle: BlurStyle.Thin,
  5318. backgroundColor: Color.Transparent,
  5319. })
  5320. }
  5321. .backgroundColor(Color.Transparent)
  5322. .onClick(() => {
  5323. this.isShowMoreView = !this.isShowMoreView;
  5324. })
  5325. Button({type:ButtonType.Circle,stateEffect:true}){
  5326. Image($r('app.media.ic_previous'))
  5327. .width(33)
  5328. .clickEffect({level:ClickEffectLevel.HEAVY})
  5329. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5330. .onClick(async () => {
  5331. this.playPrevious()
  5332. })
  5333. }
  5334. .backgroundColor(Color.Transparent)
  5335. }
  5336. .margin({ left: 33 })
  5337. Button({type:ButtonType.Circle,stateEffect:true}){
  5338. Column() {
  5339. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  5340. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  5341. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  5342. .width(this.isPhoneLan()?48:60)
  5343. .clickEffect({level:ClickEffectLevel.HEAVY})
  5344. .fillColor(Color.White)
  5345. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5346. .onClick(async () => {
  5347. this.playOrPause()
  5348. })
  5349. }
  5350. }
  5351. .backgroundColor(Color.Transparent)
  5352. .layoutWeight(1)
  5353. .margin({ left: 33, right: 33 })
  5354. Row({ space: 33 }) {
  5355. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5356. Image($r('app.media.ic_next'))
  5357. .width(33)
  5358. .clickEffect({level:ClickEffectLevel.HEAVY})
  5359. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5360. .onClick(() => {
  5361. this.playNext();
  5362. })
  5363. }
  5364. .backgroundColor(Color.Transparent)
  5365. .width(33)
  5366. Button({type:ButtonType.Circle,stateEffect:true}){
  5367. //添加或取消收藏
  5368. Image(Utility.getIsFav(this.favList,this.currentSong)?
  5369. $r('app.media.add_fac_light'):$r('app.media.add_fac'))
  5370. .width(24)
  5371. .clickEffect({level:ClickEffectLevel.MIDDLE})
  5372. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5373. .onClick(async () => {
  5374. if(this.currentSong){
  5375. this.doFav(this.currentSong)
  5376. }
  5377. })
  5378. }
  5379. .backgroundColor(Color.Transparent)
  5380. .width(24)
  5381. }
  5382. .margin({ right: 33 })
  5383. }
  5384. .width('100%')
  5385. .margin({ left:10,right:10,bottom:this.isCoverOpacity()?0:20 })
  5386. .justifyContent(FlexAlign.Center)
  5387. //播放进度条
  5388. this.playProgressView()
  5389. }
  5390. .position({ bottom:this.isCoverOpacity()?55: 100 }) // 将 固定在底部
  5391. }
  5392. //播放进度条
  5393. @Builder
  5394. playProgressView(){
  5395. Row() {
  5396. Button({type:ButtonType.Circle,stateEffect:true}){
  5397. Column() {
  5398. if (this.playType === 0) {
  5399. Image($r('app.media.loop'))
  5400. .width($r('app.float.control_image_width'))
  5401. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5402. } else if (this.playType === 1) {
  5403. Image($r('app.media.single'))
  5404. .width($r('app.float.control_image_width'))
  5405. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5406. } else if (this.playType === 2) {
  5407. Image($r('app.media.normal_play'))
  5408. .width($r('app.float.control_image_width'))
  5409. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5410. } else if (this.playType === 3) {
  5411. Image($r('app.media.random'))
  5412. .width($r('app.float.control_image_width'))
  5413. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5414. }
  5415. }
  5416. }
  5417. .backgroundColor(Color.Transparent)
  5418. .margin({ left:10,right:10 })
  5419. .onClick(async () => {
  5420. this.setLoopMode()
  5421. })
  5422. Text(this.currentTime)
  5423. .fontSize($r('app.float.slider_font_size'))
  5424. .fontColor(Color.White)
  5425. .margin(3)
  5426. Slider({
  5427. value: this.progressValue,
  5428. min: 0,
  5429. max: this.PROGRESS_MAX_VALUE,
  5430. step: 1,
  5431. style: SliderStyle.OutSet
  5432. })
  5433. .width('600px')
  5434. .blockColor(Color.White)
  5435. .trackColor($r('app.color.track_color'))
  5436. .selectedColor(Color.White)
  5437. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  5438. .layoutWeight(1)
  5439. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  5440. .showSteps(true)
  5441. .showTips(true)
  5442. .enabled(this.slideEnable)
  5443. .onChange((value: number, mode: SliderChangeMode) => {
  5444. // if (mode == 2) {
  5445. this.isSeekTo = true;
  5446. this.mDestroyPage = false;
  5447. this.showLoadIng();
  5448. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  5449. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  5450. this.seekTo(seekValue + "");
  5451. // this.setProgress()
  5452. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  5453. this.isSeekTo = false;
  5454. // }
  5455. })
  5456. Text(this.totalTime)
  5457. .fontSize($r('app.float.slider_font_size'))
  5458. .fontColor(Color.White)
  5459. .margin(3)
  5460. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  5461. //播放列表
  5462. Button({type:ButtonType.Circle,stateEffect:true}){
  5463. Image($r('app.media.playlist'))
  5464. .width($r('app.float.control_image_width'))
  5465. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5466. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  5467. height: '95%',
  5468. dragBar: true,
  5469. showClose: true,
  5470. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  5471. blurStyle: BlurStyle.Thin,
  5472. backgroundColor: Color.Transparent,
  5473. title: {
  5474. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  5475. + `(${this.songList.length}首)`
  5476. }
  5477. })
  5478. }
  5479. .backgroundColor(Color.Transparent)
  5480. .margin({ right: 10, left: 20 })
  5481. .onClick(() => {
  5482. this.isShowSheetView = !this.isShowSheetView;
  5483. this.isFrontWhite = true
  5484. setTimeout(() => {
  5485. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  5486. }, 123)
  5487. })
  5488. }
  5489. .width(PlayConstants.PROGRESS_ROW_WIDTH)
  5490. .height(this.isPhoneLan()?25:33)
  5491. .visibility(this.isPhoneLan()&&this.isAutoHide?Visibility.None:Visibility.Visible)
  5492. .animation({
  5493. duration: 666,
  5494. curve: 'ease-in-out' // 可选动画曲线
  5495. })
  5496. }
  5497. isBigScreen(){
  5498. if(this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG){
  5499. return true
  5500. }
  5501. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  5502. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  5503. &&this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  5504. return false
  5505. }else{
  5506. return true
  5507. }
  5508. return false
  5509. }
  5510. @State isAutoHide: boolean = true//手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  5511. @State isCoverRectangle: boolean = false
  5512. @State isCoverTop: boolean = true
  5513. @Builder
  5514. CoverInfo() {
  5515. Column() {
  5516. //如果是方形,判断是不是封面在顶部,如果不是顶部,显示musicNameInfo, 如果是圆形显示musicNameInfo
  5517. if(this.isCoverRectangle){
  5518. if(!this.isCoverTop){
  5519. this.musicNameInfo(false)
  5520. }
  5521. }else{
  5522. this.musicNameInfo(false)
  5523. }
  5524. Stack() {
  5525. // 唱片旋转效果
  5526. Image($r('app.media.ic_music_disc'))
  5527. .width(250)
  5528. .height(250)
  5529. .margin({ right: 20, left: 20 })
  5530. .aspectRatio(1)
  5531. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  5532. .visibility(this.isCoverOpacity() || this.isCoverRectangle?Visibility.None:Visibility.Visible)
  5533. .borderRadius('100%')
  5534. .align(Alignment.Center)
  5535. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  5536. .rotate({
  5537. angle: this.rotateAngle,
  5538. centerX: "50%",
  5539. centerY: "50%",
  5540. })
  5541. .animation({
  5542. duration: 100,
  5543. curve: Curve.Linear
  5544. })
  5545. .shadow({
  5546. radius: 30,
  5547. color: this.randomColor
  5548. })
  5549. Column(){
  5550. if(this.isCoverTop&&!this.isCoverOpacity()&&this.isCoverRectangle){
  5551. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  5552. // .height(this.isCoverOpacity() ? 250 : this.isCoverRectangle ? 320 : 162)
  5553. .width(this.isBigScreen()?'72%':this.isCoverTopBig?'100%':'86%')
  5554. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  5555. .alt(this.imageLabel)
  5556. .margin({ right: 8, left: 8,top:8 })
  5557. .aspectRatio(1)
  5558. .visibility(this.isPuraWP()?Visibility.None:Visibility.Visible)
  5559. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  5560. .clickEffect({level:ClickEffectLevel.MIDDLE})
  5561. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  5562. TransitionEffect.scale({ x: 0, y: 0 }) ))
  5563. .align(Alignment.Center)//
  5564. .clip(true)
  5565. .rotate({
  5566. x: 0,
  5567. y: 0,
  5568. z: 1,
  5569. angle: this.rotateAngle
  5570. })
  5571. .onClick(() => {
  5572. this.getImageColor()
  5573. })
  5574. this.musicNameInfo(false)
  5575. }else{
  5576. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  5577. .height(this.isCoverOpacity() ? 250 : this.isCoverRectangle ? 320 : 162)
  5578. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  5579. .alt(this.imageLabel)
  5580. .margin({ right: 20, left: 20 })
  5581. .aspectRatio(1)
  5582. .visibility(this.isPuraWP()?Visibility.None:Visibility.Visible)
  5583. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  5584. .clickEffect({level:ClickEffectLevel.MIDDLE})
  5585. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  5586. TransitionEffect.scale({ x: 0, y: 0 }) ))
  5587. .align(Alignment.Center)//
  5588. .clip(true)
  5589. .rotate({
  5590. x: 0,
  5591. y: 0,
  5592. z: 1,
  5593. angle: this.rotateAngle
  5594. })
  5595. .onClick(() => {
  5596. this.getImageColor()
  5597. })
  5598. }
  5599. }
  5600. // 唱针以左上角为点选择逆时针40度
  5601. Image($r('app.media.ic_music_cover_hand'))
  5602. .height(130)
  5603. .margin({ bottom: 220, top: 0 })
  5604. .align(Alignment.Top)
  5605. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  5606. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  5607. .visibility(this.isCoverOpacity() || this.isCoverRectangle?Visibility.None:Visibility.Visible)
  5608. Column({ space: 8 }) {
  5609. Text(this.name)
  5610. .fontSize(this.isPuraWP()?24:(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  5611. .fontWeight(FontWeight.Bold)
  5612. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  5613. .maxLines(1)
  5614. .width('48%')
  5615. .textAlign(TextAlign.Center)
  5616. .fontColor(Color.White)
  5617. .visibility(this.isPhoneLan()?Visibility.None:Visibility.Visible)
  5618. Text(this.artist)
  5619. .fontSize(this.isPuraWP()?18:(this.isCoverOpacity() ? 12 : 15))
  5620. .fontColor(Color.White)
  5621. .fontWeight(FontWeight.Bold)
  5622. .visibility(this.isPhoneLan()?Visibility.None:Visibility.Visible)
  5623. }
  5624. .justifyContent(FlexAlign.Start)
  5625. .zIndex(1)
  5626. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  5627. }
  5628. .margin({
  5629. bottom: this.isCoverOpacity() || this.isCoverRectangle ? 55 : 0,
  5630. top: this.isCoverOpacity() ? 0 : 20
  5631. })
  5632. this.BottomControl()
  5633. }
  5634. .width(CommonConstants.FULL_PERCENT)
  5635. .clip(true)
  5636. }
  5637. @Builder
  5638. private musicNameInfo(isHidden:boolean) {
  5639. Column({ space: 8 }) {
  5640. Text(this.name)
  5641. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22)
  5642. .fontWeight(FontWeight.Bold)
  5643. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  5644. .maxLines(1)
  5645. .width('99%')
  5646. .textAlign(TextAlign.Center)
  5647. .fontColor(Color.White)
  5648. Text(this.artist + ' ' + this.currentSong?.album)
  5649. .fontSize(this.isCoverOpacity() ? 12 : 15)
  5650. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  5651. .fontColor(Color.White)
  5652. .textAlign(TextAlign.Center)
  5653. .width('99%')
  5654. .maxLines(1)
  5655. }
  5656. .margin({ top: this.isCoverOpacity() ? 20 : isHidden?40:20 })
  5657. .zIndex(1)
  5658. .visibility(this.isCoverOpacity()||isHidden ? Visibility.None : Visibility.Visible)
  5659. }
  5660. @Builder
  5661. private PlayTitle() {
  5662. Row() {
  5663. Row() {
  5664. Image($r('app.media.ic_back_down'))
  5665. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  5666. .hitTestBehavior(HitTestMode.Transparent)
  5667. Text(this.name + ' ' + this.artist)
  5668. .fontColor(Color.White)
  5669. .fontSize($r('app.float.title_font_size'))
  5670. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  5671. .maxLines(1)
  5672. .visibility(Visibility.None)
  5673. .margin({ left: 2, right: 30 })
  5674. }
  5675. .layoutWeight(1)
  5676. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  5677. .onClick(() => {
  5678. this.isShowPlay = false;
  5679. })
  5680. Column() {
  5681. AVCastPicker({
  5682. normalColor: Color.White,
  5683. onStateChange: this.onStateVastChange
  5684. })
  5685. .width(24)
  5686. .height(24)
  5687. }
  5688. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  5689. //更多功能
  5690. // Image( $r('app.media.two_point') )
  5691. // .width(24)
  5692. // .visibility(this.isHide?Visibility.None:Visibility.Visible)
  5693. // .margin({left:13})
  5694. // .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  5695. // height:this.isCoverOpacity()?'95%':'85%',
  5696. // dragBar: true,
  5697. // showClose: true,
  5698. // blurStyle:BlurStyle.Thin,
  5699. // backgroundColor:Color.Transparent,
  5700. // })
  5701. // .onClick(() => {
  5702. // this.isShowMoreView = !this.isShowMoreView;
  5703. // })
  5704. }
  5705. .width(PlayConstants.ROW_WIDTH)
  5706. }
  5707. @Builder
  5708. lyricSettingSheet(isPip:boolean) {
  5709. Scroll() {
  5710. this.lyricSetting(isPip)
  5711. }
  5712. .width('100%')
  5713. .height('100%')
  5714. }
  5715. @Builder
  5716. lyricSetting(isPip:boolean) {
  5717. Column() {
  5718. // 时间调节模块
  5719. if(!isPip){
  5720. this.BuildTimeControls()
  5721. }
  5722. // 字号控制模块
  5723. this.BuildFontControls(isPip)
  5724. }
  5725. }
  5726. // 歌词时间偏移状态
  5727. @State timeOffset: number = 0.0
  5728. @State currentLyricColor: string = '#FFFFFF'
  5729. @State currentLyricColorPip: string = '#FFFFFF'
  5730. @State currentHighLightLyricColor: string = '#FF4081'
  5731. @State currentHighLightLyricColorPip: string = '#FF4081'
  5732. // 歌词字号状态
  5733. @State currentLyricSize: number = 20
  5734. @State currentLyricSizePip: number = 20
  5735. // 高亮歌词放大倍数
  5736. @State currentHightLyricSize: number = 1.2
  5737. @State currentHightLyricSizePip: number = 1.2
  5738. @State currentLyricLineSpace: number = 52
  5739. @State currentLyricLineSpacePip: number = 52
  5740. @State currentLyricAlignMode: number = 1
  5741. @State currentLyricAlignModePip: number = 1
  5742. @State blurDegree: number = 2
  5743. @State blurDegreePip: number = 2
  5744. @State isShowSelectColor: boolean = false
  5745. @State isShowHLSelectColor: boolean = false
  5746. @State isShowPipBgSelectColor: boolean = false
  5747. @State pipLyWidth: number = 330
  5748. @State pipLyHeight: number = 120
  5749. // 构建颜色选择器
  5750. @Builder
  5751. SelectColor(isHighColor:boolean,isPip:boolean,isBGPip?:boolean) {
  5752. Row({space: 10}) {
  5753. HSBColorPicker({
  5754. color: '#FFFFFF',
  5755. radius: 8,
  5756. layout: HSBColorPickerLayout.COLUMN,
  5757. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4', '#fa7105'],
  5758. onChange:(value: string) =>isHighColor?this.changeLyricHightLightColor(value,isPip):this.changeLyricColor(value,isPip,isBGPip)
  5759. })
  5760. .height(250)
  5761. .layoutWeight(1)
  5762. .padding(25)
  5763. }
  5764. .width('66%')
  5765. }
  5766. @State isOpenPip:boolean = false
  5767. @State pipBgIndex:number = 0
  5768. // 构建字号控制器
  5769. @Builder
  5770. BuildFontControls(isPip:boolean) {
  5771. Column() {
  5772. if(isPip){
  5773. Column() {
  5774. Row() {
  5775. Text('悬浮歌词')
  5776. .margin({ left: 18 })
  5777. .fontSize(15)
  5778. .fontColor(Color.White)
  5779. .fontWeight(480)
  5780. .layoutWeight(1)
  5781. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  5782. .selectedColor(this.themeColor)
  5783. .switchPointColor(Color.White)
  5784. .margin({ right: 18 })
  5785. .onChange((checked: boolean) => {
  5786. this.isOpenPip = checked;
  5787. if(this.isOpenPip){
  5788. this.startPip()
  5789. }else{
  5790. this.stopPip()
  5791. }
  5792. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  5793. })
  5794. .width(50)
  5795. .height(30);
  5796. }
  5797. .height(55)
  5798. }
  5799. .backgroundColor(Color.Transparent)
  5800. .borderRadius(15)
  5801. .margin({ left: 30, right: 30, top: 0, bottom: 20 })
  5802. .padding(0)
  5803. .border({
  5804. color: Color.White,
  5805. width: 1.8
  5806. })
  5807. }
  5808. Row() {
  5809. Text(`歌词居中:`)
  5810. .fontSize(14)
  5811. .fontColor(Color.White)
  5812. .margin({left:2})
  5813. Row() {
  5814. ForEach(['居中', '居左'], (size: string, index: number) => {
  5815. Button(size)
  5816. .width(60)
  5817. .height(28)
  5818. .fontSize(12)
  5819. .fontColor('#FFFFFF')
  5820. .backgroundColor((!isPip&&this.currentLyricAlignMode === index)||(isPip&&this.currentLyricAlignModePip === index) ? this.themeColor :Color.Transparent)
  5821. .border({
  5822. color: (!isPip&&this.currentLyricAlignMode === index) || (isPip&&this.currentLyricAlignModePip === index)?
  5823. '#007DFF' : '#DDDDDD',
  5824. width: 1.8
  5825. })
  5826. .onClick(() => {
  5827. this.setLyricAlignMode(index,isPip)
  5828. })
  5829. .margin({ left: 10, right: 8 })
  5830. })
  5831. }
  5832. .width('76%')
  5833. Blank()
  5834. }
  5835. .margin({ top:10,bottom:10,right:20,left:20})
  5836. if(isPip){
  5837. Row() {
  5838. Text(`悬浮背景:`)
  5839. .fontSize(14)
  5840. .fontColor(Color.White)
  5841. Select([
  5842. { value:CommonConstants.PIP_LYRIC_BG[0]},
  5843. { value: CommonConstants.PIP_LYRIC_BG[1]}])
  5844. .font({ size: 13, weight: FontWeight.Medium })
  5845. .fontColor(Color.White)
  5846. .margin({ left: 10 })
  5847. .selected(this.pipBgIndex)
  5848. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  5849. .onSelect(async (_index: number, text?: string | undefined) => {
  5850. this.pipBgIndex = _index
  5851. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  5852. if(this.pipBgIndex ===0 ){
  5853. if(this.cover){
  5854. this.pipBg = this.cover
  5855. }else{
  5856. this.pipBg = this.imageColor
  5857. }
  5858. this.nodeController.updateBgColor(this.pipBg,this.lyricControllerXF)
  5859. }else{
  5860. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  5861. }
  5862. })
  5863. Column(){}
  5864. .backgroundColor(this.pipBg)
  5865. .margin({ left:10,right: 10 })
  5866. .borderRadius(20)
  5867. .height(28)
  5868. .width(28)
  5869. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5870. Row() {
  5871. SymbolGlyph($r('sys.symbol.paintbrush'))
  5872. .fontColor([Color.White])
  5873. .effectStrategy(1)
  5874. Text(`选择颜色`)
  5875. .fontSize(13)
  5876. .margin({ left: 10 })
  5877. .fontColor(Color.White)
  5878. }
  5879. }
  5880. .visibility(this.pipBgIndex===1?Visibility.Visible:Visibility.None)
  5881. .backgroundColor(Color.Transparent)
  5882. .border({
  5883. color: '#FFFFFF',
  5884. radius: 20,
  5885. width: 1.8
  5886. })
  5887. .height(36)
  5888. .width(110)
  5889. .onClick(()=>{
  5890. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  5891. })
  5892. .bindPopup(this.isShowPipBgSelectColor, {
  5893. builder: this.SelectColor(false,isPip,true),
  5894. placement: Placement.Top,
  5895. mask: {color:'#33000000'},
  5896. enableArrow: false,//是否显示箭头
  5897. showInSubWindow: false,
  5898. onStateChange: (e) => {
  5899. if (!e.isVisible) {
  5900. this.isShowPipBgSelectColor = false
  5901. }
  5902. }
  5903. })
  5904. }
  5905. .width('76%')
  5906. .margin({ bottom:5,right:45,left:20})
  5907. }
  5908. if(!isPip){
  5909. Row() {
  5910. Text(`高亮居中:`)
  5911. .fontSize(14)
  5912. .fontColor(Color.White)
  5913. Column(){
  5914. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  5915. .selectedColor(this.themeColor)
  5916. .switchPointColor(Color.White)
  5917. .onChange((checked: boolean) => {
  5918. this.isHightLightCenter = checked;
  5919. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  5920. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  5921. })
  5922. .width(50)
  5923. .height(30)
  5924. .alignSelf(ItemAlign.Start)
  5925. .margin({ left: 12 })
  5926. Blank()
  5927. }
  5928. .width('76%')
  5929. }
  5930. .margin({
  5931. left: 20,
  5932. right: 15,
  5933. top: 10,
  5934. bottom: 10
  5935. })
  5936. }
  5937. Row() {
  5938. Text(`歌词颜色:`)
  5939. .fontSize(14)
  5940. .fontColor(Color.White)
  5941. Text(isPip?this.currentLyricColorPip:this.currentLyricColor)
  5942. .fontSize(15)
  5943. .fontColor(Color.White)
  5944. .margin({ left: 12, right: 12 })
  5945. Column(){}
  5946. .backgroundColor(isPip?this.currentLyricColorPip:this.currentLyricColor)
  5947. .margin({ right: 12 })
  5948. .borderRadius(20)
  5949. .height(28)
  5950. .width(28)
  5951. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5952. Row() {
  5953. SymbolGlyph($r('sys.symbol.paintbrush'))
  5954. .fontColor([Color.White])
  5955. .effectStrategy(1)
  5956. Text(`选择颜色`)
  5957. .fontSize(13)
  5958. .margin({ left: 10 })
  5959. .fontColor(Color.White)
  5960. }
  5961. }
  5962. .backgroundColor(Color.Transparent)
  5963. .border({
  5964. color: '#FFFFFF',
  5965. radius: 20,
  5966. width: 1.8
  5967. })
  5968. .height(36)
  5969. .width(110)
  5970. .onClick(()=>{
  5971. this.isShowSelectColor = !this.isShowSelectColor
  5972. })
  5973. .bindPopup(this.isShowSelectColor, {
  5974. builder: this.SelectColor(false,isPip),
  5975. placement: Placement.Top,
  5976. mask: {color:'#33000000'},
  5977. enableArrow: false,//是否显示箭头
  5978. showInSubWindow: false,
  5979. onStateChange: (e) => {
  5980. if (!e.isVisible) {
  5981. this.isShowSelectColor = false
  5982. }
  5983. }
  5984. })
  5985. }
  5986. .width('76%')
  5987. .margin({ top:10,bottom:10,right:45,left:20})
  5988. Row() {
  5989. Text(`高亮颜色:`)
  5990. .fontSize(14)
  5991. .fontColor(Color.White)
  5992. Text(isPip?this.currentHighLightLyricColorPip:this.currentHighLightLyricColor)
  5993. .fontSize(15)
  5994. .fontColor(Color.White)
  5995. .margin({ left: 12, right: 12 })
  5996. Column(){}
  5997. .backgroundColor(isPip?this.currentHighLightLyricColorPip:this.currentHighLightLyricColor)
  5998. .margin({ right: 12 })
  5999. .borderRadius(20)
  6000. .height(28)
  6001. .width(28)
  6002. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6003. Row() {
  6004. SymbolGlyph($r('sys.symbol.paintbrush'))
  6005. .fontColor([Color.White])
  6006. .effectStrategy(1)
  6007. Text(`选择颜色`)
  6008. .fontSize(13)
  6009. .margin({ left: 10 })
  6010. .fontColor(Color.White)
  6011. }
  6012. }
  6013. .backgroundColor(Color.Transparent)
  6014. .border({
  6015. color: '#FFFFFF',
  6016. radius: 20,
  6017. width: 1.8
  6018. })
  6019. .height(36)
  6020. .width(110)
  6021. .onClick(()=>{
  6022. this.isShowHLSelectColor = !this.isShowHLSelectColor
  6023. })
  6024. .bindPopup(this.isShowHLSelectColor, {
  6025. builder: this.SelectColor(true,isPip),
  6026. placement: Placement.Top,
  6027. mask: {color:'#33000000'},
  6028. enableArrow: false,//是否显示箭头
  6029. showInSubWindow: false,
  6030. onStateChange: (e) => {
  6031. if (!e.isVisible) {
  6032. this.isShowHLSelectColor = false
  6033. }
  6034. }
  6035. })
  6036. }
  6037. .width('76%')
  6038. .margin({ top:10,bottom:10,right:45,left:20})
  6039. if(isPip){
  6040. Row() {
  6041. Text(`显示宽度:`)
  6042. .fontSize(14)
  6043. .fontColor(Color.White)
  6044. Slider({
  6045. value: this.pipLyWidth,
  6046. min: 10,
  6047. max: 800,
  6048. step: 1,
  6049. style: SliderStyle.OutSet
  6050. })
  6051. .blockColor(this.themeColor)
  6052. .trackColor($r('app.color.speed_text_color'))
  6053. .selectedColor(Color.White)
  6054. .trackThickness(6)
  6055. .onChange((value: number) => {
  6056. this.pipLyWidth = value
  6057. if(this.pipController){
  6058. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  6059. PreferencesUtil.putSync('pipLyWidth',this.pipLyWidth)
  6060. }
  6061. })
  6062. .width('76%')
  6063. }
  6064. .margin({
  6065. left: 20,
  6066. right: 15,
  6067. top: 5,
  6068. bottom: 5
  6069. })
  6070. Row() {
  6071. Text(`显示高度:`)
  6072. .fontSize(14)
  6073. .fontColor(Color.White)
  6074. Slider({
  6075. value: this.pipLyHeight,
  6076. min: 10,
  6077. max: 1000,
  6078. step: 1,
  6079. style: SliderStyle.OutSet
  6080. })
  6081. .blockColor(this.themeColor)
  6082. .trackColor($r('app.color.speed_text_color'))
  6083. .selectedColor(Color.White)
  6084. .trackThickness(6)
  6085. .onChange((value: number) => {
  6086. this.pipLyHeight = value
  6087. if(this.pipController){
  6088. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  6089. PreferencesUtil.putSync('pipLyHeight',this.pipLyHeight)
  6090. }
  6091. })
  6092. .width('76%')
  6093. }
  6094. .margin({
  6095. left: 20,
  6096. right: 15,
  6097. top: 5,
  6098. bottom: 5
  6099. })
  6100. }
  6101. Row() {
  6102. Text(`歌词字号:`)
  6103. .fontSize(14)
  6104. .fontColor(Color.White)
  6105. Slider({
  6106. value: isPip?this.currentLyricSizePip:this.currentLyricSize,
  6107. min: 12,
  6108. max: 30,
  6109. step: 0.1,
  6110. style: SliderStyle.OutSet
  6111. })
  6112. .blockColor(this.themeColor)
  6113. .trackColor($r('app.color.speed_text_color'))
  6114. .selectedColor(Color.White)
  6115. .trackThickness(6)
  6116. .onChange((value: number) => {
  6117. this.setLyricTextSize(value,isPip)
  6118. })
  6119. .width('76%')
  6120. }
  6121. .margin({
  6122. left: 20,
  6123. right: 15,
  6124. top: 5,
  6125. bottom: 5
  6126. })
  6127. Row() {
  6128. Text(`高亮倍数:`)
  6129. .fontSize(14)
  6130. .fontColor(Color.White)
  6131. Slider({
  6132. value: isPip?this.currentHightLyricSizePip:this.currentHightLyricSize,
  6133. min: 1,
  6134. max: 2,
  6135. step: 0.1,
  6136. style: SliderStyle.OutSet
  6137. })
  6138. .blockColor(this.themeColor)
  6139. .trackColor($r('app.color.speed_text_color'))
  6140. .selectedColor(Color.White)
  6141. .trackThickness(6)
  6142. .onChange((value: number) => {
  6143. this.setHighLyricTextSize(value,isPip)
  6144. })
  6145. .width('76%')
  6146. }
  6147. .margin({
  6148. left: 20,
  6149. right: 15,
  6150. top: 5,
  6151. bottom: 5
  6152. })
  6153. Row() {
  6154. Text(`歌词间隙:`)
  6155. .fontSize(14)
  6156. .fontColor(Color.White)
  6157. Slider({
  6158. value: isPip?this.currentLyricLineSpacePip:this.currentLyricLineSpace,
  6159. min: 8,
  6160. max: 120,
  6161. step: 0.1,
  6162. style: SliderStyle.OutSet
  6163. })
  6164. .blockColor(this.themeColor)
  6165. .trackColor($r('app.color.speed_text_color'))
  6166. .selectedColor(Color.White)
  6167. .trackThickness(6)
  6168. .onChange((value: number) => {
  6169. this.setLyricLineSpace(value,isPip)
  6170. })
  6171. .width('76%')
  6172. }
  6173. .margin({
  6174. left: 20,
  6175. right: 15,
  6176. top: 5,
  6177. bottom: 5
  6178. })
  6179. //取值间隔为100,默认为400,取值越大,字体越粗
  6180. Row() {
  6181. Text(`歌词字重:`)
  6182. .fontSize(14)
  6183. .fontColor(Color.White)
  6184. Slider({
  6185. value: isPip?this.lyricTextWeightPip:this.lyricTextWeight,
  6186. min: 100,
  6187. max: 900,
  6188. step: 100,
  6189. style: SliderStyle.OutSet
  6190. })
  6191. .blockColor(this.themeColor)
  6192. .trackColor($r('app.color.speed_text_color'))
  6193. .selectedColor(Color.White)
  6194. .trackThickness(6)
  6195. .onChange((value: number) => {
  6196. if(isPip){
  6197. this.lyricTextWeightPip = value
  6198. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  6199. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  6200. }else{
  6201. this.lyricTextWeight = value
  6202. this.lyricController.setTextWeight(this.lyricTextWeight)
  6203. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  6204. }
  6205. })
  6206. .width('76%')
  6207. }
  6208. .margin({
  6209. left: 20,
  6210. right: 15,
  6211. top: 5,
  6212. bottom: 5
  6213. })
  6214. if(!isPip){
  6215. Row() {
  6216. Text(`歌词模糊:`)
  6217. .fontSize(14)
  6218. .fontColor(Color.White)
  6219. Slider({
  6220. value: isPip?this.blurDegreePip:this.blurDegree,
  6221. min: 0,
  6222. max: 10,
  6223. step: 0.1,
  6224. style: SliderStyle.OutSet
  6225. })
  6226. .blockColor(this.themeColor)
  6227. .trackColor($r('app.color.speed_text_color'))
  6228. .selectedColor(Color.White)
  6229. .trackThickness(6)
  6230. .onChange((value: number) => {
  6231. this.setBlurDegree(value,isPip)
  6232. })
  6233. .width('76%')
  6234. }
  6235. .margin({
  6236. left: 20,
  6237. right: 15,
  6238. top: 5,
  6239. bottom: 15
  6240. })
  6241. }
  6242. Row() {
  6243. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  6244. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  6245. }
  6246. .justifyContent(FlexAlign.Center)
  6247. .margin({ top: 3, bottom: 10 })
  6248. }
  6249. }
  6250. private setBlurDegree(index: number,isPip:boolean) {
  6251. if(isPip){
  6252. this.blurDegreePip = index
  6253. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  6254. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  6255. }else{
  6256. this.blurDegree = index
  6257. this.lyricController.setBlurDegree(this.blurDegree)
  6258. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  6259. }
  6260. }
  6261. private setLyricAlignMode(index: number,isPip:boolean) {
  6262. if(isPip){
  6263. this.currentLyricAlignModePip = index
  6264. if (this.currentLyricAlignModePip === 1) {
  6265. this.lyricControllerXF.setAlignMode("left")
  6266. } else {
  6267. this.lyricControllerXF.setAlignMode("center")
  6268. }
  6269. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  6270. }else{
  6271. this.currentLyricAlignMode = index
  6272. if (this.currentLyricAlignMode === 1) {
  6273. this.lyricController.setAlignMode("left")
  6274. } else {
  6275. this.lyricController.setAlignMode("center")
  6276. }
  6277. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  6278. }
  6279. }
  6280. private setLyricTextSize(index: number,isPip:boolean) {
  6281. if(isPip){
  6282. this.currentLyricSizePip = index
  6283. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  6284. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  6285. }else{
  6286. this.currentLyricSize = index
  6287. this.lyricController.setTextSize(this.currentLyricSize)
  6288. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  6289. }
  6290. }
  6291. private setHighLyricTextSize(scale: number,isPip:boolean) {
  6292. if(isPip){
  6293. this.currentHightLyricSizePip = scale
  6294. this.lyricControllerXF
  6295. .setHighlightScale(this.currentHightLyricSizePip)
  6296. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  6297. }else{
  6298. this.currentHightLyricSize = scale
  6299. this.lyricController
  6300. .setHighlightScale(this.currentHightLyricSize)
  6301. PreferencesUtil.putSync('HighLyricTextSize', scale)
  6302. }
  6303. }
  6304. private setLyricLineSpace(index: number,isPip:boolean) {
  6305. if(isPip){
  6306. this.currentLyricLineSpacePip = index
  6307. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  6308. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  6309. }else{
  6310. this.currentLyricLineSpace = index
  6311. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  6312. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  6313. }
  6314. }
  6315. private changeLyricColor(color: string,isPip:boolean,isBG?:boolean) {
  6316. LogUtil.info('onecold isBG = '+isBG)
  6317. if(isBG){//如果是设置悬浮背景
  6318. this.pipBg = color
  6319. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  6320. this.nodeController.updateBgColor(this.pipBg,this.lyricControllerXF)
  6321. return
  6322. }
  6323. if(isPip){
  6324. this.currentLyricColorPip = color
  6325. this.lyricControllerXF
  6326. .setTextColor(this.currentLyricColorPip)
  6327. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  6328. }else{
  6329. this.currentLyricColor = color
  6330. this.lyricController
  6331. .setTextColor(this.currentLyricColor)
  6332. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  6333. }
  6334. }
  6335. private changeLyricHightLightColor(color: string,isPip:boolean) {
  6336. if(isPip){
  6337. this.currentHighLightLyricColorPip = color
  6338. this.lyricControllerXF
  6339. .setHighlightColor(this.currentHighLightLyricColorPip)
  6340. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  6341. }else{
  6342. this.currentHighLightLyricColor = color
  6343. this.lyricController
  6344. .setHighlightColor(this.currentHighLightLyricColor)
  6345. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  6346. }
  6347. }
  6348. // 构建时间控制器
  6349. @Builder
  6350. BuildTimeControls() {
  6351. Column() {
  6352. // 时间显示
  6353. Text(this.getTimeText())
  6354. .fontSize(18)
  6355. .fontColor(Color.White)
  6356. .margin({ bottom: 10 })
  6357. Row() {
  6358. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  6359. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  6360. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  6361. }
  6362. .justifyContent(FlexAlign.Center)
  6363. }
  6364. .margin({ top: 12, bottom: 8 })
  6365. }
  6366. // 精度按钮组件
  6367. @Builder
  6368. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  6369. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6370. Column() {
  6371. Image(icon)
  6372. .width(28)
  6373. .margin({ bottom: 5 })
  6374. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  6375. Text(label)
  6376. .fontSize(12)
  6377. .fontColor('#FFFFFF')
  6378. }
  6379. }
  6380. .backgroundColor(Color.Transparent)
  6381. .enabled(!this.isButtonDisabled(step))
  6382. .onClick(() => this.handlePrecisionAdjust(step))
  6383. .padding(5)
  6384. .width(66)
  6385. .height(66)
  6386. .margin({ left: 18, right: 18 })
  6387. .border({
  6388. color: '#FFFFFF',
  6389. width: 1.8
  6390. })
  6391. }
  6392. private handlePrecisionAdjust(step: number) {
  6393. if (step === 0) {
  6394. this.timeOffset = 0
  6395. return
  6396. }
  6397. // 精度处理:保留1位小数
  6398. const newOffset = Number((this.timeOffset + step).toFixed(5))
  6399. // 边界保护(±15.0秒)
  6400. if (newOffset < -30.0 || newOffset > 30.0) {
  6401. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  6402. return
  6403. }
  6404. // 状态更新
  6405. this.timeOffset = newOffset
  6406. }
  6407. // 按钮禁用逻辑
  6408. private isButtonDisabled(step: number): boolean {
  6409. const futureOffset = this.timeOffset + step
  6410. return (futureOffset < -30.0) || (futureOffset > 30.0)
  6411. }
  6412. // 时间显示文本升级
  6413. private getTimeText(): string {
  6414. const absValue = Math.abs(this.timeOffset)
  6415. return this.timeOffset === 0
  6416. ? '歌词时间已重置'
  6417. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  6418. }
  6419. // 导入 本地歌词 搜索歌词
  6420. @Builder
  6421. pushLyricButton(icon: Resource, step: number, label: string) {
  6422. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6423. Row() {
  6424. Image(icon)
  6425. .width(14)
  6426. .margin({ left: 13 })
  6427. Text(label)
  6428. .fontSize(12)
  6429. .margin({ left: 6 })
  6430. .fontColor('#FFFFFF')}
  6431. }
  6432. .onClick(() => {
  6433. switch (step) {
  6434. case 0:
  6435. this.callFilePickerSelectFileForLyric()
  6436. break;
  6437. case 1:
  6438. //判断是不是赞助会员
  6439. if(PreferencesUtil.getStringSync('LRC_API','')===''){
  6440. this.isLyricSetting = false
  6441. this.showTipsDialog()
  6442. return
  6443. }
  6444. if (StrUtil.isNotEmpty(this.videoUrl)) {
  6445. ToastUtil.showToast('正在获取')
  6446. this.isLyricSetting = false
  6447. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  6448. this.initLyric(lyricPath, true);
  6449. }
  6450. break;
  6451. }
  6452. })
  6453. .padding(5)
  6454. .width(110)
  6455. .backgroundColor(Color.Transparent)
  6456. .height(40)
  6457. .margin({ left: 6, right: 6 })
  6458. .border({
  6459. color: '#FFFFFF',
  6460. radius: 20,
  6461. width: 1.8
  6462. })
  6463. }
  6464. showVipDialog() {
  6465. DialogHelper.showCustomContentDialog({
  6466. dialogId: 'vip',
  6467. title: "友情提示",
  6468. autoCancel: false, //点击遮障层时,不关闭弹窗
  6469. backCancel: true, //点击返回键,不关闭弹窗
  6470. contentBuilder: () => {
  6471. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  6472. },
  6473. buttons: [],
  6474. })
  6475. }
  6476. //去赞助的自定义内容
  6477. @Builder
  6478. customVipBuilder(content: string) {
  6479. Column() {
  6480. Text(content)
  6481. .fontColor(Color.Gray)
  6482. .fontSize(16)
  6483. .alignSelf(ItemAlign.Start)
  6484. .margin({ bottom: 15 })
  6485. .fontSize(16)
  6486. Row() {
  6487. Button('取消')
  6488. .fontColor(Color.White)
  6489. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  6490. .height(50)
  6491. .layoutWeight(1)
  6492. .stateEffect(true)
  6493. .margin({ right: 6 })
  6494. .onClick(() => {
  6495. DialogHelper.closeDialog('vip'); //关闭弹框
  6496. })
  6497. Button('开通')
  6498. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  6499. .layoutWeight(1)
  6500. .height(50)
  6501. .backgroundColor(this.themeColor)
  6502. .stateEffect(true)
  6503. .margin({ left: 6 })
  6504. .onClick(() => {
  6505. DialogHelper.closeDialog('vip'); //关闭弹框
  6506. this.isShowPlay = false
  6507. router.pushUrl({
  6508. url: 'pages/VipPage'
  6509. }, router.RouterMode.Single);
  6510. })
  6511. }
  6512. }
  6513. .width("100%")
  6514. .padding(10)
  6515. }
  6516. showTipsDialog() {
  6517. DialogHelper.showCustomContentDialog({
  6518. dialogId: 'tips',
  6519. title: "友情提示",
  6520. autoCancel: false, //点击遮障层时,不关闭弹窗
  6521. backCancel: true, //点击返回键,不关闭弹窗
  6522. contentBuilder: () => {
  6523. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  6524. },
  6525. buttons: [],
  6526. })
  6527. }
  6528. @Builder
  6529. customTipsBuilder(content: string) {
  6530. Column() {
  6531. Text(content)
  6532. .fontColor(Color.Gray)
  6533. .fontSize(16)
  6534. .alignSelf(ItemAlign.Start)
  6535. .margin({ bottom: 15 })
  6536. .fontSize(16)
  6537. Row() {
  6538. Button('取消')
  6539. .fontColor(Color.White)
  6540. .backgroundColor(this.themeColor)
  6541. .height(50)
  6542. .layoutWeight(1)
  6543. .stateEffect(true)
  6544. .margin({ right: 6 })
  6545. .onClick(() => {
  6546. DialogHelper.closeDialog('tips'); //关闭弹框
  6547. })
  6548. Button('跳转')
  6549. .fontColor(Color.White)//
  6550. .layoutWeight(1)
  6551. .height(50)
  6552. .backgroundColor(this.themeColor)
  6553. .stateEffect(true)
  6554. .margin({ left: 6 })
  6555. .onClick(() => {
  6556. DialogHelper.closeDialog('tips'); //关闭弹框
  6557. this.isShowPlay = false
  6558. router.pushUrl({
  6559. url: 'pages/SettingPage'
  6560. }, router.RouterMode.Single);
  6561. })
  6562. }
  6563. }
  6564. .width("100%")
  6565. .padding(10)
  6566. }
  6567. @Builder
  6568. PlayMoreSheet() {
  6569. Column() {
  6570. this.MoreList()
  6571. }
  6572. .width('100%')
  6573. .height('100%')
  6574. }
  6575. @Builder
  6576. MoreList() {
  6577. Scroll() {
  6578. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  6579. ForEach(this.moreItems, (more: MoreItem,index:number) => {
  6580. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6581. Row() {
  6582. if (more.id === 3) {
  6583. Image(more.image)
  6584. .width(24)
  6585. .height(24)
  6586. .margin({ left: 10, right: 10 })
  6587. Text(more.title)
  6588. .fontSize(16)
  6589. .fontColor(Color.White)
  6590. .bindSheet($$this.isShowDetailMore, this.detailSheet(), {
  6591. height: this.isCoverOpacity() ? '95%' : '65%',
  6592. dragBar: true,
  6593. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  6594. showClose: true,
  6595. blurStyle: BlurStyle.Thin,
  6596. backgroundColor: Color.Transparent,
  6597. title: { title: '歌曲信息' }
  6598. })
  6599. } else if (more.id === 15&&this.currentSong) { //编辑信息
  6600. Image(more.image)
  6601. .width(24)
  6602. .height(24)
  6603. .margin({ left: 10, right: 10 })
  6604. Text(more.title)
  6605. .fontSize(16)
  6606. .fontColor(Color.White)
  6607. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  6608. height: this.isCoverOpacity() ? '95%' : '93%',
  6609. dragBar: true,
  6610. showClose: true,
  6611. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  6612. // blurStyle:BlurStyle.Thin,
  6613. // backgroundColor:Color.Transparent,
  6614. title: { title: '编辑信息' }
  6615. })
  6616. } else if (more.id === 5) { //定时关闭
  6617. Image(more.image)
  6618. .width(24)
  6619. .height(24)
  6620. .margin({ left: 10, right: 10 })
  6621. Text(more.title)
  6622. .fontSize(16)
  6623. .fontColor(Color.White)
  6624. .onClick(() => {
  6625. this.doMore(more.id)
  6626. })
  6627. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  6628. height: this.isCoverOpacity() ? '95%' : '78%',
  6629. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  6630. dragBar: true,
  6631. showClose: true,
  6632. title: { title: $r('app.string.time_close') }
  6633. })
  6634. } else if (more.id === 2) { //歌词设置
  6635. Image(more.image)
  6636. .width(24)
  6637. .height(24)
  6638. .margin({ left: 10, right: 10 })
  6639. Text(more.title)
  6640. .fontSize(16)
  6641. .fontColor(Color.White)
  6642. }
  6643. else if (more.id === 16) { //悬浮歌词设置
  6644. Image(more.image)
  6645. .width(24)
  6646. .height(24)
  6647. .margin({ left: 10, right: 10 })
  6648. Text(more.title)
  6649. .fontSize(16)
  6650. .fontColor(Color.White)
  6651. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  6652. height: this.isCoverOpacity() ? '95%' : '95%',
  6653. dragBar: true,
  6654. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  6655. showClose: true,
  6656. blurStyle: BlurStyle.Thin,
  6657. backgroundColor: Color.Transparent,
  6658. title: { title: '悬浮歌词' }
  6659. })
  6660. } else if (more.id === 11) {
  6661. Image(more.image)
  6662. .width(24)
  6663. .height(24)
  6664. .margin({ left: 10, right: 10 })
  6665. Text(more.title)
  6666. .fontSize(16)
  6667. .fontColor(Color.White)
  6668. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  6669. height: this.isCoverOpacity() ? '95%' : '60%',
  6670. dragBar: true,
  6671. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  6672. showClose: true,
  6673. blurStyle: BlurStyle.Thin,
  6674. backgroundColor: Color.Transparent,
  6675. title: { title: '跳过头尾' }
  6676. })
  6677. }else if (more.id === 12) { //投播
  6678. AVCastPicker({
  6679. customPicker: (): void => this.TPImageBuilder(more),
  6680. onStateChange: (state) => {
  6681. if (state == AVCastPickerState.STATE_APPEARING) {
  6682. console.log(' The picker starts showing.');
  6683. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  6684. console.log(' The picker finishes presenting.');
  6685. }
  6686. },
  6687. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  6688. sessionType: 'video'
  6689. })
  6690. .id('AVCastPicker')
  6691. .width(46)
  6692. } else {
  6693. Image(more.image)
  6694. .width(24)
  6695. .height(24)
  6696. .margin({ left: 10, right: 10 })
  6697. .onClick(() => {
  6698. this.doMore(more.id)
  6699. })
  6700. Text(more.id==17?(this.isLandscape?'竖屏模式':'横屏模式'):more.title)
  6701. .fontSize(16)
  6702. .fontColor(Color.White)
  6703. .onClick(() => {
  6704. this.doMore(more.id)
  6705. })
  6706. Select([//倍速
  6707. { value: '0.25x' },
  6708. { value: '0.5x' },
  6709. { value: '0.75x' },
  6710. { value: '1x' },
  6711. { value: '1.25x' },
  6712. { value: '1.5x' },
  6713. { value: '1.75x' },
  6714. { value: '2x' },
  6715. { value: '3x' }])
  6716. .font({ size: 16, weight: FontWeight.Medium })
  6717. .fontColor($r('sys.color.white'))
  6718. .margin({ left: 25 })
  6719. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  6720. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  6721. .value(Utility.optimizedFormat(this.playSpeed))
  6722. .onSelect(async (_index: number, text?: string | undefined) => {
  6723. let speed = parseFloat(text?.replace('x', '') || '1');
  6724. if (!CommonConstants.video_speed_list.includes(speed)) {
  6725. speed = 1;
  6726. }
  6727. this.playSpeed = speed
  6728. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  6729. })
  6730. Slider({
  6731. value: this.volume,
  6732. min: 0,
  6733. max: 1,
  6734. step: 0.1,
  6735. style: SliderStyle.OutSet
  6736. })
  6737. .margin({ left: 18, right: 8 })
  6738. .blockColor(this.themeColor)
  6739. .trackColor($r('app.color.speed_text_color'))
  6740. .selectedColor(Color.White)
  6741. .trackThickness(9)
  6742. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  6743. .onChange((value: number) => {
  6744. this.volume = value;
  6745. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  6746. })
  6747. .layoutWeight(1)
  6748. Blank()
  6749. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  6750. .selectedColor(this.themeColor)
  6751. .switchPointColor(Color.White)
  6752. .margin({ right: 15 })
  6753. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  6754. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  6755. if (more.id == 6) {
  6756. this.isMusicMemoryPlay = checked;
  6757. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  6758. if (this.isMusicMemoryPlay) {
  6759. ToastUtil.showToast('记忆播放已开启')
  6760. } else {
  6761. ToastUtil.showToast('记忆播放已关闭')
  6762. }
  6763. }
  6764. })
  6765. .width(48)
  6766. .height(24);
  6767. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  6768. .selectedColor(this.themeColor)
  6769. .switchPointColor(Color.White)
  6770. .margin({ right: 15 })
  6771. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  6772. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  6773. if (more.id == 7) {
  6774. this.isMusicBGCover = checked;
  6775. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  6776. if (this.isMusicBGCover) {
  6777. ToastUtil.showToast('播放背景随音乐封面已开启')
  6778. } else {
  6779. ToastUtil.showToast('播放背景随音乐封面已关闭')
  6780. }
  6781. }
  6782. })
  6783. .width(48)
  6784. .height(24);
  6785. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  6786. .selectedColor(this.themeColor)
  6787. .switchPointColor(Color.White)
  6788. .margin({ right: 15 })
  6789. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  6790. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  6791. if (more.id == 8) {
  6792. this.isSavePlayMode = checked;
  6793. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  6794. if (this.isSavePlayMode) {
  6795. ToastUtil.showToast('保存播放模式已开启')
  6796. } else {
  6797. ToastUtil.showToast('保存播放模式已关闭')
  6798. }
  6799. }
  6800. })
  6801. .width(48)
  6802. .height(24);
  6803. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  6804. .selectedColor(this.themeColor)
  6805. .switchPointColor(Color.White)
  6806. .margin({ right: 15 })
  6807. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  6808. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  6809. if (more.id == 13) {
  6810. this.isCoverRectangle = checked;
  6811. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  6812. if (this.isCoverRectangle) {
  6813. ToastUtil.showToast('封面方形已开启')
  6814. this.animationRoFun()
  6815. } else {
  6816. ToastUtil.showToast('封面圆形已开启')
  6817. this.animationRoFun()
  6818. }
  6819. }
  6820. })
  6821. .width(48)
  6822. .height(24);
  6823. }
  6824. }
  6825. .width('100%')
  6826. .height(45)
  6827. .padding(15)
  6828. .backgroundColor(Color.Transparent)
  6829. .borderRadius(12)
  6830. .margin({ bottom: 6 })
  6831. }
  6832. .transition(TransitionEffect.move(TransitionEdge.BOTTOM).animation({ duration: 600, curve: Curve.Ease, delay: 60*index }))
  6833. .backgroundColor(Color.Transparent)
  6834. .onClick(() => {
  6835. this.doMore(more.id)
  6836. })
  6837. });
  6838. }
  6839. .width('100%')
  6840. .padding(16)
  6841. }.margin({ bottom: 18 })
  6842. }
  6843. @Builder
  6844. TPImageBuilder(more: MoreItem): void {
  6845. Row() {
  6846. Image($r('app.media.tuoping'))
  6847. .width(22)
  6848. .height(22)
  6849. .margin({ left: 10, right: 10 })
  6850. Text(more.title)
  6851. .fontSize(16)
  6852. .fontColor(Color.White)
  6853. }
  6854. }
  6855. private moreItems: MoreItem[] = [
  6856. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  6857. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  6858. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  6859. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  6860. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  6861. { id: 15, image: $r('app.media.rename2'), title: '编辑信息' },
  6862. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  6863. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  6864. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  6865. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  6866. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  6867. { id: 4, image: $r('app.media.share2'), title: '分享' },
  6868. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  6869. { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  6870. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  6871. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  6872. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  6873. ];
  6874. @State isShowMoreView: boolean = false;
  6875. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  6876. @State isShowTimeCloseMore: boolean = false
  6877. @State isShowDetailMore: boolean = false
  6878. @State isMusicBGCover: boolean = true
  6879. @State isSavePlayMode: boolean = true
  6880. @State isLyricSetting: boolean = false
  6881. @State isJumpSetting: boolean = false
  6882. @State isShowEdit: boolean = false
  6883. @State showPipLyric: boolean = false
  6884. async setRingTone() {
  6885. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  6886. return
  6887. }
  6888. // 确定后的逻辑
  6889. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  6890. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  6891. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  6892. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  6893. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  6894. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  6895. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  6896. , this.videoUrl, this.name).then(res => {
  6897. LogUtil.info('onecold setFlag :' + res);
  6898. });
  6899. }
  6900. doMore(moreId: number) {
  6901. switch (moreId) {
  6902. case 2: //歌词
  6903. this.isLyricSetting = !this.isLyricSetting;
  6904. this.isShowMoreView = false
  6905. break;
  6906. case 3: //详情
  6907. this.isShowDetailMore = !this.isShowDetailMore;
  6908. break;
  6909. case 4: //分享
  6910. if (this.currentSong !== undefined) {
  6911. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  6912. }
  6913. this.isShowMoreView = false
  6914. break;
  6915. case 5: //定时关闭
  6916. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  6917. break;
  6918. case 10: //设为铃声
  6919. this.setRingTone()
  6920. this.isShowMoreView = false
  6921. break;
  6922. case 11: //跳过头尾
  6923. this.isJumpSetting = !this.isJumpSetting;
  6924. break;
  6925. case 13: //倍速
  6926. break;
  6927. case 14: //搜索封面
  6928. if (this.currentSong !== undefined) {
  6929. this.doSearchCover(this.currentSong)
  6930. }
  6931. this.isShowMoreView = false
  6932. break;
  6933. case 15: //编辑信息
  6934. this.isShowEdit = !this.isShowEdit;
  6935. break;
  6936. case 16: //悬浮歌词
  6937. this.showPipLyric = !this.showPipLyric;
  6938. break;
  6939. case 17: //横屏模式
  6940. if (this.isLandscape) {
  6941. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  6942. } else {
  6943. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  6944. }
  6945. this.isShowMoreView = false
  6946. break;
  6947. }
  6948. }
  6949. /**
  6950. * 切换横竖屏
  6951. *
  6952. */
  6953. setOrientation(orientation: number) {
  6954. this.windowClass.setPreferredOrientation(orientation).then(() => {
  6955. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  6956. }).catch((err: BusinessError) => {
  6957. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  6958. });
  6959. }
  6960. /**
  6961. * 画中画功能(悬浮歌词功能)
  6962. *
  6963. */
  6964. private nodeController: TextNodeController = new TextNodeController('#000000',this.lyricControllerXF);
  6965. pipController?: PiPWindow.PiPController;
  6966. navigationId: string = '';
  6967. @State curState: string = '';
  6968. @State curError: ResourceStr = '';
  6969. @State pipBg:string = '#E8E8E8'
  6970. @State buttonAction: string = '';
  6971. //开启画中画功能
  6972. async startPip() {
  6973. this.nodeController = new TextNodeController(this.pipBg,this.lyricControllerXF);
  6974. if (!this.pipController) {
  6975. await this.createPipController();
  6976. }
  6977. if (!this.pipController) {
  6978. Logger.info(`[${TAG}] pipController create error`);
  6979. return;
  6980. }
  6981. await this.pipController.startPiP();
  6982. }
  6983. async stopPip() {
  6984. if (!this.pipController) {
  6985. Logger.info(`[${TAG}] pipController is not exist`);
  6986. return;
  6987. }
  6988. this.isOpenPip = false
  6989. await this.pipController.stopPiP();
  6990. }
  6991. async createPipController() {
  6992. this.pipController = await PiPWindow.create({
  6993. context: getContext(this),
  6994. componentController: this.xcomponentController,
  6995. navigationId: this.navigationId,
  6996. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  6997. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  6998. customUIController: this.nodeController,
  6999. });
  7000. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth',330)
  7001. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight',120)
  7002. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  7003. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  7004. this.onStateChange(state, reason);
  7005. });
  7006. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  7007. this.onActionEvent(event, status);
  7008. });
  7009. }
  7010. destroyPipController() {
  7011. if (!this.pipController) {
  7012. return;
  7013. }
  7014. this.pipController.off('stateChange');
  7015. this.pipController.off('controlPanelActionEvent');
  7016. this.pipController = undefined;
  7017. }
  7018. onStateChange(state: PiPWindow.PiPState, reason: string) {
  7019. switch (state) {
  7020. case PiPWindow.PiPState.ABOUT_TO_START:
  7021. this.curState = 'ABOUT_TO_START';
  7022. this.curError = $r('app.string.current_error_hint');
  7023. break;
  7024. case PiPWindow.PiPState.STARTED:
  7025. this.curState = 'STARTED';
  7026. this.curError = $r('app.string.current_error_hint');
  7027. break;
  7028. case PiPWindow.PiPState.ABOUT_TO_STOP:
  7029. this.curState = 'ABOUT_TO_STOP';
  7030. this.curError = $r('app.string.current_error_hint');
  7031. break;
  7032. case PiPWindow.PiPState.STOPPED:
  7033. this.curState = 'STOPPED';
  7034. this.curError = $r('app.string.current_error_hint');
  7035. this.stopPip()
  7036. this.destroyPipController()
  7037. break;
  7038. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  7039. this.curState = 'ABOUT_TO_RESTORE';
  7040. this.curError = $r('app.string.current_error_hint');
  7041. break;
  7042. case PiPWindow.PiPState.ERROR:
  7043. this.curState = 'ERROR';
  7044. this.curError = reason;
  7045. break;
  7046. default:
  7047. break;
  7048. }
  7049. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  7050. }
  7051. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  7052. LogUtil.info('onecold onActionEvent = '+ event + ' status='+status )
  7053. switch (event) {
  7054. case 'playbackStateChanged':
  7055. if (status === 0) {
  7056. this.pause();
  7057. } else {
  7058. this.startPlayOrResumePlay();
  7059. }
  7060. break;
  7061. case 'nextVideo':
  7062. // 切换到下一个视频
  7063. this.playNext()
  7064. break;
  7065. case 'previousVideo':
  7066. // 切换到上一个视频
  7067. this.playPrevious()
  7068. break;
  7069. case 'previousVideo':
  7070. // 切换到上一个视频
  7071. this.playPrevious()
  7072. break;
  7073. default:
  7074. }
  7075. this.buttonAction = event + `-status:${status}`;
  7076. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  7077. }
  7078. /**
  7079. * 画中画功能(悬浮歌词功能)结束
  7080. *
  7081. */
  7082. doSearchCover(item:VideoItem){
  7083. if(PreferencesUtil.getStringSync('COVER_API','')===''){
  7084. this.isShowMoreView = false
  7085. this.showTipsDialog()
  7086. return
  7087. }
  7088. if (item !== undefined) {
  7089. let artist = item?.artist
  7090. if (StrUtil.isEmpty(artist) || artist === undefined) {
  7091. artist = ''
  7092. }
  7093. this.searchCover(item,item.name, artist)
  7094. }
  7095. }
  7096. searchCover(item:VideoItem,title: string, artist: string) {
  7097. NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API','')).then(async (res) => {
  7098. LogUtil.debug("onecold res =" + res)
  7099. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  7100. if(item.filePath==this.currentSong?.filePath){
  7101. this.cover = res
  7102. if (this.currentSong) {
  7103. this.currentSong.pixelMapPath = res
  7104. }
  7105. }
  7106. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  7107. if (success) {
  7108. this.doUpdateData()
  7109. console.log(" onecold 更新音乐封面成功,数据库已同步");
  7110. } else {
  7111. console.error(" onecold 更新音乐封面数据库失败原因: " + error);
  7112. }
  7113. });
  7114. LogUtil.debug("onecold this.cover =" + this.cover)
  7115. }
  7116. })
  7117. }
  7118. @State jumpTopTime: number = 0
  7119. @State jumpEndTime: number = 0
  7120. @State isOpenJump: boolean = false
  7121. @Builder
  7122. JumpTopEndSheet() {
  7123. Scroll() {
  7124. Column() {
  7125. Column() {
  7126. Text('仅对本播放列表有效')
  7127. .fontSize(16)
  7128. .fontColor($r('app.color.text_color'))
  7129. // 跳过头尾
  7130. Column() {
  7131. Row() {
  7132. Text('跳过片头:')
  7133. .fontSize(16)
  7134. .fontColor($r('app.color.text_color'))
  7135. Text(this.jumpTopTime + 's')
  7136. .fontSize(16)
  7137. .fontColor($r('app.color.text_color'))
  7138. }
  7139. .margin({ bottom: 5 })
  7140. Row() {
  7141. Slider({
  7142. value: this.jumpTopTime,
  7143. min: 0,
  7144. max: 120,
  7145. step: 1,
  7146. style: SliderStyle.OutSet
  7147. })
  7148. .blockColor(this.themeColor)
  7149. .trackColor($r('app.color.speed_text_color'))
  7150. .selectedColor(Color.White)
  7151. .trackThickness(8)
  7152. .onChange((value: number) => {
  7153. this.jumpTopTime = value;
  7154. })
  7155. .width('85%')
  7156. }
  7157. .alignItems(VerticalAlign.Top)
  7158. }
  7159. .margin({ top: 10, bottom: 10 })
  7160. // 跳过头尾
  7161. Column() {
  7162. Row() {
  7163. Text('跳过片尾:')
  7164. .fontSize(16)
  7165. .fontColor($r('app.color.text_color'))
  7166. Text(this.jumpEndTime + 's')
  7167. .fontSize(16)
  7168. .fontColor($r('app.color.text_color'))
  7169. }
  7170. .margin({ bottom: 5 })
  7171. Row() {
  7172. Slider({
  7173. value: this.jumpEndTime,
  7174. min: 0,
  7175. max: 120,
  7176. step: 1,
  7177. style: SliderStyle.OutSet
  7178. })
  7179. .blockColor(this.themeColor)
  7180. .trackColor($r('app.color.speed_text_color'))
  7181. .selectedColor(Color.White)
  7182. .trackThickness(8)
  7183. .onChange((value: number) => {
  7184. this.jumpEndTime = value;
  7185. })
  7186. .width('85%')
  7187. }
  7188. .alignItems(VerticalAlign.Top)
  7189. }
  7190. .margin({ top: 10, bottom: 10 })
  7191. Row() {
  7192. Button('保存设置')
  7193. .fontColor(Color.White)
  7194. .layoutWeight(1)
  7195. .height(40)
  7196. .width(80)
  7197. .backgroundColor(this.themeColor)
  7198. .stateEffect(true)
  7199. .margin({ left: 0, bottom: 20 })
  7200. .onClick(async () => {
  7201. if (!Utility.isNoble()) {
  7202. this.isJumpSetting = false
  7203. this.isShowMoreView = false
  7204. this.showVipDialog()
  7205. return
  7206. }
  7207. if (this.currentSong === undefined) {
  7208. return
  7209. }
  7210. if (this.modeType === 0) {
  7211. let parentPath = FileUtil.getParentPath(this.videoUrl)
  7212. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  7213. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  7214. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  7215. } else if (this.modeType === 1) { //媒体库
  7216. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  7217. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  7218. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  7219. } else if (this.modeType === 2) { //艺术家
  7220. if (this.currentSong?.artist) {
  7221. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  7222. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  7223. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  7224. }
  7225. } else if (this.modeType === 3) { //专辑
  7226. if (this.currentSong?.album) {
  7227. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  7228. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  7229. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  7230. }
  7231. }
  7232. ToastUtil.showShort("保存成功")
  7233. this.isJumpSetting = false
  7234. })
  7235. }
  7236. .margin({
  7237. left: 38,
  7238. right: 38,
  7239. top: 10,
  7240. bottom: 10
  7241. })
  7242. .width(120)
  7243. .height(50)
  7244. }
  7245. }
  7246. }
  7247. .width('100%')
  7248. .height('100%')
  7249. }
  7250. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  7251. private onStateVastChange(state: AVCastPickerState) {
  7252. if (state == AVCastPickerState.STATE_APPEARING) {
  7253. console.log('The picker starts showing.');
  7254. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  7255. console.log('The picker finishes presenting.');
  7256. }
  7257. }
  7258. private showSelectLyric() {
  7259. DialogHelper.showActionSheetDialog({
  7260. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  7261. // sheets: ["本地歌词", "搜索歌词"],
  7262. sheets:[
  7263. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  7264. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  7265. ],
  7266. maskColor: Color.Transparent,
  7267. backgroundColor: $r('app.color.bg_card'),
  7268. transition: AnimationHelper.transitionInDown(666),
  7269. onAction: (index) => {
  7270. switch (index) {
  7271. case 0:
  7272. this.callFilePickerSelectFileForLyric()
  7273. break;
  7274. case 1:
  7275. if (StrUtil.isNotEmpty(this.videoUrl)) {
  7276. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  7277. this.initLyric(lyricPath);
  7278. }
  7279. break;
  7280. }
  7281. }
  7282. })
  7283. }
  7284. // 拉起picker选择文件管理器
  7285. async callFilePickerSelectFileForLyric(): Promise<void> {
  7286. try {
  7287. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  7288. DocumentSelectOptions.maxSelectNumber = 1
  7289. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  7290. let documentPicker = new picker.DocumentViewPicker();
  7291. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  7292. Logger.info(TAG,
  7293. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  7294. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  7295. this.saveVideoDatasLyric(DocumentSelectResult)
  7296. }
  7297. }).catch((err: BusinessError) => {
  7298. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  7299. });
  7300. } catch (err) {
  7301. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  7302. }
  7303. }
  7304. async saveVideoDatasLyric(uris: string[]) {
  7305. if (ArrayUtil.isEmpty(uris)) {
  7306. return
  7307. }
  7308. let newUris: string[] = [];
  7309. for (let i = 0; i < uris.length; i++) {
  7310. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  7311. Logger.info(TAG, 'filePath uri: ' + filePath);
  7312. newUris.push(filePath)
  7313. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  7314. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  7315. fileIo.copyFileSync(file.fd, file2.fd)
  7316. fileIo.closeSync(file);
  7317. fileIo.closeSync(file2);
  7318. this.initLyric(filePath)
  7319. }
  7320. }
  7321. private initDelayPlay(context: object) {
  7322. this.mContext = context;
  7323. }
  7324. startPipLyric(){
  7325. if(this.pipController)
  7326. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE, PiPWindow.PiPControlStatus.PLAY);
  7327. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip',false)
  7328. if(this.isOpenPip){
  7329. this.startPip()
  7330. }else{
  7331. this.stopPip()
  7332. }
  7333. }
  7334. private startPlayOrResumePlay() {
  7335. this.startPipLyric()
  7336. this.mDestroyPage = false;
  7337. this.animationState = AnimationStatus.Running
  7338. LogUtils.getInstance().LOGI("startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  7339. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  7340. this.stopProgressTask();
  7341. this.startProgressTask();
  7342. this.play(this.videoUrl.toString());
  7343. }
  7344. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  7345. this.mIjkMediaPlayer.start();
  7346. this.setProgress()
  7347. this.CONTROL_PlayStatus = PlayStatus.PLAY
  7348. }
  7349. this.setIsPlaying(true)
  7350. this.updateSessionPlayState(true)
  7351. this.watchStatus();
  7352. this.updateLastPlayTimeStr(this.videoUrl)
  7353. }
  7354. updateLastPlayTimeStr(filePath:string){
  7355. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  7356. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  7357. if (success) {
  7358. this.getHistoryList(false)
  7359. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  7360. } else {
  7361. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  7362. }
  7363. });
  7364. }
  7365. private completionNum(num: number): string | number {
  7366. if (num < 10) {
  7367. return '0' + num;
  7368. } else {
  7369. return num;
  7370. }
  7371. }
  7372. private stringForTime(timeMs: number): string {
  7373. let totalSeconds: number | string = (timeMs / 1000);
  7374. let newSeconds: number | string = totalSeconds % 60;
  7375. let minutes: number | string = (totalSeconds / 60) % 60;
  7376. let hours: number | string = totalSeconds / 3600;
  7377. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  7378. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  7379. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  7380. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  7381. if (this.isCurrentTime) {
  7382. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  7383. this.oldSeconds = newSeconds
  7384. } else {
  7385. newSeconds = this.oldSeconds
  7386. }
  7387. }
  7388. newSeconds = this.completionNum(newSeconds);
  7389. if (hours > 0) {
  7390. return hours + ":" + minutes + ":" + newSeconds;
  7391. } else {
  7392. return minutes + ":" + newSeconds;
  7393. }
  7394. }
  7395. private setProgress() {
  7396. let position = this.mIjkMediaPlayer.getCurrentPosition();
  7397. let duration = this.mIjkMediaPlayer.getDuration();
  7398. let pos = 0;
  7399. if (duration > 0) {
  7400. this.slideEnable = true;
  7401. let curPercent = position / duration;
  7402. pos = curPercent * 100;
  7403. if (pos > this.PROGRESS_MAX_VALUE) {
  7404. this.progressValue = this.PROGRESS_MAX_VALUE
  7405. } else {
  7406. this.progressValue = pos;
  7407. }
  7408. }
  7409. // LogUtils.getInstance()
  7410. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  7411. this.totalTime = this.stringForTime(duration);
  7412. if (position > duration) {
  7413. position = duration;
  7414. }
  7415. this.isCurrentTime = true;
  7416. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  7417. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  7418. this.currentTime = this.stringForTime(position);
  7419. this.isCurrentTime = false
  7420. if (this.mIjkMediaPlayer.isPlaying()) {
  7421. this.randomColor =
  7422. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  7423. // 判断是否播放到结束时间
  7424. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  7425. if (position >= duration - this.jumpEndTime * 1000) {
  7426. this.playNext()
  7427. }
  7428. }
  7429. } else {
  7430. this.randomColor = 'rbg(0,0,0)'
  7431. }
  7432. }
  7433. private startProgressTask() {
  7434. let that = this;
  7435. this.updateProgressTimer = setInterval(() => {
  7436. //LogUtils.getInstance().LOGI("startProgressTask");
  7437. if (!that.mDestroyPage) {
  7438. that.setProgress();
  7439. }
  7440. }, 300);
  7441. }
  7442. private stopProgressTask() {
  7443. LogUtils.getInstance().LOGI("stopProgressTask");
  7444. clearInterval(this.updateProgressTimer);
  7445. }
  7446. private showLoadIng() {
  7447. this.loadingVisible = Visibility.Visible;
  7448. this.replayVisible = Visibility.None;
  7449. }
  7450. private hideLoadIng() {
  7451. this.loadingVisible = Visibility.None;
  7452. this.replayVisible = Visibility.None;
  7453. }
  7454. private showRePlay() {
  7455. this.loadingVisible = Visibility.None;
  7456. this.replayVisible = Visibility.Visible;
  7457. }
  7458. private async play(url: string) {
  7459. let that = this;
  7460. that.showLoadIng();
  7461. //设置XComponent回调的context
  7462. if (!!this.mContext) {
  7463. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  7464. }
  7465. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  7466. this.mIjkMediaPlayer.reset();
  7467. }
  7468. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  7469. //设置debug模式
  7470. this.mIjkMediaPlayer.setDebug(false);
  7471. //初始化配置
  7472. this.mIjkMediaPlayer.native_setup();
  7473. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0
  7474. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  7475. //设置视频源
  7476. this.mIjkMediaPlayer.setDataSource(url);
  7477. //设置视频源http请求头
  7478. let headers = new Map([
  7479. ["user_agent", "Mozilla/5.0 BiliDroid/7.30.0 (bbcallen@gmail.com)"],
  7480. ["referer", "https://www.bilibili.com"]
  7481. ]);
  7482. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  7483. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  7484. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  7485. // }
  7486. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  7487. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  7488. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  7489. const fileSize = await this.getFileSize(this.videoUrl);
  7490. let bufferSize = 1 * 1024 * 1024; // 默认缓冲区大小为2MB
  7491. if (fileSize > 3 * 1024 * 1024 * 1024) { // 文件大于3GB
  7492. bufferSize = 25 * 1024 * 1024; // 设置缓冲区大小为25MB
  7493. }
  7494. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  7495. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  7496. //停止预读的最小帧数
  7497. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  7498. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  7499. // 设置其他缓冲相关选项
  7500. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  7501. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  7502. //启动预加载
  7503. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  7504. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  7505. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  7506. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  7507. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  7508. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  7509. // 因此需要播放器丢包,才不会累积延时
  7510. // 这个和第三个参数packet-buffering无关。
  7511. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  7512. // 无限制收流
  7513. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  7514. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  7515. // 屏幕常亮
  7516. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  7517. // 设置超时
  7518. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  7519. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  7520. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  7521. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  7522. // 变速播放
  7523. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  7524. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  7525. let Speed = this.mIjkMediaPlayer.getSpeed()
  7526. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  7527. //是否开启循环播放
  7528. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  7529. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  7530. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  7531. if (height === 0) {
  7532. return;
  7533. }
  7534. const va = width / height;
  7535. const vpa = that.videoParentAspectRatio;
  7536. if (vpa > va) {
  7537. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  7538. } else {
  7539. that.videoWidth = '100%';
  7540. }
  7541. if (width && height) {
  7542. that.videoAspectRatio = width / height;
  7543. }
  7544. LogUtils.getInstance()
  7545. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  7546. that.hideLoadIng();
  7547. }
  7548. }
  7549. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  7550. let mOnPreparedListener: OnPreparedListener = {
  7551. onPrepared: async () => {
  7552. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  7553. try {
  7554. // this.cover = this.songList[this.curIndex].pixelMapPath
  7555. // this.artist = this.songList[this.curIndex].artist
  7556. // this.videoUrl = this.songList[this.curIndex].filePath
  7557. let isBgCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  7558. if (isBgCover && this.cover !== undefined && StrUtil.isNotEmpty(this.cover)) {
  7559. this.setImageColor2(this.cover)
  7560. } else {
  7561. this.getImageColor();
  7562. }
  7563. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  7564. await this.initLyric(lyricPath);
  7565. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  7566. this.avSessionController.initAvSession(false);
  7567. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  7568. this.setAvSessionListener();
  7569. this.updateSessionPlayState(true)
  7570. this.setCurrentPlayMode()
  7571. }, 500)
  7572. let timeoutPlay = 0
  7573. if (StrUtil.isNotEmpty(this.videoUrl) &&
  7574. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  7575. timeoutPlay = 1000
  7576. }
  7577. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  7578. if (this.modeType === 0) { //文件夹
  7579. let parentPath = FileUtil.getParentPath(this.videoUrl)
  7580. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  7581. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  7582. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  7583. } else if (this.modeType === 1) { //媒体库
  7584. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  7585. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  7586. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  7587. } else if (this.modeType === 2) { //艺术家
  7588. if (this.currentSong?.artist) {
  7589. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  7590. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  7591. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  7592. }
  7593. } else if (this.modeType === 3) { //专辑
  7594. if (this.currentSong?.album) {
  7595. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  7596. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  7597. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  7598. }
  7599. }
  7600. this.duration = this.mIjkMediaPlayer.getDuration()
  7601. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  7602. if (this.mIjkMediaPlayer != null) {
  7603. if (this.jumpTopTime * 1000 <= this.duration) {
  7604. // 调用 seekTo 方法,跳到指定时间
  7605. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  7606. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  7607. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  7608. }
  7609. }, timeoutPlay)
  7610. } else {
  7611. // 提示用户无法跳过
  7612. ToastUtil.showToast('跳过时间超过视频时长');
  7613. }
  7614. }
  7615. } else {
  7616. this.jumpTopTime = 0
  7617. this.jumpEndTime = 0
  7618. console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  7619. console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  7620. console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' + PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  7621. //记忆播放(每一首都会记忆播放)
  7622. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  7623. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  7624. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  7625. this.restorePlaybackPosition() //读取播放记忆功能
  7626. }else if(this.isMemoryLastPlay&&this.isFirstStartPlay){
  7627. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  7628. this.restorePlaybackPosition() //读取播放记忆功能
  7629. }
  7630. this.isFirstStartPlay = false
  7631. }, timeoutPlay)
  7632. }else{
  7633. this.isFirstStartPlay = false
  7634. }
  7635. }
  7636. this.saveLastPlayList()
  7637. } catch (error) {
  7638. let err: BusinessError = error as BusinessError;
  7639. console.error('onecold failed with err: ' + JSON.stringify(err));
  7640. }
  7641. }
  7642. }
  7643. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  7644. let mOnTimedTextListener: OnTimedTextListener = {
  7645. onTimedText: () => {
  7646. }
  7647. }
  7648. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  7649. let mOnCompletionListener: OnCompletionListener = {
  7650. onCompletion: () => {
  7651. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  7652. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  7653. this.playNext()
  7654. } else if (this.playType == 1) { //1:单片重复播放
  7655. this.CONTROL_PlayStatus = PlayStatus.INIT
  7656. that.startPlayOrResumePlay();
  7657. } else if (this.playType == 2) { //2:正常播放,单曲播完
  7658. that.showRePlay();
  7659. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  7660. that.progressValue = this.PROGRESS_MAX_VALUE;
  7661. that.slideEnable = false;
  7662. that.stop();
  7663. // ToastUtil.showToast('开始重新播放')
  7664. } else if (this.playType == 3) { //3:随机播放
  7665. this.randomPlay()
  7666. }
  7667. }
  7668. }
  7669. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  7670. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  7671. onBufferingUpdate: (percent: number) => {
  7672. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  7673. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  7674. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  7675. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  7676. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  7677. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  7678. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  7679. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  7680. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  7681. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  7682. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  7683. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  7684. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  7685. let Looping = this.mIjkMediaPlayer.isLooping()
  7686. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  7687. }
  7688. }
  7689. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  7690. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  7691. onSeekComplete: () => {
  7692. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  7693. that.startPlayOrResumePlay();
  7694. }
  7695. }
  7696. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  7697. let mOnInfoListener: OnInfoListener = {
  7698. onInfo: (what: number, extra: number) => {
  7699. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  7700. that.hideLoadIng();
  7701. }
  7702. }
  7703. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  7704. let mOnErrorListener: OnErrorListener = {
  7705. onError: (what: number, extra: number) => {
  7706. this.stopProgressTask();
  7707. LogUtils.getInstance().LOGI("OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  7708. that.hideLoadIng();
  7709. if (StrUtil.isNotEmpty(this.videoUrl) && !FileUtil.accessSync(this.videoUrl)) {
  7710. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  7711. } else {
  7712. ToastUtil.showToast(getContext()
  7713. .resourceManager
  7714. .getStringByNameSync("Honey_the_video_is_playing_errant_The_system_is_wandering"))
  7715. }
  7716. }
  7717. }
  7718. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  7719. this.mIjkMediaPlayer.setMessageListener();
  7720. this.mIjkMediaPlayer.prepareAsync();
  7721. this.mIjkMediaPlayer.start();
  7722. }
  7723. //保存最后播放的那首歌和已经对应的播放列表
  7724. saveLastPlayList() {
  7725. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  7726. PreferencesUtil.putSync('LastMusicList', this.songList)
  7727. }
  7728. // 清空播放记录
  7729. clearVideoHistory() {
  7730. this.table.clearPlayHistory( (success: boolean, error?: string) => {
  7731. if (success) {
  7732. this.historyList = [];
  7733. this.updateListData(this.historyList)
  7734. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  7735. ToastUtil.showToast('清空播放记录成功')
  7736. } else {
  7737. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  7738. }
  7739. });
  7740. }
  7741. public async setAvSessionListener() {
  7742. if (!this.avSessionController) {
  7743. return;
  7744. }
  7745. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  7746. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  7747. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  7748. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  7749. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  7750. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  7751. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  7752. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  7753. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  7754. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  7755. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  7756. }
  7757. setLoopMode() {
  7758. let itype = this.playType + 1
  7759. if (itype >= 4) {
  7760. this.playType = 0
  7761. ToastUtil.showToast('连续播放')
  7762. } else if (itype === 1) {
  7763. this.playType = 1
  7764. ToastUtil.showToast('单曲循环')
  7765. } else if (itype === 2) {
  7766. this.playType = 2
  7767. ToastUtil.showToast('单曲播完')
  7768. } else if (itype === 3) {
  7769. this.playType = 3
  7770. ToastUtil.showToast('随机播放')
  7771. } else if (itype === 0) {
  7772. this.playType = 0
  7773. ToastUtil.showToast('连续播放')
  7774. }
  7775. PreferencesUtil.putSync('musicPlayType', this.playType)
  7776. this.setCurrentPlayMode()
  7777. }
  7778. private sessionSetLoopModeCallback = (mode: number) => {
  7779. if (this.mIjkMediaPlayer != null) {
  7780. ToastUtil.showToast('当前播放模式:' + mode)
  7781. Logger.info('onecold 当前播放模式= ' + mode)
  7782. let hmPlayMode = mode + 1
  7783. if (hmPlayMode >= 4) {
  7784. hmPlayMode = 0
  7785. }
  7786. if (hmPlayMode === 1) {
  7787. this.playType = 1
  7788. ToastUtil.showToast('单曲循环')
  7789. } else if (hmPlayMode === 0) {
  7790. this.playType = 2
  7791. ToastUtil.showToast('单曲播完')
  7792. } else if (hmPlayMode === 3) {
  7793. this.playType = 3
  7794. ToastUtil.showToast('随机播放')
  7795. } else if (hmPlayMode === 2) {
  7796. this.playType = 0
  7797. ToastUtil.showToast('连续播放')
  7798. }
  7799. PreferencesUtil.putSync('musicPlayType', this.playType)
  7800. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  7801. let playBackState: avSession.AVPlaybackState = {
  7802. loopMode: hmPlayMode,
  7803. };
  7804. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  7805. console.info(`set setLoopMode AVPlaybackState successfully`);
  7806. }).catch((err: BusinessError) => {
  7807. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  7808. });
  7809. }
  7810. }
  7811. setCurrentPlayMode() {
  7812. if (!this.avSessionController) {
  7813. return;
  7814. }
  7815. let mLoopMode = 0
  7816. switch (this.playType) {
  7817. case 0:
  7818. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  7819. break;
  7820. case 1:
  7821. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  7822. break;
  7823. case 2:
  7824. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  7825. break;
  7826. case 3:
  7827. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  7828. break;
  7829. }
  7830. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  7831. let playBState: avSession.AVPlaybackState = {
  7832. loopMode: mLoopMode,
  7833. isFavorite:Utility.getIsFav(this.favList,this.currentSong),
  7834. };
  7835. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  7836. console.info(`set setLoopMode AVPlaybackState successfully`);
  7837. }).catch((err: BusinessError) => {
  7838. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  7839. });
  7840. }
  7841. private sessionToggleFavoriteCallback = (assetId: string) => {
  7842. if (this.mIjkMediaPlayer != null && this.currentSong) {
  7843. console.info(`on toggleFavorite `);
  7844. // 应用收到收藏命令,进行收藏处理。
  7845. this.isFac = Utility.getIsFav(this.favList,this.currentSong)
  7846. this.doFav(this.currentSong)
  7847. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  7848. let playbackState: avSession.AVPlaybackState = {
  7849. isFavorite:!this.isFac,
  7850. };
  7851. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  7852. console.info(`SetAVPlaybackState successfully`);
  7853. }).catch((err: BusinessError) => {
  7854. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  7855. });
  7856. }
  7857. }
  7858. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  7859. device: avSession.OutputDeviceInfo) => {
  7860. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  7861. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  7862. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  7863. await this.startCasting();
  7864. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  7865. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  7866. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  7867. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  7868. if (device) {
  7869. this.endCasting();
  7870. }
  7871. }
  7872. };
  7873. private async startCasting() {
  7874. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  7875. this.setPlaybackStateChangeListener();
  7876. this.pause();
  7877. this.initQueueItem();
  7878. this.prepare();
  7879. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  7880. refToIsCasting?.set(true);
  7881. this.castSeek = true;
  7882. this.isCastPlaying = true;
  7883. }
  7884. async changeCasting() {
  7885. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  7886. this.initQueueItem();
  7887. this.prepare();
  7888. this.setPlaybackStateChangeListener();
  7889. this.isCastPlaying = true;
  7890. this.castSeek = true;
  7891. }
  7892. public endCasting() {
  7893. this.avSessionController.getAvSession()?.stopCasting();
  7894. this.stopCast();
  7895. this.isCastPlaying = false;
  7896. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  7897. refToIsCasting?.set(false);
  7898. this.pause();
  7899. this.setIsPlaying(false);
  7900. // if (this.curIndex === this.curSource.index) {
  7901. // this.play
  7902. // this.seek(this.currentTime * 1000);
  7903. // this.setIsPlaying(true);
  7904. // } else {
  7905. // this.pauseVideo();
  7906. // this.setIsPlaying(false);
  7907. // }
  7908. }
  7909. public setIsPlaying(isPlayer: boolean) {
  7910. this.isPlaying = isPlayer;
  7911. }
  7912. private setPlaybackStateChangeListener(): void {
  7913. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  7914. this.castController?.on('endOfStream', this.reloadCasting);
  7915. this.castController?.on('playNext', this.playNextCallback);
  7916. this.castController?.on('playPrevious', this.playPreviousCallback);
  7917. }
  7918. private updateSessionPlayState(isPlay: boolean): void {
  7919. // if(!this.isBgPlayOpen)
  7920. // return
  7921. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  7922. this.setAVSessionPlayState({
  7923. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  7924. position: {
  7925. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  7926. updateTime: new Date().getTime()
  7927. }
  7928. });
  7929. }
  7930. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  7931. this.avSessionController.setAvSessionPlayState(playbackState)
  7932. }
  7933. private positionChange(position: number) {
  7934. this.currentTime2 = position / 1000;
  7935. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  7936. }
  7937. private playDurationChange(duration: number) {
  7938. this.duration = duration;
  7939. this.durationTime = Math.floor(this.duration / 1000);
  7940. this.durationStringTime = secondToTime((this.durationTime));
  7941. }
  7942. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  7943. const duration = playbackState?.extras?.duration;
  7944. if (typeof duration === 'number') {
  7945. this.playDurationChange(duration as number);
  7946. }
  7947. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  7948. this.positionChange(playbackState?.position?.elapsedTime);
  7949. }
  7950. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  7951. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  7952. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  7953. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  7954. this.isCastPlaying = false;
  7955. }
  7956. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  7957. this.isCastPlaying = true;
  7958. }
  7959. };
  7960. private reloadCasting = async () => {
  7961. let item = this.songList[this.curIndex];
  7962. let uri = fileUri.getUriFromPath(item.filePath);
  7963. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  7964. // description.startPosition = 0;
  7965. this.castItem = {
  7966. itemId: this.curIndex,
  7967. description: {
  7968. assetId: item.filePath,
  7969. title: item.name,
  7970. artist: '',
  7971. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  7972. // mediaUri: item.filePath,
  7973. fdSrc: {
  7974. fd: file.fd
  7975. },
  7976. // 该字段大写,音频'AUDIO',视频'VIDEO'
  7977. mediaType: 'VIDEO',
  7978. mediaSize: item.videoSize,
  7979. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  7980. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  7981. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  7982. duration: this.duration,
  7983. // albumCoverUri: 'https://www.example.jpeg',
  7984. // albumTitle: '《ExampleAlbum》',
  7985. appName: this.appName,
  7986. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  7987. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  7988. }
  7989. };
  7990. this.prepare();
  7991. this.isCastPlaying = true;
  7992. };
  7993. public playNextCallback = (): void => {
  7994. this.playNext()
  7995. };
  7996. public playPreviousCallback = (): void => {
  7997. this.playPrevious()
  7998. };
  7999. async prepare() {
  8000. await this.castController?.prepare(this.castItem);
  8001. await this.castController?.start(this.castItem);
  8002. }
  8003. public initQueueItem() {
  8004. let item = this.songList[this.curIndex];
  8005. let time = this.currentTime;
  8006. let uri = fileUri.getUriFromPath(item.filePath);
  8007. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  8008. this.castItem = {
  8009. itemId: this.curIndex,
  8010. description: {
  8011. assetId: item.filePath,
  8012. title: item.name,
  8013. artist: '',
  8014. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  8015. fdSrc: {
  8016. fd: file.fd
  8017. },
  8018. // 该字段大写,音频'AUDIO',视频'VIDEO'
  8019. mediaType: 'AUDIO',
  8020. mediaSize: item.videoSize,
  8021. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  8022. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  8023. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  8024. duration: this.duration,
  8025. // albumCoverUri: 'https://www.example.jpeg',
  8026. // albumTitle: '《ExampleAlbum》',
  8027. appName: this.appName,
  8028. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  8029. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  8030. }
  8031. };
  8032. }
  8033. async stopCast() {
  8034. try {
  8035. this.castController?.off('playbackStateChange');
  8036. this.castController?.off('endOfStream');
  8037. this.castController?.off('playNext');
  8038. this.castController?.off('playPrevious');
  8039. this.castController?.off('error');
  8040. } catch (error) {
  8041. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  8042. }
  8043. }
  8044. private sessionPlayCallback = (): void => {
  8045. this.playOrPause()
  8046. };
  8047. private sessionPauseCallback = (): void => {
  8048. this.playOrPause()
  8049. };
  8050. private playOrPause() {
  8051. if (!this.debounce()) {
  8052. return;
  8053. }
  8054. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8055. this.pause();
  8056. } else {
  8057. this.startPlayOrResumePlay();
  8058. this.playChange()
  8059. }
  8060. }
  8061. private sessionPlayNextCallback = (): void => {
  8062. this.playNext()
  8063. };
  8064. private sessionPlayPreviousCallback = (): void => {
  8065. this.playPrevious()
  8066. };
  8067. private sessionStopCallback = (): void => {
  8068. this.stop()
  8069. };
  8070. private sessionFastForwardCallback = (time?: number) => {
  8071. if (!time) {
  8072. return;
  8073. }
  8074. if (this.mIjkMediaPlayer != null) {
  8075. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  8076. let seeTime = curPosition + time * 1000;
  8077. // 限制 seekValue 在合法范围内
  8078. if (seeTime < 0) {
  8079. seeTime = 0;
  8080. } else if (seeTime > this.duration) {
  8081. seeTime = this.duration;
  8082. }
  8083. Logger.info('onecold seeTime= ' + seeTime)
  8084. this.setSeekToActionProgress(seeTime)
  8085. this.seekTo(seeTime + "")
  8086. }
  8087. };
  8088. /**
  8089. * Gesture method onActionUpdate.
  8090. *
  8091. * @param event Gesture event.手势拖动设置快进和后退
  8092. */
  8093. private setSeekToActionProgress(position: number) {
  8094. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  8095. let duration = this.mIjkMediaPlayer.getDuration();
  8096. let pos = 0;
  8097. if (duration > 0) {
  8098. this.slideEnable = true;
  8099. let curPercent = position / duration;
  8100. pos = curPercent * 100;
  8101. if (pos > this.PROGRESS_MAX_VALUE) {
  8102. this.progressValue = this.PROGRESS_MAX_VALUE
  8103. } else {
  8104. this.progressValue = pos;
  8105. }
  8106. }
  8107. // LogUtils.getInstance()
  8108. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  8109. this.totalTime = this.stringForTime(duration);
  8110. if (position > duration) {
  8111. position = duration;
  8112. }
  8113. this.isCurrentTime = true;
  8114. this.currentTime = this.stringForTime(position);
  8115. this.isCurrentTime = false
  8116. }
  8117. private sessionRewindCallback = (time?: number) => {
  8118. if (!time) {
  8119. return;
  8120. }
  8121. if (this.mIjkMediaPlayer != null) {
  8122. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  8123. let seeTime = curPosition - time * 1000;
  8124. // 限制 seekValue 在合法范围内
  8125. if (seeTime < 0) {
  8126. seeTime = 0;
  8127. } else if (seeTime > this.duration) {
  8128. seeTime = this.duration;
  8129. }
  8130. Logger.info('onecold seeTime= ' + seeTime)
  8131. this.setSeekToActionProgress(seeTime)
  8132. this.seekTo(seeTime + "")
  8133. }
  8134. };
  8135. private sessionSeekCallback = (seekTime: number) => {
  8136. if (this.mIjkMediaPlayer != null) {
  8137. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  8138. this.seekTo(seekTime + "")
  8139. }
  8140. };
  8141. private async getFileSize(filePath: string): Promise<number> {
  8142. try {
  8143. const stat = await fs.stat(filePath);
  8144. return stat.size;
  8145. } catch (err) {
  8146. console.error('Failed to get file size: ' + err.message);
  8147. return 0;
  8148. }
  8149. }
  8150. private pause() {
  8151. if (this.mIjkMediaPlayer.isPlaying()) {
  8152. this.savePlaybackPosition();
  8153. this.mIjkMediaPlayer.pause();
  8154. this.setProgress();
  8155. this.mDestroyPage = true;
  8156. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  8157. this.updateSessionPlayState(false)
  8158. this.playChange()
  8159. if(this.pipController)
  8160. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE, PiPWindow.PiPControlStatus.PAUSE);
  8161. }
  8162. }
  8163. private stop() {
  8164. this.savePlaybackPosition();
  8165. this.CONTROL_PlayStatus = PlayStatus.INIT;
  8166. this.mIjkMediaPlayer.stop();
  8167. this.mIjkMediaPlayer.release();
  8168. this.stopProgressTask();
  8169. this.updateSessionPlayState(false)
  8170. this.playChange()
  8171. this.watchStatus();
  8172. }
  8173. //保持记忆播放功能
  8174. private savePlaybackPosition() {
  8175. if (this.mIjkMediaPlayer != null) {
  8176. const position = this.mIjkMediaPlayer.getCurrentPosition();
  8177. // ToastUtil.showToast('保存记忆播放 = ' + position)
  8178. const duration = this.mIjkMediaPlayer.getDuration();
  8179. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  8180. // 如果播放位置接近视频末尾,则保存 position 为 0
  8181. const playbackPosition = (duration - position < threshold) ? 0 : position;
  8182. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  8183. }
  8184. }
  8185. //获取记忆播放功能
  8186. private restorePlaybackPosition() {
  8187. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  8188. // ToastUtil.showToast('position = ' + position)
  8189. if (this.mIjkMediaPlayer != null && position > 0) {
  8190. // ToastUtil.showToast('seekTo = ' + position)
  8191. this.seekTo(position + "");
  8192. }
  8193. }
  8194. private seekTo(value: string) {
  8195. // this.stopProgressTask();
  8196. // if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  8197. // ToastUtil.showToast('wma格式不支持拖动快进。')
  8198. // return
  8199. // }
  8200. this.mIjkMediaPlayer.seekTo(value);
  8201. // this.startPlayOrResumePlay()
  8202. // 在这里恢复计时器状态
  8203. this.setProgress()
  8204. // this.startProgressTask();
  8205. }
  8206. // 添加到下一首播放
  8207. private addToNextPlay(song: VideoItem) {
  8208. if (!this.debounce()) {
  8209. return;
  8210. }
  8211. if (this.currentSong) {
  8212. if (this.currentSong === song) {
  8213. ToastUtil.showToast('当前已经在播放这首歌了!')
  8214. return
  8215. }
  8216. }
  8217. // 如果未开始播放或队列为空
  8218. if (this.curIndex === -1 || this.songList.length === 0) {
  8219. this.songList = [song];
  8220. this.curIndex = 0;
  8221. this.doPlay(song)
  8222. return;
  8223. }
  8224. // 插入到当前索引+1的位置
  8225. const insertPos = this.curIndex + 1;
  8226. this.songList.splice(insertPos, 0, song);
  8227. this.songList = [...this.songList]; // 触发状态更新
  8228. this.sonDataSource.pushArrayData(this.songList)
  8229. ToastUtil.showToast('已添加至下一首播放')
  8230. }
  8231. //下一个
  8232. private playNext() {
  8233. if (!this.debounce()) {
  8234. return;
  8235. }
  8236. if (this.playType == 3) { //3:随机播放
  8237. this.randomPlay()
  8238. return;
  8239. }
  8240. if (ArrayUtil.isNotEmpty(this.songList)) {
  8241. if (this.curIndex == this.songList.length - 1) {
  8242. this.curIndex = 0;
  8243. } else {
  8244. this.curIndex++;
  8245. }
  8246. this.CONTROL_PlayStatus = PlayStatus.INIT;
  8247. this.stop();
  8248. this.currentSong = this.songList[this.curIndex]
  8249. this.videoUrl = this.songList[this.curIndex].filePath;
  8250. this.cover = this.songList[this.curIndex].pixelMapPath
  8251. this.artist = this.songList[this.curIndex].artist
  8252. this.name = this.songList[this.curIndex].name
  8253. this.startPlayOrResumePlay()
  8254. }
  8255. }
  8256. // 存储已播放的歌曲索引
  8257. private playedIndices: Set<number> = new Set();
  8258. //随机播放
  8259. private randomPlay() {
  8260. // if (!this.debounce()) {
  8261. // return;
  8262. // }
  8263. if (ArrayUtil.isNotEmpty(this.songList)) {
  8264. if (this.songList.length > 3) {
  8265. // 如果所有歌曲都播放过一次,清空已播放索引集合
  8266. if (this.playedIndices.size === this.songList.length) {
  8267. this.playedIndices.clear();
  8268. }
  8269. // 随机选择一个未播放的歌曲索引
  8270. let newIndex: number;
  8271. // 添加超时机制防止无限循环
  8272. let attempt = 0;
  8273. const maxAttempts = 100; // 根据需求调整
  8274. do {
  8275. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  8276. attempt++;
  8277. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  8278. if (attempt >= maxAttempts) {
  8279. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  8280. newIndex = Math.floor(Math.random() * this.songList.length);
  8281. }
  8282. this.curIndex = newIndex;
  8283. this.playedIndices.add(newIndex);
  8284. } else {
  8285. // 当歌曲数量小于或等于3时,直接播放下一首
  8286. if (this.curIndex == this.songList.length - 1) {
  8287. this.curIndex = 0;
  8288. } else {
  8289. this.curIndex++;
  8290. }
  8291. }
  8292. this.CONTROL_PlayStatus = PlayStatus.INIT;
  8293. this.stop();
  8294. this.currentSong = this.songList[this.curIndex];
  8295. this.videoUrl = this.songList[this.curIndex].filePath;
  8296. this.name = this.songList[this.curIndex].name;
  8297. this.cover = this.songList[this.curIndex].pixelMapPath
  8298. this.artist = this.songList[this.curIndex].artist
  8299. this.startPlayOrResumePlay();
  8300. }
  8301. }
  8302. private playIndex(index: number) {
  8303. if (!this.debounce()) {
  8304. return;
  8305. }
  8306. if (ArrayUtil.isNotEmpty(this.songList)) {
  8307. this.CONTROL_PlayStatus = PlayStatus.INIT;
  8308. this.stop();
  8309. this.currentSong = this.songList[this.curIndex]
  8310. this.videoUrl = this.songList[index].filePath;
  8311. this.name = this.songList[index].name
  8312. this.cover = this.songList[this.curIndex].pixelMapPath
  8313. this.artist = this.songList[this.curIndex].artist
  8314. this.curIndex = index;
  8315. this.startPlayOrResumePlay()
  8316. }
  8317. }
  8318. //上一个
  8319. private playPrevious() {
  8320. if (!this.debounce()) {
  8321. return;
  8322. }
  8323. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  8324. this.randomModePlayFromHistory()
  8325. return;
  8326. }
  8327. if (this.curIndex == 0) {
  8328. this.curIndex = this.songList.length - 1;
  8329. } else {
  8330. this.curIndex--;
  8331. }
  8332. this.CONTROL_PlayStatus = PlayStatus.INIT;
  8333. this.stop();
  8334. this.currentSong = this.songList[this.curIndex]
  8335. this.videoUrl = this.songList[this.curIndex].filePath;
  8336. this.name = this.songList[this.curIndex].name
  8337. this.cover = this.songList[this.curIndex].pixelMapPath
  8338. this.artist = this.songList[this.curIndex].artist
  8339. this.startPlayOrResumePlay()
  8340. }
  8341. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  8342. private randomModePlayFromHistory() {
  8343. if (this.historyList.length >= 2) {
  8344. // 播放历史记录的第二首
  8345. const prevSong = this.historyList[1];
  8346. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  8347. this.CONTROL_PlayStatus = PlayStatus.INIT;
  8348. this.stop();
  8349. this.currentSong = prevSong;
  8350. this.videoUrl = prevSong.filePath;
  8351. this.cover = prevSong.pixelMapPath
  8352. this.artist = prevSong.artist
  8353. this.name = prevSong.name;
  8354. this.startPlayOrResumePlay();
  8355. } else {
  8356. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  8357. if (this.curIndex === 0) {
  8358. this.curIndex = this.songList.length - 1;
  8359. } else {
  8360. this.curIndex--;
  8361. }
  8362. this.CONTROL_PlayStatus = PlayStatus.INIT;
  8363. this.stop();
  8364. this.currentSong = this.songList[this.curIndex];
  8365. this.videoUrl = this.songList[this.curIndex].filePath;
  8366. this.cover = this.songList[this.curIndex].pixelMapPath
  8367. this.artist = this.songList[this.curIndex].artist
  8368. this.name = this.songList[this.curIndex].name;
  8369. this.startPlayOrResumePlay();
  8370. }
  8371. }
  8372. debounce() {
  8373. const delay = 600;
  8374. let cur = new Date().getTime();
  8375. if (cur - this.last > delay) {
  8376. this.last = cur;
  8377. return true;
  8378. }
  8379. return false;
  8380. }
  8381. /**
  8382. * Sets whether the screen is a constant based on the playback status.
  8383. */
  8384. watchStatus() {
  8385. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  8386. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8387. this.windowClass.setWindowKeepScreenOn(true);
  8388. } else {
  8389. this.windowClass.setWindowKeepScreenOn(false);
  8390. }
  8391. }
  8392. /**
  8393. * Volume gesture method onActionStart.
  8394. *
  8395. * @param event Gesture event.
  8396. */
  8397. private customDialogComponentIdMM: number = 0
  8398. @Builder
  8399. customDialogComponentMM() {
  8400. Column() {
  8401. Row() {
  8402. Blank()
  8403. Text('验证密码')
  8404. .fontSize(22)
  8405. .fontColor($r('app.color.pri_bg'))
  8406. .margin({ top: 18 })
  8407. Blank()
  8408. Image($r('app.media.close'))
  8409. .fillColor(Color.White)
  8410. .margin({ top: 18, right: 18 })
  8411. .width(20)
  8412. .onClick(() => {
  8413. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  8414. })
  8415. }
  8416. .width('100%') // 使Row占据整个宽度
  8417. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  8418. Verify({
  8419. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  8420. });
  8421. }.height('60%')
  8422. .backgroundColor($r('app.color.index_background'))
  8423. .justifyContent(FlexAlign.SpaceBetween)
  8424. }
  8425. private handleVerifyCompleted(isSuccess: boolean) {
  8426. if (isSuccess) {
  8427. console.log('验证成功');
  8428. // 在这里处理验证成功后的逻辑
  8429. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  8430. this.currentPath = this.lockPath
  8431. this.getSortedFiles(this.currentPath)
  8432. } else {
  8433. // console.log('验证失败');
  8434. ToastUtil.showToast('验证失败')
  8435. }
  8436. }
  8437. private showVerifyDialog() {
  8438. promptAction.openCustomDialog({
  8439. transition: TransitionEffect.asymmetric(
  8440. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  8441. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  8442. ,
  8443. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  8444. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  8445. ),
  8446. builder: () => {
  8447. this.customDialogComponentMM()
  8448. },
  8449. isModal: true,
  8450. autoCancel: true,
  8451. maskColor: Color.Transparent,
  8452. alignment: DialogAlignment.Bottom,
  8453. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  8454. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  8455. console.log("dialog onWillDismiss")
  8456. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  8457. dismissDialogAction.dismiss()
  8458. }
  8459. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  8460. dismissDialogAction.dismiss()
  8461. }
  8462. }
  8463. }).then((dialogId: number) => {
  8464. this.customDialogComponentIdMM = dialogId
  8465. })
  8466. }
  8467. //左滑操作 移动文件 重命名 删除等操作
  8468. @Builder
  8469. DeleteButton(item: VideoItem, index: number, filePath: string) {
  8470. Row() {
  8471. //加入收藏
  8472. Button() {
  8473. Image(Utility.getIsFav(this.favList,item)?$r('app.media.add_fac_light2'):$r('app.media.add_fac'))
  8474. .fillColor(Color.White)
  8475. .width(20)
  8476. }
  8477. .width(40)
  8478. .height(40)
  8479. .type(ButtonType.Circle)
  8480. .backgroundColor(this.themeColor)
  8481. .margin(5)
  8482. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  8483. .onClick(() => {
  8484. if(item){
  8485. this.doFav(item)
  8486. }
  8487. })
  8488. //加入下一首播放
  8489. Button() {
  8490. Image($r('app.media.next_to_play'))
  8491. .fillColor(Color.White)
  8492. .width(20)
  8493. }
  8494. .width(40)
  8495. .height(40)
  8496. .type(ButtonType.Circle)
  8497. .backgroundColor(this.themeColor)
  8498. .margin(5)
  8499. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  8500. .onClick(() => {
  8501. this.addToNextPlay(item);
  8502. })
  8503. //复制文件
  8504. Button() {
  8505. Image($r('app.media.copy'))
  8506. .fillColor(Color.White)
  8507. .width(20)
  8508. }
  8509. .width(40)
  8510. .height(40)
  8511. .type(ButtonType.Circle)
  8512. .backgroundColor(this.themeColor)
  8513. .margin(5)
  8514. .id(filePath + 'copy')
  8515. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  8516. .onClick(() => {
  8517. this.showCopyDialog(false, item, index, filePath + 'copy');
  8518. })
  8519. //移动文件
  8520. Button() {
  8521. Image($r('app.media.cut'))
  8522. .fillColor(Color.White)
  8523. .width(20)
  8524. }
  8525. .width(40)
  8526. .height(40)
  8527. .type(ButtonType.Circle)
  8528. .backgroundColor(this.themeColor)
  8529. .margin(5)
  8530. .id(filePath)
  8531. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  8532. .onClick(() => {
  8533. this.showCutDialog(false, item, index, filePath);
  8534. })
  8535. Button() {
  8536. Image($r('app.media.cut_current'))
  8537. .fillColor(Color.White)
  8538. .width(20)
  8539. }
  8540. .width(40)
  8541. .height(40)
  8542. .type(ButtonType.Circle)
  8543. .backgroundColor(this.themeColor)
  8544. .margin(5)
  8545. .id(filePath + 'current')
  8546. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  8547. (this.isHasDir ? Visibility.Visible : Visibility.None))
  8548. .onClick(() => {
  8549. this.showCutDialog(true, item, index, filePath + 'current');
  8550. })
  8551. //重命名
  8552. Button() {
  8553. Image($r('app.media.rename2'))
  8554. .fillColor(Color.White)
  8555. .width(20)
  8556. }
  8557. .width(40)
  8558. .height(40)
  8559. .type(ButtonType.Circle)
  8560. .backgroundColor(this.themeColor)
  8561. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  8562. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  8563. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  8564. .margin(5)
  8565. .onClick(() => {
  8566. this.showReNameDialog(item, index + '', filePath)
  8567. })
  8568. Button() {
  8569. Image($r('app.media.delete2'))
  8570. .fillColor(Color.White)
  8571. .width(20)
  8572. }
  8573. .width(40)
  8574. .height(40)
  8575. .type(ButtonType.Circle)
  8576. .backgroundColor(this.themeColor)
  8577. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  8578. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  8579. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  8580. .margin(5)
  8581. .onClick(() => {
  8582. this.showWarnIsDeleteFile(item, index + '', filePath)
  8583. })
  8584. Button() {
  8585. Image($r('app.media.share2'))
  8586. .fillColor(Color.White)
  8587. .width(20)
  8588. }
  8589. .width(40)
  8590. .height(40)
  8591. .type(ButtonType.Circle)
  8592. .backgroundColor(this.themeColor)
  8593. .margin(5)
  8594. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  8595. .onClick(() => {
  8596. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  8597. })
  8598. }
  8599. }
  8600. /**
  8601. * 穿山甲banner广告
  8602. */
  8603. // private declare bannerAd: CSJNativeExpressAd;
  8604. // @State private status: string = "未加载"
  8605. // @State private isShowAd: boolean = false
  8606. // private declare mAdSlot: AdSlot;
  8607. // private mBiddingAdm = '' //服务端bidding才需要设置
  8608. // private expressLoadAdListener: NativeExpressAdListener = {
  8609. // /**
  8610. // * 加载失败的回调
  8611. // *
  8612. // * @param code
  8613. // * @param message
  8614. // */
  8615. // onError: (code: number, message: string) => {
  8616. // console.error("加载广告失败,code=" + code + ",message=" + message);
  8617. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  8618. // },
  8619. //
  8620. // /**
  8621. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  8622. // *
  8623. // * @param ads 返回的广告列表
  8624. // */
  8625. //
  8626. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  8627. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  8628. // if (ads && ads.length > 0) {
  8629. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  8630. // ad.setExpressInteractionListener({
  8631. // /**
  8632. // *广告的点击回调
  8633. // * @param type 广告的交互类型
  8634. // */
  8635. // onAdClicked: (type: number) => {
  8636. // console.log("BannerExpressAdPage==onAdClicked......");
  8637. // },
  8638. //
  8639. // /**
  8640. // * 广告的展示回调 每个广告仅回调一次
  8641. // * @param type 广告的交互类型
  8642. // */
  8643. // onAdShow: (type: number) => {
  8644. // console.log("BannerExpressAdPage==onAdShow......");
  8645. // },
  8646. //
  8647. // /**
  8648. // * 模板渲染失败
  8649. // */
  8650. // onRenderFail: (code: number, msg: string) => {
  8651. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  8652. // },
  8653. //
  8654. // /**
  8655. // * 模板渲染成功
  8656. // * @param width 返回view的宽 单位 vp
  8657. // * @param height 返回view的高 单位 vp
  8658. // */
  8659. // onRenderSuccess: (width: number, height: number) => {
  8660. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  8661. // this.bannerAd = ad;
  8662. // this.status = "广告加载完成待展示";
  8663. //
  8664. // this.showBannerAd()
  8665. // }
  8666. // })
  8667. // //渲染广告
  8668. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  8669. // this.setDislikeCallback(ad); //设置dislike
  8670. // ad.render(this.getUIContext())
  8671. // this.status = "广告加载中...";
  8672. // });
  8673. // }
  8674. // }
  8675. // }
  8676. //
  8677. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  8678. // ad.setDislikeCallback({
  8679. // /**
  8680. // * dislike show
  8681. // */
  8682. // onShow: () => {
  8683. // console.log("BannerExpressAdPage==dislike......show");
  8684. // },
  8685. //
  8686. // /**
  8687. // * @param position 选择的位置
  8688. // * @param value 选择的内容
  8689. // * @param enforceRemove 是否强制关闭广告
  8690. // */
  8691. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  8692. // this.isShowAd = false;
  8693. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  8694. // ",enforce=" + enforceRemove);
  8695. // },
  8696. //
  8697. // /**
  8698. // * 点击取消
  8699. // */
  8700. // onCancel: () => {
  8701. // console.log("BannerExpressAdPage==dislike......onCancel");
  8702. // }
  8703. //
  8704. // })
  8705. // }
  8706. /**
  8707. * 加载Banner广告
  8708. */
  8709. loadBannerAd(rit: string) {
  8710. // if (Utility.isNoble()) {
  8711. // return
  8712. // }
  8713. // if (!Utility.isPassInstallTime(2)) {
  8714. // return
  8715. // }
  8716. // this.isShowAd = false;
  8717. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  8718. // this.mAdSlot = new AdSlotBuilder()
  8719. // .setCodeId(rit)
  8720. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  8721. // .setAdCount(1)
  8722. // .setBidAdm(this.mBiddingAdm)
  8723. // .build()
  8724. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  8725. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  8726. // this.status = "广告加载中..."
  8727. }
  8728. /**
  8729. * 展示Banner广告
  8730. */
  8731. // showBannerAd() {
  8732. // if (!this.bannerAd) {
  8733. // return
  8734. // }
  8735. // this.isShowAd = true
  8736. // this.status = "已展示"
  8737. // }
  8738. /**
  8739. * 穿山甲广告代码结束
  8740. */
  8741. }
  8742. //视频气泡窗口的布局
  8743. @Builder
  8744. function customPopupBuilder(dataBu: BubbleBean) {
  8745. List() {
  8746. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  8747. ListItem() {
  8748. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8749. Row() {
  8750. Column() {
  8751. Image(dataBu.imageRes[index])
  8752. .height(28)
  8753. .fillColor(dataBu.color)
  8754. .alignSelf(ItemAlign.Center)
  8755. }
  8756. .width(32)
  8757. Text(item)
  8758. .padding({
  8759. top: 10,
  8760. bottom: 10,
  8761. right: 10,
  8762. left: 10
  8763. })
  8764. .textAlign(TextAlign.Start)
  8765. .width("100%")
  8766. }
  8767. }
  8768. .backgroundColor($r('app.color.settings_background_main'))
  8769. .margin({ top: 6, bottom: 6 })
  8770. }
  8771. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM).animation({ duration: 500,curve: Curve.Ease, delay: 100*index }),
  8772. TransitionEffect.scale({ x: 0, y: 0 }) ))
  8773. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  8774. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  8775. .onClick(() => {
  8776. dataBu.onItemClick?.(index)
  8777. })
  8778. })
  8779. }
  8780. .width(120)
  8781. .divider({
  8782. strokeWidth: 1,
  8783. color: "#22FFFFFF"
  8784. })
  8785. }
  8786. // Function to calculate a hash for the file list
  8787. function simpleHash(fileList: string[]): string {
  8788. let hash = 0;
  8789. const str = fileList.join(',');
  8790. for (let i = 0; i < str.length; i++) {
  8791. const char = str.charCodeAt(i);
  8792. hash = (hash << 5) - hash + char;
  8793. hash |= 0; // Convert to 32bit integer
  8794. }
  8795. return hash.toString();
  8796. }
  8797. interface MoreItem {
  8798. id: number;
  8799. image: Resource;
  8800. title: string;
  8801. }
  8802. //视频气泡窗口的布局
  8803. @Builder
  8804. function cutPopupBuilder(dataBu: BubbleBean) {
  8805. Column() {
  8806. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  8807. .padding({
  8808. top: 10,
  8809. bottom: 10,
  8810. right: 10,
  8811. left: 10
  8812. })
  8813. .textAlign(TextAlign.Start)
  8814. .width(160)
  8815. .fontWeight(666)
  8816. .fontSize(16)
  8817. List() {
  8818. ForEach(dataBu.data, (item: string, index: number) => {
  8819. ListItem() {
  8820. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8821. Row() {
  8822. Column() {
  8823. Image($r('app.media.music_group'))
  8824. .height(28)
  8825. .fillColor(dataBu.color)
  8826. .alignSelf(ItemAlign.Center)
  8827. }
  8828. .width(32)
  8829. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  8830. .padding({
  8831. top: 10,
  8832. bottom: 10,
  8833. right: 10,
  8834. left: 10
  8835. })
  8836. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  8837. .fontSize(15)
  8838. }
  8839. }
  8840. .backgroundColor(Color.Transparent)
  8841. .margin({ top: 7, bottom: 7 })
  8842. }
  8843. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM).animation({ duration: 500 }),
  8844. TransitionEffect.scale({ x: 0, y: 0 }) ))
  8845. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  8846. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  8847. .onClick(() => {
  8848. dataBu.onItemClick?.(index)
  8849. })
  8850. })
  8851. }
  8852. .width(150)
  8853. .divider({
  8854. strokeWidth: 1,
  8855. color: "#22FFFFFF"
  8856. })
  8857. }
  8858. .height(300)
  8859. .padding({
  8860. bottom:30
  8861. })
  8862. }