LocalMusic.ets 330 KB

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