LocalMusic.ets 374 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065
  1. import TitleBar from './TitleBar'
  2. import { curves, display, PiPWindow, promptAction, router, SymbolGlyphModifier, window } from '@kit.ArkUI';
  3. import { VideoItem } from '../viewmodel/VideoItem';
  4. import {
  5. AppUtil,
  6. ArrayUtil,
  7. Base64Util,
  8. DateUtil,
  9. DeviceUtil,
  10. DisplayUtil,
  11. FileUtil,
  12. ImageUtil,
  13. LogUtil,
  14. MD5,
  15. PreferencesUtil,
  16. RandomUtil,
  17. StrUtil,
  18. ToastUtil
  19. } from '@pura/harmony-utils';
  20. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  21. import { CommonConstants } from '../common/constants/CommonConstants';
  22. import Logger from '../common/util/Logger';
  23. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  24. import { Utility } from '../common/util/Utility';
  25. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  26. import { BubbleBean } from '../viewmodel/BubbleBean';
  27. import { PopupPosition, XPopup } from '@chinalike/popup';
  28. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  29. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  30. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  31. import { MessageEvents, util, worker, ErrorEvent } from '@kit.ArkTS';
  32. import { Verify } from './Verify';
  33. import { RotatingCover } from './RotatingCover';
  34. import { PlayConstants } from '../common/constants/PlayConstants';
  35. import { effectKit } from '@kit.ArkGraphics2D';
  36. import { ColorConversion } from '../common/util/ColorConversion';
  37. import { LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  38. import { AvSessionController } from '../controller/AvSessionController';
  39. import {
  40. // DeviceChangeReason,
  41. IjkMediaPlayer,
  42. InterruptEvent,
  43. InterruptHintType,
  44. LogUtils,
  45. OnBufferingUpdateListener,
  46. OnCompletionListener,
  47. OnErrorListener,
  48. OnInfoListener,
  49. OnPreparedListener,
  50. OnSeekCompleteListener,
  51. OnTimedTextListener,
  52. OnVideoSizeChangedListener
  53. } from '@ohos/ijkplayer';
  54. import { PlayStatus } from '../common/PlayStatus';
  55. import fs from '@ohos.file.fs';
  56. import { image } from '@kit.ImageKit';
  57. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  58. import * as chardet from '@changwei/chardet';
  59. import { UniversalDetector } from '@ohos/juniversalchardet';
  60. import { SettingPage } from '../pages/SettingPage';
  61. import { secondToTime } from '../common/util/CommUtils';
  62. import { CommonConstants2 } from '../common/util/CommonConstants2';
  63. import { hilog } from '@kit.PerformanceAnalysisKit';
  64. import { LazyDataSource } from '../common/util/LazyDataSource';
  65. import MediaTable from '../common/util/MediaTable';
  66. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  67. import ImageUtils from '../common/util/ImageUtils';
  68. import { ringtone } from '@kit.RingtoneKit';
  69. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  70. import { resourceManager } from '@kit.LocalizationKit';
  71. import { deviceInfo } from '@kit.BasicServicesKit';
  72. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  73. import { LrcParser } from '@sgaolei/lrc_parser';
  74. import app from '@system.app';
  75. import { TextNodeController } from './PipLyricTextBuilder';
  76. import { IndexerView } from './IndexerView';
  77. import { KeyCode } from '@kit.InputKit';
  78. // import { FFmpeg, FFProgressMessageParser } from '@sj/ffmpeg';
  79. const TAG = 'LocalMusic';
  80. const DEFAULT_INDEX =
  81. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  82. 'X', 'Y', 'Z']
  83. //排序类型
  84. function getTypeOrder(type: number) {
  85. switch (type) {
  86. case CommonConstants.TYPE_IS_DIR:
  87. return 1; // First
  88. case CommonConstants.TYPE_IS_CSJAD:
  89. return 2; // Middle
  90. case CommonConstants.TYPE_LOCAL:
  91. return 3; // Last
  92. default:
  93. return 4; // Unknown types, if any, go last
  94. }
  95. }
  96. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  97. // 定义接口
  98. interface HiCarAspectRatio {
  99. ratio: number;
  100. name: string;
  101. }
  102. interface GeneratedObjectLiteralInterface_1 {
  103. assetId: string;
  104. title: string;
  105. artist: string;
  106. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  107. mediaUri: string;
  108. // 该字段大写,音频'AUDIO',视频'VIDEO'
  109. mediaType: string;
  110. mediaSize: number;
  111. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  112. startPosition: number;
  113. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  114. duration: number;
  115. albumCoverUri: string;
  116. albumTitle: string;
  117. appName: string;
  118. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  119. drmScheme: string;
  120. }
  121. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  122. const ITEM_HEIGHT: number = 58; // 列表项中高度
  123. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  124. //功能强大的音乐播放器
  125. @Preview
  126. @Component
  127. export struct LocalMusic {
  128. @Consume mType: number;
  129. @StorageProp('themeColor') themeColor: string =
  130. 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 mScrollMap: 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 isShowPlayPageBack: boolean = false //是否显示播放页返回键
  177. @State isShowHeader: boolean = true
  178. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  179. @State isShowSingleLineLyric: boolean = false //是否显示播放页返回键
  180. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  181. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  182. @State isSwipe: boolean = false //listItem的左滑开关
  183. @State customizeBgPath: string | undefined = '';
  184. @State isDarkMode: boolean = false
  185. @State lyricTextWeight: number = 400
  186. @State lyricTextWeightPip: number = 400
  187. @State currentSwiperIndex: number = 0
  188. @State blurValue: number = 0 //背景模糊
  189. @State bgBrightness: number = 0 //背景亮度
  190. private listScroller: ListScroller = new ListScroller()
  191. private playListScroller: Scroller = new Scroller()
  192. @StorageProp('isLandscape') isLandscape: boolean = false;
  193. @StorageProp('topRectHeight') topRectHeight: number = px2vp(AppUtil.getStatusBarHeight());
  194. @StorageProp('windowWidth') windowWidth: number = 0;
  195. @StorageProp('windowHeight') windowHeight: number = 0;
  196. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  197. private UNKONWN:string = '';
  198. private listArea: Area = {
  199. width: 0,
  200. height: 0,
  201. position: {},
  202. globalPosition: {}
  203. }
  204. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  205. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  206. onColorModeChange() {
  207. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  208. if (this.isCustomizeBg) {
  209. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  210. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  211. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  212. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  213. } else {
  214. if (!this.isDarkMode) {
  215. this.titleBarModel.setTitleBarBackground(this.themeColor)
  216. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  217. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  218. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  219. } else {
  220. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  221. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  222. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  223. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  224. }
  225. }
  226. }
  227. onModeChange() {
  228. this.isFavMusic = false
  229. if (this.modeType === 2 || this.modeType === 3) {
  230. this.titleBarModel.setRightIcon(null)
  231. } else {
  232. this.titleBarModel.setRightIcon(($r('app.media.add')))
  233. }
  234. LogUtil.info('onecold onModeChange = ' + this.modeType)
  235. switch (this.modeType) {
  236. case 0:
  237. this.getSortedFiles(this.currentPath)
  238. break
  239. case 1:
  240. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  241. this.updateListData(this.mediaKuList)
  242. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  243. break
  244. case 2:
  245. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  246. this.updateListData(this.artistList)
  247. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  248. break
  249. case 3:
  250. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  251. this.updateListData(this.albumList)
  252. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  253. break
  254. }
  255. }
  256. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  257. // @StorageLink('isPlay') isPlay: boolean = false;
  258. @StorageLink('isShowPlay') isShowPlay: boolean = false;
  259. @StorageLink('songList') songList: Array<VideoItem> = [];
  260. @State translateY: number = 0;
  261. @State isShowSheet: boolean = false;
  262. @State isShowSheetView: boolean = false;
  263. @State isShowTimeCloseView: boolean = false;
  264. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  265. @StorageLink('currIndex') curIndex: number = 0;
  266. @Consume isShowDrawer: boolean;
  267. @Consume offsetX: number;
  268. @State isFac: boolean = false;
  269. @State favList: Array<VideoItem> = []
  270. @Consume isFavMusic: boolean
  271. @State isClickedPLayAll: boolean = false;
  272. private scrollerForlist: ListScroller = new ListScroller();
  273. imagesF: ImageFrameInfo[] = [
  274. { src: $r("app.media.app_loading0") },
  275. { src: $r("app.media.app_loading1") },
  276. { src: $r("app.media.app_loading2") },
  277. { src: $r("app.media.app_loading3") },
  278. ]
  279. @State animationState: AnimationStatus = AnimationStatus.Initial
  280. // 缓存机制
  281. private cache: Map<string, Array<VideoItem>> = new Map();
  282. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  283. // 持久化缓存
  284. private async saveCacheToStorage() {
  285. const cacheArray = Array.from(this.cache.entries());
  286. const stringCacheArray = Array.from(this.stringCache.entries());
  287. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  288. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  289. }
  290. // 载入缓存
  291. private async loadCacheFromStorage() {
  292. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  293. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  294. if (cacheString) {
  295. const cacheArray: [string, Array<VideoItem>][] = JSON.parse(cacheString);
  296. this.cache = new Map(cacheArray);
  297. }
  298. if (stringCacheString) {
  299. const stringCacheArray: [string, string][] = JSON.parse(stringCacheString);
  300. this.stringCache = new Map(stringCacheArray);
  301. }
  302. }
  303. // 查找缓存
  304. private findCache(key: string): Array<VideoItem> | undefined {
  305. return this.cache.get(key);
  306. }
  307. // 查找字符串缓存
  308. private findStringCache(key: string): string | undefined {
  309. return this.stringCache.get(key);
  310. }
  311. // 添加缓存
  312. private addCache(key: string, value: Array<VideoItem>) {
  313. this.cache.set(key, value);
  314. }
  315. // 添加字符串缓存
  316. private addStringCache(key: string, value: string) {
  317. this.stringCache.set(key, value);
  318. }
  319. // 删除缓存
  320. private deleteCache(key: string) {
  321. this.cache.delete(key);
  322. this.saveCacheToStorage()
  323. }
  324. // 删除字符串缓存
  325. private deleteStringCache(key: string) {
  326. this.stringCache.delete(key);
  327. }
  328. // 多选机制
  329. @State selectedFiles: Array<VideoItem> = [];
  330. @State isMultiSelect: boolean = false;
  331. @State isAllSelected: boolean = false;
  332. @State appName: string = ''
  333. @State isHasDir: boolean = false
  334. @State packName: string = ''
  335. context = getContext(this);
  336. @State titleBarModel: TitleBar.Model = new TitleBar.Model()
  337. .setTitleTextStyle(FontStyle.Normal)
  338. .setTitleBarStyle(TitleBar.BarStyle.TRANSPARENT)
  339. .setLeftIcon($r('app.media.menu'))
  340. .setLeftIconWidth(25)
  341. .setLeftIconHeight(25)
  342. .setTitleName('首页')
  343. .setTitleFontSize(18)
  344. .setTitleFontColor(Color.White)
  345. .setTitleBarBackground(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  346. .setTitleBarBottomLineColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  347. .setLeftTitleStateNormalStyleColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  348. .setRightIcon($r('app.media.add'))
  349. .setOnRightClickListener(() => {
  350. this.showSheelDialog()
  351. })
  352. .setOnTitleClickListener(() => {
  353. this.showPupDialog()
  354. })
  355. .setOnLeftClickListener(() => {
  356. this.doSwipBack()
  357. })
  358. doSwipBack() {
  359. if (this.modeType !== 0 && this.isCanBack) {
  360. this.onModeChange()
  361. this.isCanBack = false
  362. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  363. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  364. setTimeout(() => {
  365. if (this.modeType == 2) {
  366. if (this.isGridMusic) {
  367. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  368. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  369. } else {
  370. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  371. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  372. }
  373. } else if (this.modeType == 3) {
  374. if (this.isGridMusic) {
  375. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  376. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  377. } else {
  378. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  379. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  380. }
  381. }
  382. }, 200)
  383. return
  384. }
  385. if (this.isHistory || this.isFavMusic) {
  386. this.isHistory = false
  387. this.getSortedFiles(this.currentPath)
  388. return
  389. }
  390. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  391. animateTo({ duration: 555 }, () => {
  392. // 动画闭包内控制Image组件的出现和消失
  393. this.isShowDrawer = !this.isShowDrawer
  394. this.offsetX = 0
  395. })
  396. return
  397. }
  398. //返回上一级歌单的滚动位置
  399. setTimeout(() => {
  400. if (this.modeType == 0) {
  401. if (this.isGridMusic) {
  402. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  403. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  404. } else {
  405. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  406. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  407. }
  408. }
  409. }, 300)
  410. this.currentPath = Utility.getParentDirectory(this.currentPath)
  411. Logger.info('this.currentPath2 = ' + this.currentPath)
  412. this.getSortedFiles(this.currentPath)
  413. }
  414. // 组件生命周期
  415. aboutToAppear() {
  416. this.initSetting()
  417. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  418. this.topRectHeight = px2vp(AppUtil.getStatusBarHeight());
  419. Utility.getAppName(getContext(this)).then((appName: string) => {
  420. this.appName = appName
  421. })
  422. this.packName = AppUtil.getBundleName()
  423. this.loadCacheFromStorage(); // 加载缓存
  424. this.mkDownLoadDir()
  425. let eventMusic: emitter.InnerEvent = { eventId: 2 }
  426. // 监听广播事件(打开其他应用处理)
  427. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  428. this.saveVideoDatas([eventData.data?.message], true)
  429. });
  430. //侧滑广播接收时间
  431. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: 888 }
  432. // 监听广播事件(打开其他应用处理)
  433. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  434. animateTo({ duration: 555 }, () => {
  435. this.doSwipBack()
  436. })
  437. });
  438. //ScanFilePage广播接收时间
  439. let eventScanUpdate: emitter.InnerEvent = { eventId: 101 }
  440. // 监听ScanFilePage广播事件(更新数据库)
  441. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  442. this.doUpdateData()
  443. });
  444. let eventSetting: emitter.InnerEvent = { eventId: 333 }
  445. // 监听广播事件(通用设置配置更新)
  446. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  447. this.doChangeSetting()
  448. });
  449. let event: Callback<InterruptEvent> = (event) => {
  450. LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  451. this.savePlaybackPosition()
  452. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  453. this.pause();
  454. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  455. this.startPlayOrResumePlay();
  456. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  457. this.stop();
  458. }
  459. }
  460. this.mIjkMediaPlayer.on('audioInterrupt', event);
  461. // 音频设备断连回调处理
  462. // let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  463. // LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  464. // if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  465. // this.pause();
  466. // }
  467. // }
  468. // this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  469. this.makeWorker()
  470. //折叠屏的屏幕显示模式变化
  471. display.on('foldDisplayModeChange', (data) => {
  472. this.doChangeBarHeight()
  473. });
  474. display.on('foldStatusChange', (data) => {
  475. Logger.info('onecold foldStatusChange ')
  476. });
  477. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  478. // 读取 themeMode 并同步 currentColorMode
  479. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  480. this.applyThemeMode(this.themeMode)
  481. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  482. AppStorage.setOrCreate('themeColor', themeColor);
  483. this.themeColor = themeColor;
  484. this.doChangeSetting()
  485. this.windowClass.on('windowSizeChange', (size) => {
  486. // LogUtil.info('onecold windowSizeChange')
  487. this.doChangeBarHeight()
  488. let viewWidth = px2vp(size.width);
  489. let viewHeight = px2vp(size.height);
  490. if(this.isPhoneLan()){
  491. this.is_auto_hide_progress = false
  492. setTimeout(() => {
  493. this.is_auto_hide_progress = true
  494. }, 6000)
  495. }else{
  496. this.startAutoHide()
  497. }
  498. });
  499. this.eventHub.on('onStateChange', (fg: boolean) => {
  500. if (fg && this.curState === 'STARTED') {
  501. this.stopPip();
  502. }
  503. });
  504. }
  505. startAutoHide() {
  506. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  507. this.is_auto_hide_progress = false
  508. setTimeout(() => {
  509. this.is_auto_hide_progress = true
  510. }, 6000)
  511. }
  512. }
  513. applyThemeMode(mode: number) {
  514. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  515. if (mode === 1) {
  516. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  517. } else if (mode === 2) {
  518. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  519. }
  520. AppStorage.setOrCreate('currentColorMode', colorMode)
  521. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  522. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  523. AppStorage.setOrCreate('themeMode', mode)
  524. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  525. // 只有强制浅色/深色时才主动设置
  526. const context = getContext(this) as common.UIAbilityContext
  527. context.getApplicationContext().setColorMode(colorMode)
  528. }
  529. initSetting() {
  530. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  531. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  532. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  533. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, true)
  534. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  535. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  536. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  537. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  538. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  539. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  540. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  541. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  542. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  543. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 3)
  544. this.isCoverTop = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP, false)
  545. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  546. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  547. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  548. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  549. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  550. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  551. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  552. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  553. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  554. //如果是hicar连接状态,这些都是false
  555. if(this.isHiCarStatus){
  556. this.isShowTitleBar = false//不显示导航栏
  557. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//大屏幕不可以Grid
  558. {
  559. this.isShowHeader = false//二级菜单不显示头部
  560. this.isGridMusic= false//用list不用网格
  561. this.isCoverTopBig = false
  562. }
  563. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  564. }
  565. if (this.isSavePlayMode) {
  566. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  567. }
  568. if (this.isCustomizeBg) {
  569. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  570. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  571. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  572. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  573. } else {
  574. if (!this.isDarkMode) {
  575. this.titleBarModel.setTitleBarBackground(this.themeColor)
  576. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  577. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  578. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  579. } else {
  580. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  581. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  582. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  583. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  584. }
  585. }
  586. }
  587. doChangeSetting() {
  588. this.initSetting()
  589. this.deleteCache(this.currentPath)
  590. if (this.modeType === 0) {
  591. this.getSortedFiles(this.currentPath)
  592. }
  593. }
  594. doChangeBarHeight() {
  595. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  596. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  597. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  598. this.setBarHeightNormal()
  599. }
  600. }
  601. onPageShow() {
  602. app.setImageCacheCount(100);
  603. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  604. app.setImageRawDataCacheSize(104857600);
  605. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  606. }
  607. //开启线程查看各个数据库
  608. makeWorker() {
  609. setTimeout(() => {
  610. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  611. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  612. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  613. // workerInstance.postMessage({
  614. // code: 1,
  615. // data1: this.context,
  616. // data2: this.rootPath,
  617. // data3: this.lockPath,
  618. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  619. // });
  620. PreferencesUtil.putSync('isFirstApp', false)
  621. } else {
  622. workerInstance.postMessage({ code: 2, data: this.context });
  623. workerInstance.postMessage({ code: 3, data: this.context });
  624. workerInstance.postMessage({ code: 4, data: this.context });
  625. this.getHistoryList(false)
  626. }
  627. }, 1000)
  628. workerInstance.onmessage = (e: MessageEvents): void => {
  629. switch (e.data.code) {
  630. case 101: //第一次扫描文件夹入库
  631. ToastUtil.showToast('刷新同步数据库成功!')
  632. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  633. this.doUpdateData()
  634. break;
  635. case 102: //查询媒体库列表
  636. this.mediaKuList = e.data.data
  637. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  638. Utility.doSortListAscending(this.mediaKuList)
  639. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  640. if (this.modeType === 1) {
  641. this.updateListData(this.mediaKuList)
  642. }
  643. break;
  644. case 103: //收到查询艺术家列表
  645. this.artistMap = e.data.data1;
  646. this.artistList = e.data.data2;
  647. break;
  648. case 104: //收到查询专辑列表
  649. this.albumMap = e.data.data1;
  650. this.albumList = e.data.data2
  651. //查询完毕在启动是否自动播放
  652. if (this.isStartAutoPlay) {
  653. this.startPlayOrResumePlay()
  654. }
  655. break;
  656. }
  657. };
  658. // 在调用terminate后,执行onexit
  659. workerInstance.onexit = (code) => {
  660. console.log("main thread terminate");
  661. }
  662. //若Worker处于已销毁或正在销毁等非运行状态时,调用其功能接口,会抛出相应的错误。
  663. // 使用Worker模块时,需要在主线程中注册onerror接口,否则当worker线程出现异常时会发生jscrash问题。
  664. workerInstance.onerror = (err: ErrorEvent) => {
  665. console.log("onerror" + err.message);
  666. }
  667. }
  668. @State isFirstStartPlay: boolean = false
  669. //获取download_path
  670. async mkDownLoadDir() {
  671. const documentViewPicker = new picker.DocumentViewPicker()
  672. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  673. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  674. // this.rootPath = this.download_path
  675. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  676. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  677. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  678. Logger.info('onecold rootPath = ' + this.rootPath)
  679. Logger.info('onecold lockPath = ' + this.lockPath)
  680. if (!FileUtil.accessSync(this.lockPath)) {
  681. FileUtil.mkdirSync(this.lockPath)
  682. }
  683. if (!FileUtil.accessSync(this.favPath)) {
  684. FileUtil.mkdirSync(this.favPath)
  685. }
  686. if (!FileUtil.accessSync(this.historyPath)) {
  687. FileUtil.mkdirSync(this.historyPath)
  688. }
  689. this.getSortedFiles(this.rootPath).then(() => {
  690. this.isFavMusic = false
  691. //穿山甲
  692. // this.loadBannerAd(CSJUtil.getBannerID())
  693. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  694. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  695. if (ArrayUtil.isEmpty(this.songList)) {
  696. this.songList = this.getCurFileList()
  697. } else {
  698. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  699. }
  700. if (ArrayUtil.isNotEmpty(this.songList)) {
  701. this.isFirstStartPlay = true
  702. this.sonDataSource.pushArrayData(this.songList)
  703. if (this.currentSong === undefined) {
  704. this.isFirstStartPlay = false
  705. this.currentSong = this.songList[0]
  706. }
  707. this.videoUrl = this.currentSong.filePath
  708. this.name = this.currentSong.name
  709. this.cover = this.currentSong.pixelMapPath
  710. } else {
  711. this.name = '空空如也'
  712. }
  713. })
  714. this.getFavList(false)
  715. }
  716. getFavList(isFavRefresh: boolean) {
  717. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  718. this.favList = result
  719. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  720. this.videoLocalList = this.favList
  721. this.updateListData(this.videoLocalList)
  722. }
  723. })
  724. }
  725. getHistoryList(isRefresh: boolean) {
  726. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  727. this.historyList = result
  728. // for (let i = 0; i < this.historyList.length; i++) {
  729. //
  730. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  731. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  732. // }
  733. if (isRefresh) {
  734. this.videoLocalList = this.historyList
  735. this.updateListData(this.videoLocalList, true)
  736. }
  737. })
  738. }
  739. // 组件消失生命周期
  740. aboutToDisappear() {
  741. console.info('LifeCycleComponent aboutToDisappear');
  742. emitter.off(2);
  743. emitter.off(101);
  744. emitter.off(888);
  745. emitter.off(333);
  746. this.mDestroyPage = true;
  747. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  748. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  749. this.stop();
  750. }
  751. this.mIjkMediaPlayer.off('audioInterrupt');
  752. if (workerInstance) {
  753. workerInstance.terminate();
  754. }
  755. this.stopPip();
  756. this.destroyPipController()
  757. }
  758. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean) {
  759. this.isFavMusic = false
  760. if (isWorkerPost) {
  761. workerInstance.postMessage({ code: 2, data: this.context }); //刷新媒体库列表
  762. }
  763. if (this.modeType !== 0) {
  764. return
  765. }
  766. this.isCanBack = false
  767. this.currentPath = curPath
  768. this.titleBarModel.setTitleName(Utility.getFileDirName(this.currentPath, this.rootPath))
  769. if (curPath === this.rootPath) {
  770. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  771. } else {
  772. this.currentTitleName = Utility.getFileDirName(this.currentPath, this.rootPath)
  773. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  774. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  775. }
  776. }
  777. // Get the current file list and calculate its hash
  778. this.fileList = FileUtil.listFileSync(curPath);
  779. const currentHash = simpleHash(this.fileList);
  780. // Check cache
  781. const cachedValue = this.findCache(curPath);
  782. Logger.info('onecold cachedValue = ' + cachedValue)
  783. const cachedHash = this.findStringCache(curPath + '_hash');
  784. const cachedDirList = this.findCache(curPath + "_dirList");
  785. if (cachedValue !== undefined) {
  786. // this.videoLocalList = cachedValue;
  787. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  788. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  789. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  790. }
  791. this.updateListData(cachedValue)
  792. }
  793. if (cachedDirList !== undefined) {
  794. this.dirList = cachedDirList
  795. }
  796. //通过当前hash值和缓存hash判断list有没有变化
  797. if (cachedValue && cachedHash === currentHash) {
  798. return;
  799. }
  800. this.fileList = FileUtil.listFileSync(curPath)
  801. let directories: Array<VideoItem> = [];
  802. let files: Array<VideoItem> = [];
  803. for (let i = 0; i < this.fileList.length; i++) {
  804. console.info(`The name of file: ${this.fileList[i]}`);
  805. let path = curPath + '/' + this.fileList[i]
  806. if (FileUtil.isDirectory(path)) {
  807. let item: VideoItem =
  808. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  809. '')
  810. if (this.isShowDir(item.name)) {
  811. directories.push(item);
  812. }
  813. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  814. // Utility.doSortListAscending(directories)
  815. } else {
  816. if (this.currentPath === this.lockPath) {
  817. let item: VideoItem =
  818. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  819. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  820. files.push(item);
  821. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  822. // this.doSortListAscending(files)
  823. }
  824. }
  825. }
  826. }
  827. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  828. if (this.currentPath !== this.lockPath) {
  829. files = result;
  830. }
  831. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  832. Utility.doSortListAscending(files)
  833. if (this.currentPath === this.rootPath) {
  834. this.dirList = directories
  835. this.addCache(curPath + "_dirList", this.dirList);
  836. }
  837. //插入广告先注释掉
  838. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  839. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  840. // directories.push(adItem)
  841. // }
  842. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  843. this.videoLocalList = directories.concat(files);
  844. this.updateListData(this.videoLocalList)
  845. if (ArrayUtil.isNotEmpty(files)) {
  846. if (this.currentPath != this.rootPath) {
  847. if (files) {
  848. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  849. }
  850. }
  851. // 缓存结果
  852. this.addCache(curPath, this.videoLocalList);
  853. await this.saveCacheToStorage(); // 保存缓存至本地存储
  854. this.addStringCache(curPath + '_hash', currentHash);
  855. }
  856. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  857. // for (let i = 0; i < this.videoLocalList.length; i++) {
  858. //
  859. // console.info(`onecold gengxin 1: ${this.videoLocalList[i].pixelMapPath}`);
  860. //
  861. // }
  862. // this.setButtonStatus()
  863. if (isOpen) {
  864. if (destPath === undefined) {
  865. // 处理 destPath 为 undefined 的情况
  866. return
  867. }
  868. if (destPath.endsWith('.lrc')) {
  869. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  870. if (StrUtil.isNotEmpty(this.videoUrl)) {
  871. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  872. this.initLyric(lyricPath);
  873. }
  874. return
  875. }
  876. let item2 = new VideoItem(Utility.getMediaNameByUri(destPath), destPath, destPath, 0, 0, '')
  877. this.doPlay(item2)
  878. }
  879. });
  880. }
  881. //扫描文件夹入库
  882. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  883. const files = FileUtil.listFileSync(curPath);
  884. let mediaItems: VideoItem[] = [];
  885. Logger.info('onecold scanDirectory start ')
  886. for (const file of files) {
  887. const fPath = `${curPath}/${file}`;
  888. if (fPath === this.lockPath) {
  889. Logger.info(`Skipping locked path: ${fPath}`);
  890. continue;
  891. }
  892. if (FileUtil.isDirectory(fPath)) {
  893. // Recursively scan subdirectories
  894. const subDirItems = await this.scanDirectory(fPath);
  895. mediaItems = mediaItems.concat(subDirItems);
  896. } else {
  897. Logger.info('onecold scanDirectory filePath = ' + fPath)
  898. // Process media files
  899. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  900. let mediaItem: VideoItem =
  901. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, true);
  902. mediaItems.push(mediaItem);
  903. this.table.insert(mediaItem, (id: number) => {
  904. });
  905. }
  906. }
  907. }
  908. return mediaItems;
  909. }
  910. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  911. animateTo({ duration: 888 }, () => {
  912. this.opacityItem = 0;
  913. });
  914. setTimeout(() => {
  915. this.videoLocalList = mList;
  916. if (!noSort) {
  917. if (this.modeType === 0 || this.modeType === 1) {
  918. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  919. this.doSortType(this.sortType)
  920. }
  921. }
  922. this.dataSource.pushArrayData(this.videoLocalList)
  923. animateTo({ duration: 888 }, () => {
  924. this.opacityItem = 1;
  925. });
  926. this.setButtonStatus()
  927. }, 200);
  928. }
  929. //排序模式和多选模式
  930. showPupDialog() {
  931. if (this.modeType === 2 || this.modeType === 3) {
  932. this.titleBarModel.setRightIcon(null)
  933. } else {
  934. this.titleBarModel.setRightIcon(($r('app.media.add')))
  935. }
  936. let dataBean = new BubbleBean()
  937. dataBean.data = ["首页", "媒体库", "艺术家", "专辑", "同步数据"]
  938. dataBean.color = this.themeColor
  939. dataBean.modeType = this.modeType
  940. dataBean.imageRes =
  941. [$r('app.media.home_press'), $r('app.media.kp_music'), $r('app.media.music_menu'), $r('app.media.llq'),
  942. $r('app.media.refresh')]
  943. let pup: XPopup;
  944. if (this.isDarkMode) {
  945. pup = XPopup.Builder()
  946. .setPopupPosition(PopupPosition.BOTTOM)
  947. .atView('pup_positon_music')
  948. .setBackgroundColor(Color.Black)
  949. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  950. .show()
  951. } else {
  952. pup = XPopup.Builder()
  953. .setPopupPosition(PopupPosition.BOTTOM)
  954. .atView('pup_positon_music')
  955. .setBackgroundColor(Color.White)
  956. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  957. .show()
  958. }
  959. dataBean.onItemClick = (i) => {
  960. XPopup.dismissTop()
  961. switch (i) {
  962. case 0: //首页
  963. this.modeType = 0
  964. this.getSortedFiles(this.currentPath)
  965. break
  966. case 1:
  967. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  968. this.modeType = 1
  969. this.updateListData(this.mediaKuList)
  970. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  971. break
  972. case 2:
  973. this.modeType = 2
  974. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  975. this.updateListData(this.artistList)
  976. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  977. break
  978. case 3:
  979. this.modeType = 3
  980. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  981. this.updateListData(this.albumList)
  982. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  983. break
  984. case 4: //同步数据
  985. this.asyncCurrentPathData()
  986. break
  987. }
  988. }
  989. }
  990. getCurFileList(): Array<VideoItem> {
  991. let files: Array<VideoItem> = [];
  992. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  993. for (let i = 0; i < this.videoLocalList.length; i++) {
  994. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  995. files.push(this.videoLocalList[i]);
  996. }
  997. }
  998. }
  999. return files
  1000. }
  1001. setButtonStatus() {
  1002. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1003. this.isZero = false
  1004. } else {
  1005. this.isZero = true
  1006. }
  1007. if (this.currentPath !== this.rootPath &&
  1008. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  1009. this.isHasDir = true //不为空,说明有子文件夹
  1010. } else {
  1011. this.isHasDir = false
  1012. }
  1013. }
  1014. showRankDialog() {
  1015. if (this.modeType === 2 || this.modeType === 3) {
  1016. //动作面板
  1017. DialogHelper.showBottomSheetDialog({
  1018. title: "请选择排序模式",
  1019. maskColor: Color.Transparent,
  1020. // sheets: ["按名称升序", "按名称降序"],
  1021. sheets: [
  1022. { value: '按名称升序', fontColor: $r('app.color.text_color') },
  1023. { value: '按名称降序', fontColor: $r('app.color.text_color') },
  1024. ],
  1025. backgroundColor: $r('app.color.bg_card'),
  1026. height: '30%',
  1027. transition: AnimationHelper.transitionInDown(555),
  1028. onAction: (index) => {
  1029. switch (index) {
  1030. case 0:
  1031. Utility.doSortListAscending(this.videoLocalList)
  1032. break;
  1033. case 1:
  1034. Utility.doSortListDescending(this.videoLocalList)
  1035. break;
  1036. }
  1037. this.updateListData(this.videoLocalList)
  1038. }
  1039. })
  1040. return
  1041. }
  1042. //动作面板
  1043. DialogHelper.showBottomSheetDialog({
  1044. title: "请选择排序模式",
  1045. maskColor: Color.Transparent,
  1046. height: '75%',
  1047. // sheets: ["按艺术家升序", "按艺术家降序", "按专辑升序", "按专辑降序", "按名称升序", "按名称降序", "按添加时间升序","按添加时间降序"],
  1048. sheets: [
  1049. { value: "按艺术家升序", fontColor: $r('app.color.text_color') },
  1050. { value: "按艺术家降序", fontColor: $r('app.color.text_color') },
  1051. { value: "按专辑升序", fontColor: $r('app.color.text_color') },
  1052. { value: "按专辑降序", fontColor: $r('app.color.text_color') },
  1053. { value: "按名称升序", fontColor: $r('app.color.text_color') },
  1054. { value: "按名称降序", fontColor: $r('app.color.text_color') },
  1055. { value: "按添加时间升序", fontColor: $r('app.color.text_color') },
  1056. { value: "按添加时间降序", fontColor: $r('app.color.text_color') },
  1057. ],
  1058. backgroundColor: $r('app.color.bg_card'),
  1059. transition: AnimationHelper.transitionInDown(555),
  1060. onAction: (index) => {
  1061. this.doSortType(index)
  1062. PreferencesUtil.put(SettingPage.SORT_TYPE, index)
  1063. this.updateListData(this.videoLocalList, true)
  1064. }
  1065. })
  1066. }
  1067. doSortType(index: number) {
  1068. switch (index) {
  1069. case 0:
  1070. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1071. // 类型排序优先级
  1072. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1073. if (typeOrder !== 0) {
  1074. return typeOrder;
  1075. }
  1076. // 处理艺术家可能为undefined的字符串比较
  1077. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1078. const artistB = b.artist?.trim() || '';
  1079. return artistA.localeCompare(artistB);
  1080. });
  1081. break;
  1082. case 1:
  1083. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1084. // 类型排序优先级
  1085. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1086. if (typeOrder !== 0) {
  1087. return typeOrder;
  1088. }
  1089. // 处理艺术家可能为undefined的字符串比较
  1090. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1091. const artistB = b.artist?.trim() || '';
  1092. return artistB.localeCompare(artistA);
  1093. });
  1094. break;
  1095. case 2:
  1096. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1097. // 类型排序优先级
  1098. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1099. if (typeOrder !== 0) {
  1100. return typeOrder;
  1101. }
  1102. // 处理专辑可能为undefined的字符串比较
  1103. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1104. const albumB = b.album?.trim() || '';
  1105. return albumA.localeCompare(albumB);
  1106. });
  1107. break;
  1108. case 3:
  1109. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1110. // 类型排序优先级
  1111. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1112. if (typeOrder !== 0) {
  1113. return typeOrder;
  1114. }
  1115. // 处理专辑可能为undefined的字符串比较
  1116. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1117. const albumB = b.album?.trim() || '';
  1118. return albumB.localeCompare(albumA);
  1119. });
  1120. break;
  1121. case 4:
  1122. Utility.doSortListAscending(this.videoLocalList)
  1123. break;
  1124. case 5:
  1125. Utility.doSortListDescending(this.videoLocalList)
  1126. break;
  1127. case 6:
  1128. this.videoLocalList.sort((a, b) => {
  1129. // First, sort by type
  1130. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1131. if (typeOrder !== 0) {
  1132. return typeOrder;
  1133. }
  1134. // If types are the same, sort by cTime in ascending order
  1135. return a.cTime.localeCompare(b.cTime);
  1136. });
  1137. break;
  1138. case 7:
  1139. this.videoLocalList.sort((a, b) => {
  1140. // First, sort by type
  1141. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1142. if (typeOrder !== 0) {
  1143. return typeOrder;
  1144. }
  1145. // If types are the same, sort by cTime in descending order
  1146. return b.cTime.localeCompare(a.cTime);
  1147. });
  1148. break;
  1149. }
  1150. }
  1151. showSheelDialog() {
  1152. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  1153. // this.showTips()
  1154. // return
  1155. // }
  1156. this.showAddDialog()
  1157. }
  1158. showAddDialog() {
  1159. if (this.modeType === 2 || this.modeType === 3) {
  1160. return
  1161. }
  1162. DialogHelper.showActionSheetDialog({
  1163. title: "请选择添加方式(建议歌词文件一起导入)",
  1164. // sheets: ["新建歌单", "手动导入", "自动导入"],
  1165. sheets: [
  1166. { value: "新建歌单", fontColor: $r('app.color.text_color') },
  1167. { value: "手动导入", fontColor: $r('app.color.text_color') },
  1168. { value: "自动导入", fontColor: $r('app.color.text_color') },
  1169. { value: "全选导入", fontColor: $r('app.color.text_color') },
  1170. ],
  1171. maskColor: Color.Transparent,
  1172. backgroundColor: $r('app.color.bg_card'),
  1173. transition: AnimationHelper.transitionInDown(555),
  1174. onAction: (index) => {
  1175. switch (index) {
  1176. case 0:
  1177. if (this.modeType === 0) {
  1178. this.showMkDialog()
  1179. } else {
  1180. ToastUtil.showToast('请切换到首页才能新建歌单!')
  1181. }
  1182. break;
  1183. case 1:
  1184. this.callFilePickerSelectFile()
  1185. break;
  1186. case 2:
  1187. this.showTips()
  1188. break;
  1189. case 3:
  1190. this.goSelectMusic()
  1191. break;
  1192. }
  1193. }
  1194. })
  1195. }
  1196. //拉起音频
  1197. goSelectMusic() {
  1198. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  1199. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  1200. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  1201. ) {
  1202. ToastUtil.showToast('暂时不支持该设备')
  1203. return
  1204. }
  1205. try {
  1206. let documentSelectOptions = new picker.DocumentSelectOptions();
  1207. documentSelectOptions.authMode = true
  1208. documentSelectOptions.multiAuthMode = true
  1209. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  1210. let documentPicker = new picker.DocumentViewPicker(this.context);
  1211. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  1212. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  1213. this.saveVideoDatas(documentSelectResult)
  1214. }
  1215. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  1216. JSON.stringify(documentSelectResult));
  1217. }).catch((err: BusinessError) => {
  1218. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  1219. });
  1220. } catch (error) {
  1221. let err: BusinessError = error as BusinessError;
  1222. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1223. }
  1224. }
  1225. async showTips() {
  1226. DialogHelper.showTipsDialog({
  1227. title: '使用提示:自动导入教程',
  1228. content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  1229. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  1230. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  1231. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  1232. onAction: (action) => {
  1233. if (action == DialogAction.TWO) {
  1234. PreferencesUtil.putSync('isFirstMusic', false)
  1235. router.pushUrl({
  1236. url: 'pages/ScanFilePage'
  1237. });
  1238. }
  1239. }
  1240. })
  1241. }
  1242. showMkDialog() {
  1243. DialogHelper.showTextInputDialog({
  1244. title: '新建歌单',
  1245. maskColor: Color.Transparent,
  1246. text: '',
  1247. transition: AnimationHelper.transitionInDown(666),
  1248. onChange: (text) => {
  1249. console.error("onChange: " + text);
  1250. },
  1251. onAction: (action, dialogId, content) => {
  1252. // ToastUtil.showToast('content = ' +content)
  1253. if (action == DialogAction.TWO) {
  1254. const newName = content
  1255. const newPath = this.currentPath + '/' + newName
  1256. FileUtil.mkdir(newPath, true).then(() => {
  1257. this.cache.delete(this.currentPath); // 删除目标路径缓存
  1258. this.getSortedFiles(this.currentPath)
  1259. }).catch((error: BusinessError) => {
  1260. console.error(error.message);
  1261. });
  1262. }
  1263. }
  1264. })
  1265. }
  1266. @State progress: number = 0;
  1267. async saveVideoDatas(uris: string[], isOpen?: boolean) {
  1268. if (ArrayUtil.isEmpty(uris)) {
  1269. return;
  1270. }
  1271. let newUris: string[] = [];
  1272. this.progress = 0
  1273. DialogHelper.showLoadingProgress({
  1274. progress: this.progress,
  1275. backCancel: false,
  1276. autoCancel: false,
  1277. loadColor: this.themeColor,
  1278. fontColor: this.themeColor
  1279. });
  1280. // 计算所有文件的总大小
  1281. let totalSize = 0;
  1282. for (let uri of uris) {
  1283. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  1284. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  1285. await fileIo.close(sourceFile.fd);
  1286. }
  1287. let totalRead = 0;
  1288. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  1289. Logger.info(TAG, 'destPath uri: ' + destPath);
  1290. for (let i = 0; i < uris.length; i++) {
  1291. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  1292. Logger.info(TAG, 'filePath uri: ' + filePath);
  1293. newUris.push(filePath);
  1294. try {
  1295. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  1296. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  1297. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  1298. const buffer = new ArrayBuffer(buffSize);
  1299. let len = await fileIo.read(sourceFile.fd, buffer);
  1300. while (len > 0) {
  1301. await fileIo.write(destFile.fd, buffer.slice(0, len));
  1302. totalRead += len;
  1303. // 计算总进度
  1304. this.progress = Math.floor((totalRead / totalSize) * 100);
  1305. DialogHelper.updateLoading('正在导入', this.progress);
  1306. len = await fileIo.read(sourceFile.fd, buffer);
  1307. }
  1308. await fileIo.close(sourceFile.fd);
  1309. await fileIo.close(destFile.fd);
  1310. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  1311. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  1312. let mediaItem: VideoItem =
  1313. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, true);
  1314. this.table.insert(mediaItem, (id: number) => {
  1315. // 删除目标路径缓存
  1316. this.cache.delete(this.currentPath);
  1317. this.getSortedFiles(this.currentPath, true, destPath, isOpen)
  1318. });
  1319. }
  1320. }
  1321. } catch (error) {
  1322. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  1323. }
  1324. }
  1325. DialogHelper.closeLoading()
  1326. this.isZero = false
  1327. // setTimeout(() => {
  1328. // // 删除目标路径缓存
  1329. // this.cache.delete(this.currentPath);
  1330. // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
  1331. // }, 500);
  1332. Logger.info(TAG, 'scan select video result:' + newUris)
  1333. }
  1334. //拉起音频
  1335. // goSelectMusic(){
  1336. //
  1337. // try {
  1338. // let audioSelectOptions = new picker.AudioSelectOptions();
  1339. // let audioPicker = new picker.AudioViewPicker(this.context);
  1340. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  1341. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  1342. // this.saveVideoDatas(audioSelectResult)
  1343. // }
  1344. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  1345. // }).catch((err: BusinessError) => {
  1346. //
  1347. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  1348. // });
  1349. // } catch (error) {
  1350. // let err: BusinessError = error as BusinessError;
  1351. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1352. // }
  1353. //
  1354. //
  1355. //
  1356. // }
  1357. goSelectImage(item: VideoItem) {
  1358. if (!item) {
  1359. return
  1360. }
  1361. let selectUris: Array<string> = [];
  1362. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  1363. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  1364. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; // 过滤选择媒体文件类型为IMAGE
  1365. photoSelectOptions.maxSelectNumber = 1; // 选择媒体文件的最大数目
  1366. photoPicker.select(photoSelectOptions).then(async (photoSelectResult: photoAccessHelper.PhotoSelectResult) => {
  1367. //用一个全局变量存储返回的uri
  1368. selectUris = photoSelectResult.photoUris;
  1369. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  1370. //使用fs.openSync接口,通过uri打开这个文件得到fd
  1371. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  1372. console.info('file fd: ' + file.fd);
  1373. let name = await MD5.digestSync(this.videoUrl)
  1374. let imagePath = this.context.filesDir + FileUtil.separator + name
  1375. imagePath = fileUri.getUriFromPath(imagePath)
  1376. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  1377. fileIo.copyFileSync(file.fd, file2.fd)
  1378. fileIo.closeSync(file);
  1379. fileIo.closeSync(file2);
  1380. if (item.filePath == this.currentSong?.filePath) {
  1381. this.cover = imagePath
  1382. }
  1383. if (item) {
  1384. item.pixelMapPath = imagePath
  1385. }
  1386. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  1387. if (success) {
  1388. this.doUpdateData()
  1389. console.log(" onecold 更新音乐封面成功,数据库已同步");
  1390. } else {
  1391. console.error(" onecold 更新音乐封面数据库失败原因: " + error);
  1392. }
  1393. });
  1394. LogUtil.debug("onecold this.cover =" + this.cover)
  1395. }).catch((err: BusinessError) => {
  1396. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  1397. })
  1398. }
  1399. // 拉起picker选择文件管理器
  1400. async callFilePickerSelectFile(): Promise<void> {
  1401. try {
  1402. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  1403. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  1404. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  1405. } else {
  1406. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  1407. }
  1408. let documentPicker = new picker.DocumentViewPicker();
  1409. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  1410. Logger.info(TAG,
  1411. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  1412. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  1413. this.saveVideoDatas(DocumentSelectResult)
  1414. }
  1415. }).catch((err: BusinessError) => {
  1416. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  1417. });
  1418. } catch (err) {
  1419. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  1420. }
  1421. }
  1422. showWarnIsDeleteFile(item: VideoItem, index: string, filePath: string) {
  1423. //操作确认类弹出框
  1424. DialogHelper.showAlertDialog({
  1425. maskColor: Color.Transparent,
  1426. content: "确定要删除这个文件吗?",
  1427. backgroundColor: Color.Grey,
  1428. transition: AnimationHelper.transitionInUp(555),
  1429. onAction: (action) => {
  1430. if (action == DialogAction.ONE) {
  1431. // ToastUtil.showToast(`您点击了取消按钮`);
  1432. } else if (action == DialogAction.TWO) {
  1433. // ToastUtil.showToast(`您点击了确认按钮`);
  1434. this.doDelete(item, index + '', filePath)
  1435. }
  1436. }
  1437. })
  1438. }
  1439. //删除单个索引index的视频
  1440. doDelete(item: VideoItem, index: string, filePath: string) {
  1441. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1442. Logger.info(TAG, 'delete filePath = ' + filePath);
  1443. if (item.type === CommonConstants.TYPE_IS_DIR) {
  1444. //旧文件删除
  1445. this.table.deleteDataForParentPath(item.filePath, () => {
  1446. FileUtil.rmdir(filePath).then(() => {
  1447. this.videoLocalList.splice(Number(index), 1)
  1448. this.deleteCache(this.currentPath)
  1449. this.getSortedFiles(this.currentPath, true)
  1450. }).catch((error: BusinessError) => {
  1451. console.error(error.message);
  1452. });
  1453. });
  1454. } else {
  1455. this.table.deleteData(item, () => {
  1456. FileUtil.unlink(filePath)
  1457. .catch((error: BusinessError) => {
  1458. console.error(error.message);
  1459. // 可以根据 error.code 判断是否为"文件不存在",如需特殊处理
  1460. })
  1461. .finally(() => {
  1462. this.videoLocalList.splice(Number(index), 1)
  1463. this.deleteCache(this.currentPath)
  1464. this.getSortedFiles(this.currentPath, true)
  1465. });
  1466. });
  1467. }
  1468. }
  1469. }
  1470. //重命名的对话框
  1471. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  1472. DialogHelper.showTextInputDialog({
  1473. title: '重命名',
  1474. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  1475. maskColor: Color.Transparent,
  1476. backgroundColor: Color.Grey,
  1477. transition: AnimationHelper.transitionInDown(666),
  1478. onChange: (text) => {
  1479. console.error("onChange: " + text);
  1480. },
  1481. onAction: (action, dialogId, content) => {
  1482. // ToastUtil.showToast('content = ' +content)
  1483. if (action == DialogAction.TWO) {
  1484. const newName = content
  1485. const newPath = this.currentPath + '/' + newName
  1486. console.log("onecold item = " + item.type);
  1487. this.doReName(index, newName, filePath, newPath, item)
  1488. }
  1489. }
  1490. })
  1491. }
  1492. //剪切 移动到另个文件夹的对话框
  1493. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1494. Logger.info('onecold showCutDialog')
  1495. let mList: Array<string> = []
  1496. let rPath = this.rootPath
  1497. if (isCurrent) {
  1498. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1499. rPath = this.currentPath
  1500. } else {
  1501. mList = Utility.getNameList(this.dirList);
  1502. rPath = this.rootPath
  1503. }
  1504. let dataBean = new BubbleBean()
  1505. dataBean.data = mList
  1506. dataBean.color = this.themeColor
  1507. dataBean.onItemClick = (i) => {
  1508. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1509. Logger.info('newPath = ' + newPath)
  1510. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  1511. ToastUtil.showToast('移动成功')
  1512. this.table.deleteData(item, () => {
  1513. });
  1514. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1515. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1516. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1517. CommonConstants.TYPE_LOCAL, true);
  1518. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1519. this.table.insert(newItem, (id: number) => {
  1520. //加入数据库
  1521. });
  1522. }
  1523. this.cache.delete(this.currentPath); // 删除原路径缓存
  1524. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1525. this.getSortedFiles(this.currentPath, true)
  1526. }).catch((error: BusinessError) => {
  1527. console.error(error.message);
  1528. });
  1529. XPopup.dismissTop()
  1530. }
  1531. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1532. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1533. popupPosition = PopupPosition.TOP
  1534. }
  1535. if (index <= 3) {
  1536. popupPosition = PopupPosition.BOTTOM
  1537. }
  1538. let pup: XPopup
  1539. if (this.isDarkMode) {
  1540. pup = XPopup.Builder()
  1541. .setPopupPosition(popupPosition)
  1542. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  1543. .setBackgroundColor(Color.Black)
  1544. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1545. .show()
  1546. } else {
  1547. pup = XPopup.Builder()
  1548. .setPopupPosition(popupPosition)
  1549. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  1550. .setBackgroundColor(Color.White)
  1551. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1552. .show()
  1553. }
  1554. }
  1555. //复制 到另个文件夹的对话框
  1556. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1557. Logger.info('onecoldv showCopyDialog')
  1558. let mList: Array<string> = []
  1559. let rPath = this.rootPath
  1560. if (isCurrent) {
  1561. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1562. rPath = this.currentPath
  1563. } else {
  1564. mList = Utility.getNameList(this.dirList);
  1565. rPath = this.rootPath
  1566. }
  1567. let dataBean = new BubbleBean()
  1568. dataBean.data = mList
  1569. dataBean.isCopy = true
  1570. dataBean.color = this.themeColor
  1571. dataBean.onItemClick = (i) => {
  1572. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1573. Logger.info('newPath = ' + newPath)
  1574. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  1575. ToastUtil.showToast('复制成功')
  1576. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1577. this.getSortedFiles(this.currentPath)
  1578. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1579. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1580. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1581. CommonConstants.TYPE_LOCAL, true);
  1582. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1583. this.table.insert(newItem, (id: number) => {
  1584. //加入数据库
  1585. });
  1586. }
  1587. }).catch((error: BusinessError) => {
  1588. console.error(error.message);
  1589. });
  1590. XPopup.dismissTop()
  1591. }
  1592. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1593. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1594. popupPosition = PopupPosition.TOP
  1595. }
  1596. if (index <= 3) {
  1597. popupPosition = PopupPosition.BOTTOM
  1598. }
  1599. let pup: XPopup
  1600. if (this.isDarkMode) {
  1601. pup = XPopup.Builder()
  1602. .setPopupPosition(popupPosition)
  1603. .atView(id)
  1604. .setMaxHeight('60%')
  1605. .setBackgroundColor(Color.Black)
  1606. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1607. .show();
  1608. } else {
  1609. pup = XPopup.Builder()
  1610. .setPopupPosition(popupPosition)
  1611. .atView(id)
  1612. .setMaxHeight('60%')
  1613. .setBackgroundColor(Color.White)
  1614. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1615. .show();
  1616. }
  1617. }
  1618. //重命名索引index的视频
  1619. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  1620. FileUtil.rename(oldPath, newPath).then(async () => {
  1621. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1622. if (info.type === CommonConstants.TYPE_IS_DIR) {
  1623. //如果是文件夹先删除源数据,再添加新数据
  1624. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  1625. if (success) {
  1626. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  1627. } else {
  1628. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  1629. }
  1630. });
  1631. this.scanDirectory(newPath)
  1632. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  1633. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  1634. if (success) {
  1635. console.log(" onecold 重命名成功,数据库已同步");
  1636. } else {
  1637. console.error(" onecold 重命名数据库失败原因: " + error);
  1638. }
  1639. });
  1640. }
  1641. let mediaItem: VideoItem =
  1642. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, true);
  1643. this.videoLocalList[index] = mediaItem;
  1644. }
  1645. this.cache.delete(this.currentPath)
  1646. this.getSortedFiles(this.currentPath, true)
  1647. }).catch((error: BusinessError) => {
  1648. console.error(error.message);
  1649. });
  1650. }
  1651. build() {
  1652. Scroll() {
  1653. Column() {
  1654. if (!this.isShowCoverHeader()) {
  1655. Column() {
  1656. Line().width('100%').height('100%')
  1657. }
  1658. .height(this.topRectHeight)
  1659. .backgroundColor(this.isCustomizeBg ? Color.Transparent :
  1660. (this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor))
  1661. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  1662. TitleBar({ model: $titleBarModel })
  1663. .id('pup_positon_music')
  1664. }
  1665. Stack() {
  1666. Column() {
  1667. XComponent({
  1668. id: 'xcomponentId',
  1669. type: 'surface',
  1670. libraryname: 'ijkplayer_napi',
  1671. controller: this.xcomponentController
  1672. })
  1673. .onLoad((event?: object) => {
  1674. if (!!event) {
  1675. this.initDelayPlay(event);
  1676. }
  1677. })
  1678. .onLoad((event?: object) => {
  1679. if (!!event) {
  1680. this.initDelayPlay(event);
  1681. }
  1682. })
  1683. .onKeyEvent((event?: KeyEvent) => {
  1684. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  1685. if (!event || event.type !== KeyType.Down) {
  1686. return;
  1687. }
  1688. //空格键 Space key controls pause/play
  1689. if (event.keyCode === KeyCode.KEYCODE_SPACE) {
  1690. this.playOrPause()
  1691. }
  1692. // Right-click to fast forward
  1693. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  1694. this.sessionFastForwardCallback(15);
  1695. }
  1696. // Left-click to rewind
  1697. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  1698. this.sessionRewindCallback(15);
  1699. }
  1700. })
  1701. .onDestroy(() => {
  1702. })
  1703. .width('100%')// .width(this.videoWidth)
  1704. .aspectRatio(this.videoAspectRatio)
  1705. }
  1706. .aspectRatio(this.videoAspectRatio)
  1707. .justifyContent(FlexAlign.Center)
  1708. .backgroundColor(Color.Transparent)
  1709. .visibility(Visibility.Hidden)
  1710. .height(CommonConstants.FULL_PERCENT)
  1711. .width(CommonConstants.FULL_PERCENT)
  1712. Stack() {
  1713. Row() {
  1714. Blank()
  1715. .layoutWeight(1)
  1716. IndexerView(
  1717. {
  1718. indexArray: DEFAULT_INDEX,
  1719. selectedIndex: this.selectedIndex,
  1720. textSize: 12,
  1721. selectedColor: "#ff419ee5",
  1722. normalColor: "#ffa0a0a0",
  1723. floatSelectedTextColor: "#ffffff",
  1724. floatSelectedViewColor: "#ff419ee5",
  1725. onIndexChanged: (index) => {
  1726. this.listScroller.scrollToIndex(index)
  1727. }
  1728. })
  1729. .width(24)
  1730. .height("50%")
  1731. }.visibility(Visibility.None)
  1732. Column() {
  1733. if (!this.isShowCoverHeader()) {
  1734. this.tabTitle()
  1735. }
  1736. if (this.isGridMusic) {
  1737. this.getGridView()
  1738. } else {
  1739. this.getListView()
  1740. }
  1741. if (this.modeType == 0) {
  1742. Column() {
  1743. Button('同步数据', { type: ButtonType.Capsule, stateEffect: true })
  1744. .width(130)
  1745. .height(50)
  1746. .margin({ top: 100, bottom: 40 })
  1747. .backgroundColor(this.themeColor)
  1748. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  1749. .onClick(() => {
  1750. this.asyncCurrentPathData()
  1751. })
  1752. }
  1753. .height(100)
  1754. .position({ top: 260 })
  1755. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  1756. .animation({ duration: 500 }),
  1757. TransitionEffect.scale({ x: 0, y: 0 })))
  1758. .justifyContent(FlexAlign.Center)
  1759. .opacity(this.isZero ? 1 : 0)
  1760. .visibility(this.isZero && !this.isFavMusic && !this.isHistory
  1761. && this.modeType === 0 ? Visibility.Visible : Visibility.None)
  1762. .animation({
  1763. duration: 500,
  1764. curve: 'ease-in-out' // 可选动画曲线
  1765. })
  1766. .width('100%')
  1767. }
  1768. }
  1769. .layoutWeight(1)
  1770. .height('100%')
  1771. }
  1772. .layoutWeight(1)
  1773. .height('100%')
  1774. Row() {
  1775. Button(this.isAllSelected ? '全不选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  1776. .width('35%')
  1777. .height(60)
  1778. .margin({ top: 10, bottom: 10, right: 6 })
  1779. .backgroundColor(this.themeColor)
  1780. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1781. .onClick(() => {
  1782. if (this.isAllSelected) {
  1783. // 全不选
  1784. this.selectedFiles = [];
  1785. } else {
  1786. // 全选
  1787. this.selectedFiles = [...this.getCurFileList()];
  1788. }
  1789. this.isAllSelected = !this.isAllSelected;
  1790. })
  1791. Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  1792. .width('35%')
  1793. .height(60)
  1794. .id('music_cut')
  1795. .margin({ top: 10, bottom: 10, right: 6 })
  1796. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1797. .backgroundColor(this.themeColor)
  1798. .onClick(() => {
  1799. this.showCutDialogForMultipleFiles(false, 'music_cut')
  1800. })
  1801. Button('移动', { type: ButtonType.Circle, stateEffect: true })
  1802. .width('35%')
  1803. .height(60)
  1804. .id('music_cut_current')
  1805. .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  1806. .margin({ top: 10, bottom: 10, right: 6 })
  1807. .backgroundColor(this.themeColor)
  1808. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1809. .onClick(() => {
  1810. this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  1811. })
  1812. Button('复制', { type: ButtonType.Circle, stateEffect: true })
  1813. .width('35%')
  1814. .height(60)
  1815. .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  1816. .margin({ top: 10, bottom: 10, right: 6 })
  1817. .backgroundColor(this.themeColor)
  1818. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1819. .onClick(() => {
  1820. this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  1821. })
  1822. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  1823. .width('35%')
  1824. .height(60)
  1825. .margin({ top: 10, bottom: 10, right: 6 })
  1826. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  1827. .backgroundColor(this.themeColor)
  1828. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1829. .onClick(() => {
  1830. this.showWarnIsDelete()
  1831. })
  1832. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  1833. .width('35%')
  1834. .height(60)
  1835. .margin({ top: 10, bottom: 10, right: 6 })
  1836. .backgroundColor(this.themeColor)
  1837. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1838. .onClick(() => {
  1839. this.selectedFiles = [];
  1840. this.isAllSelected = false
  1841. this.isMultiSelect = false
  1842. })
  1843. }
  1844. .width('100%')
  1845. .justifyContent(FlexAlign.Center)
  1846. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  1847. .opacity(this.isMultiSelect ? 1 : 0)
  1848. .animation({
  1849. duration: 666,
  1850. curve: 'ease-in-out' // 可选动画曲线
  1851. })
  1852. .position(this.isShowCoverHeader() ? { bottom: 78 }
  1853. : { bottom: this.isPhoneLan() ? 130 : 168 }) // 将 Row 固定在底部
  1854. }
  1855. .width('100%')
  1856. .height('100%')
  1857. .alignContent(Alignment.Top)
  1858. Column() {
  1859. this.PlayController()
  1860. }
  1861. .hitTestBehavior(HitTestMode.Transparent)
  1862. .position({ bottom: 0 }) // 将 Row 固定在底部
  1863. .opacity(this.barBottomOpacity)
  1864. }
  1865. .width('100%')
  1866. .height('100%')
  1867. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  1868. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  1869. .backgroundImagePosition(Alignment.Center)
  1870. .backdropBlur(this.blurValue)
  1871. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  1872. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  1873. }
  1874. }
  1875. asyncCurrentPathData() {
  1876. if (this.modeType == 0) {
  1877. workerInstance.postMessage({
  1878. code: 1,
  1879. data1: this.context,
  1880. data2: this.currentPath,
  1881. data3: this.lockPath,
  1882. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1883. });
  1884. }
  1885. }
  1886. // 处理文件选择的函数
  1887. handleFileSelection(item: VideoItem, checked: boolean) {
  1888. if (checked) {
  1889. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  1890. this.selectedFiles.push(item);
  1891. }
  1892. } else {
  1893. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  1894. if (index > -1) {
  1895. this.selectedFiles.splice(index, 1);
  1896. }
  1897. }
  1898. }
  1899. showWarnIsDelete() {
  1900. //操作确认类弹出框
  1901. DialogHelper.showAlertDialog({
  1902. content: "确定要删除这些文件吗?",
  1903. transition: AnimationHelper.transitionInUp(666),
  1904. maskColor: Color.Transparent,
  1905. backgroundColor: Color.Grey,
  1906. onAction: (action) => {
  1907. if (action == DialogAction.ONE) {
  1908. // ToastUtil.showToast(`您点击了取消按钮`);
  1909. } else if (action == DialogAction.TWO) {
  1910. // ToastUtil.showToast(`您点击了确认按钮`);
  1911. this.deleteMultipleFiles()
  1912. }
  1913. }
  1914. })
  1915. }
  1916. //多选删除文件
  1917. deleteMultipleFiles() {
  1918. if (ArrayUtil.isNotEmpty(this.selectedFiles)) {
  1919. this.selectedFiles.forEach((item) => {
  1920. Logger.info(TAG, 'delete filePath = ' + item.filePath);
  1921. if (item.type === CommonConstants.TYPE_IS_DIR) {
  1922. this.table.deleteDataForParentPath(item.filePath, () => {
  1923. FileUtil.rmdir(item.filePath).then(() => {
  1924. this.videoLocalList = this.videoLocalList.filter(v => v !== item);
  1925. this.selectedFiles = [];
  1926. this.isMultiSelect = false
  1927. this.isAllSelected = false
  1928. this.cache.delete(this.currentPath);
  1929. this.getSortedFiles(this.currentPath, true);
  1930. }).catch((error: Error) => {
  1931. console.error(error.message);
  1932. });
  1933. });
  1934. } else {
  1935. this.table.deleteData(item, () => {
  1936. FileUtil.unlink(item.filePath).catch((error: Error) => {
  1937. console.error(error.message);
  1938. }).finally(() => {
  1939. this.videoLocalList = this.videoLocalList.filter(v => v !== item);
  1940. this.selectedFiles = [];
  1941. this.isMultiSelect = false
  1942. this.isAllSelected = false
  1943. this.cache.delete(this.currentPath);
  1944. this.getSortedFiles(this.currentPath, true);
  1945. });
  1946. });
  1947. }
  1948. });
  1949. }
  1950. }
  1951. //多选移动文件
  1952. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  1953. Logger.info('onecold showCutDialogForMultipleFiles')
  1954. let mList: Array<string> = []
  1955. let rPath = this.rootPath
  1956. if (isCurrent) {
  1957. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1958. rPath = this.currentPath
  1959. } else {
  1960. mList = Utility.getNameList(this.dirList);
  1961. rPath = this.rootPath
  1962. }
  1963. let dataBean = new BubbleBean();
  1964. dataBean.data = mList;
  1965. dataBean.color = this.themeColor
  1966. dataBean.onItemClick = (i) => {
  1967. const newDirPath = rPath + '/' + mList[i];
  1968. // Logger.info('newDirPath = ' + newDirPath)
  1969. this.selectedFiles.forEach((item) => {
  1970. const newPath = newDirPath + '/' + item.fileName;
  1971. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  1972. ToastUtil.showToast('移动成功');
  1973. this.table.deleteData(item, () => {
  1974. this.cache.delete(this.currentPath); // 删除原路径缓存
  1975. this.cache.delete(newDirPath); // 删除目标路径缓存
  1976. this.getSortedFiles(this.currentPath, true);
  1977. });
  1978. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1979. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1980. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1981. CommonConstants.TYPE_LOCAL, true);
  1982. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1983. this.table.insert(newItem, (id: number) => {
  1984. //加入数据库
  1985. });
  1986. }
  1987. }).catch((error: Error) => {
  1988. console.error(error.message);
  1989. });
  1990. });
  1991. this.isMultiSelect = false
  1992. this.selectedFiles = [];
  1993. this.isAllSelected = false
  1994. XPopup.dismissTop();
  1995. };
  1996. let pup: XPopup
  1997. if (this.isDarkMode) {
  1998. pup = XPopup.Builder()
  1999. .setPopupPosition(PopupPosition.TOP)
  2000. .atView(viewId)
  2001. .setBackgroundColor(Color.Black)
  2002. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2003. .show();
  2004. } else {
  2005. pup = XPopup.Builder()
  2006. .setPopupPosition(PopupPosition.TOP)
  2007. .atView(viewId)
  2008. .setBackgroundColor(Color.White)
  2009. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2010. .show();
  2011. }
  2012. }
  2013. doFav(item: VideoItem) {
  2014. LogUtil.info('onecold doFav isFav=' + item.isFav)
  2015. let isFav = 0
  2016. if (Utility.getIsFav(this.favList, item)) {
  2017. isFav = 0
  2018. } else {
  2019. isFav = 1
  2020. }
  2021. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  2022. if (result) {
  2023. if (isFav === 1) {
  2024. ToastUtil.showToast('收藏成功');
  2025. } else {
  2026. ToastUtil.showToast('取消收藏成功');
  2027. }
  2028. this.deleteCache(this.currentPath)
  2029. this.getFavList(false)
  2030. if (this.modeType === 0 && !this.isFavMusic) {
  2031. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  2032. this.getSortedFiles(this.currentPath)
  2033. }
  2034. workerInstance.postMessage({ code: 2, data: this.context });
  2035. workerInstance.postMessage({ code: 3, data: this.context });
  2036. workerInstance.postMessage({ code: 4, data: this.context });
  2037. }
  2038. })
  2039. }
  2040. //多选复制文件
  2041. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  2042. console.log('onecold showCopyDialogForMultipleFiles');
  2043. let mList: Array<string> = []
  2044. let rPath = this.rootPath
  2045. if (isCurrent) {
  2046. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2047. rPath = this.currentPath
  2048. } else {
  2049. mList = Utility.getNameList(this.dirList);
  2050. rPath = this.rootPath
  2051. }
  2052. let dataBean = new BubbleBean();
  2053. dataBean.data = mList;
  2054. dataBean.isCopy = true
  2055. dataBean.color = this.themeColor
  2056. dataBean.onItemClick = (i) => {
  2057. const newDirPath = rPath + '/' + mList[i];
  2058. // Logger.info('newDirPath = ' + newDirPath)
  2059. this.selectedFiles.forEach((item) => {
  2060. const newPath = newDirPath + '/' + item.fileName;
  2061. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2062. ToastUtil.showToast('复制成功');
  2063. this.cache.delete(newDirPath); // 删除目标路径缓存
  2064. this.getSortedFiles(this.currentPath);
  2065. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2066. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2067. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2068. CommonConstants.TYPE_LOCAL, true);
  2069. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2070. this.table.insert(newItem, (id: number) => {
  2071. //加入数据库
  2072. });
  2073. }
  2074. }).catch((error: Error) => {
  2075. console.error(error.message);
  2076. });
  2077. });
  2078. this.isMultiSelect = false
  2079. this.selectedFiles = [];
  2080. this.isAllSelected = false
  2081. XPopup.dismissTop();
  2082. };
  2083. let pup: XPopup
  2084. if (this.isDarkMode) {
  2085. pup = XPopup.Builder()
  2086. .setPopupPosition(PopupPosition.TOP)
  2087. .atView(viewId)
  2088. .setBackgroundColor(Color.Black)
  2089. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2090. .show();
  2091. } else {
  2092. pup = XPopup.Builder()
  2093. .setPopupPosition(PopupPosition.TOP)
  2094. .atView(viewId)
  2095. .setBackgroundColor(Color.White)
  2096. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2097. .show();
  2098. }
  2099. }
  2100. @Builder
  2101. private DirItem(item: VideoItem, index?: number) {
  2102. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2103. Row() {
  2104. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  2105. $r('app.media.music_group'))
  2106. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2107. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2108. .fillColor(this.themeColor)// .fontSize(33)
  2109. .alt($r('app.media.music_group'))
  2110. .borderRadius('100%')
  2111. .clip(true)
  2112. .margin({ left: 20, top: 8, bottom: 8 })
  2113. Column() {
  2114. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  2115. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2116. .maxLines(1)// .width('88%')
  2117. .animation({
  2118. duration: 555,
  2119. curve: 'ease-in-out',
  2120. })
  2121. .transition({
  2122. type: TransitionType.Insert,
  2123. opacity: 0,
  2124. translate: { x: 160 }
  2125. })
  2126. .margin({ left: 10, right: 20 })
  2127. .fontColor($r('app.color.text_color'))
  2128. Row() {
  2129. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  2130. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2131. .padding({ top: 8 })
  2132. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  2133. .fontColor($r('app.color.text_color'))
  2134. .margin({ left: 10 })
  2135. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  2136. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2137. .padding({ top: 8 })
  2138. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2139. .fontColor($r('app.color.text_color'))
  2140. .margin({ left: 10 })
  2141. Blank()
  2142. }
  2143. }
  2144. .height('100%')
  2145. .layoutWeight(1)
  2146. .justifyContent(FlexAlign.Center)
  2147. .alignItems(HorizontalAlign.Start)
  2148. Blank()
  2149. Image($r('app.media.arrow_right'))
  2150. .height(25)
  2151. .margin({ right: 10 })
  2152. .alignSelf(ItemAlign.Center)
  2153. .id(item.filePath)
  2154. }
  2155. }
  2156. .backgroundColor(Color.Transparent)
  2157. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2158. .width('100%')
  2159. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  2160. .opacity(this.opacityItem) // 绑定透明度
  2161. }
  2162. isShowDir(dirName: string) {
  2163. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  2164. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  2165. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  2166. if (dirName === undefined) {
  2167. return true
  2168. }
  2169. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  2170. return this.isShowSimi
  2171. }
  2172. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  2173. return this.isShowFAV
  2174. }
  2175. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  2176. return this.isShowHistory
  2177. }
  2178. return true
  2179. }
  2180. @State opacityItem: number = 1; // 控制透明度的状态变量
  2181. @Builder
  2182. private MusicItem(item: VideoItem, index?: number) {
  2183. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2184. Row() {
  2185. Stack() {
  2186. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  2187. .fillColor(this.themeColor)
  2188. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2189. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2190. .alt($r('app.media.music_red'))
  2191. .borderRadius('100%')
  2192. .clip(true)
  2193. .opacity(this.opacityItem)// 绑定透明度
  2194. .margin({ left: 20 })
  2195. }
  2196. Column() {
  2197. Column() {
  2198. Text(item.name)
  2199. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2200. .maxLines(1)
  2201. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  2202. .animation({
  2203. duration: 555,
  2204. curve: 'Linear',
  2205. })
  2206. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2207. $r('app.color.text_color'))
  2208. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2209. .bindPopup(this.longItemFilePath === item.filePath, {
  2210. builder: this.MenuBuilder(item,index,item.filePath),
  2211. placement: Placement.Top,
  2212. // autoCancel: true,
  2213. mask: {color:'#33000000'},
  2214. // popupColor: Color.Yellow,
  2215. enableArrow: false,//是否显示箭头
  2216. showInSubWindow: false,
  2217. onStateChange: (e) => {
  2218. if (!e.isVisible) {
  2219. this.longItemFilePath = ''
  2220. this.tempLyricContent = ''
  2221. }
  2222. }
  2223. })
  2224. .gesture(LongPressGesture()
  2225. .onAction(async () => {
  2226. //如果是专辑和艺术家的首页,不能长按
  2227. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2228. return
  2229. //如果是我的收藏 最近播放等也不能长按
  2230. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2231. item.name === LocalMusic.STR_HISTORY_MUSIC
  2232. )
  2233. return
  2234. this.longItemFilePath = item.filePath
  2235. this.tempLyricContent = await this.getLyricContent(item)
  2236. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2237. })
  2238. .onActionEnd((event: GestureEvent) => {
  2239. })
  2240. )
  2241. Row() {
  2242. Column(){
  2243. Text(item.md5Str?.includes('Lossless')?
  2244. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  2245. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  2246. .padding({ top: 3,right:6,left:6,bottom:3 })
  2247. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2248. $r('app.color.text_color'))
  2249. .fontWeight(500)
  2250. .borderRadius(12)
  2251. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2252. .backgroundColor('#FFC107')
  2253. }
  2254. .padding({ top: 8 })
  2255. Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
  2256. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2257. .padding({ top: 8 })
  2258. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2259. $r('app.color.text_color'))
  2260. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2261. Blank()
  2262. Text(item.size)
  2263. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2264. .padding({ top: 8 })
  2265. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  2266. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2267. $r('app.color.text_color'))
  2268. .margin({ left: 10 })
  2269. }
  2270. .gesture(LongPressGesture()
  2271. .onAction(async () => {
  2272. //如果是专辑和艺术家的首页,不能长按
  2273. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2274. return
  2275. //如果是我的收藏 最近播放等也不能长按
  2276. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2277. item.name === LocalMusic.STR_HISTORY_MUSIC
  2278. )
  2279. return
  2280. this.longItemFilePath = item.filePath
  2281. this.tempLyricContent = await this.getLyricContent(item)
  2282. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2283. })
  2284. .onActionEnd((event: GestureEvent) => {
  2285. })
  2286. )
  2287. }
  2288. .height('100%')
  2289. .width('100%')
  2290. .justifyContent(FlexAlign.Center)
  2291. .alignItems(HorizontalAlign.Start)
  2292. }
  2293. .height('100%')
  2294. .margin({ left: 5 })
  2295. .layoutWeight(1)
  2296. Column() {
  2297. Checkbox({ name: 'checkbox' + index })
  2298. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  2299. .selectedColor(this.themeColor)
  2300. .shape(CheckBoxShape.CIRCLE)
  2301. .opacity(this.isMultiSelect ? 1 : 0)
  2302. .animation({
  2303. duration: 666,
  2304. curve: 'Smooth' // 可选动画曲线
  2305. })
  2306. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2307. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  2308. .margin({ left: 20, top: 8, bottom: 8 })
  2309. .width(22)
  2310. .height(22)
  2311. ImageAnimator()
  2312. .images(this.imagesF)// 动画数组
  2313. .duration(1000)// 持续
  2314. .state(this.animationState)// 动画状态
  2315. .fillMode(FillMode.Forwards)
  2316. .width(18)
  2317. .margin({ right: 20, top: 8, bottom: 8 })
  2318. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  2319. Visibility.None)
  2320. .height(18)
  2321. .iterations(-1) // 播放次数
  2322. }
  2323. }
  2324. }
  2325. .backgroundColor(Color.Transparent)
  2326. .width('100%')
  2327. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2328. }
  2329. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  2330. @Builder
  2331. tabTitle() {
  2332. Column() {
  2333. // 使用 Stack 布局来实现绝对定位效果
  2334. Stack() {
  2335. // 背景动画容器
  2336. Row() {
  2337. ForEach(this.tabs, (i: string, index) => {
  2338. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2339. Flex()
  2340. .backgroundColor(this.isDarkMode ? $r('app.color.tab_item_bg') : this.themeColor)
  2341. .borderRadius(20)
  2342. .padding(10)
  2343. .margin(6)
  2344. .width('100%')
  2345. .height('100%')
  2346. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2347. .visibility(this.modeType === index ? Visibility.Visible : Visibility.None)
  2348. .opacity(this.modeType === index ? 1 : 0)
  2349. .animation({
  2350. duration: 666,
  2351. playMode: PlayMode.Normal,
  2352. curve: 'ease-in-out'
  2353. });
  2354. }
  2355. .layoutWeight(1)
  2356. .margin({
  2357. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5,
  2358. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5, bottom: 1
  2359. });
  2360. });
  2361. }
  2362. .width('100%')
  2363. .height(50);
  2364. // 导航栏容器
  2365. Row() {
  2366. ForEach(this.tabs, (item: string, index) => {
  2367. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2368. Text(item)
  2369. .fontSize(16)
  2370. .fontColor(this.modeType === index ? Color.White : $r('app.color.text_color'))
  2371. .padding(15)
  2372. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2373. .onClick(() => {
  2374. this.modeType = index;
  2375. this.onModeChange();
  2376. });
  2377. }
  2378. .layoutWeight(1)
  2379. .stateStyles({
  2380. pressed: { opacity: 0.6 } // 按压反馈
  2381. });
  2382. });
  2383. }
  2384. .width('100%')
  2385. .height(this.topBarHeight)
  2386. .opacity(this.barOpacity)
  2387. .backgroundColor(Color.Transparent);
  2388. }
  2389. .width('100%')
  2390. .height(this.topBarHeight)
  2391. .opacity(this.barOpacity)
  2392. Line()
  2393. .width('100%')
  2394. .height(1)
  2395. .backgroundColor($r('app.color.index_background'))
  2396. .opacity(this.barOpacity)
  2397. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  2398. }
  2399. .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  2400. }
  2401. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  2402. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  2403. @State currentYear:string = ''
  2404. isShowCoverHeader() {
  2405. if (!this.isShowHeader) {
  2406. return false
  2407. }
  2408. if (this.modeType == 0) {
  2409. if (this.isHistory || this.isFavMusic) {
  2410. return true
  2411. }
  2412. if (this.currentPath != this.rootPath) {
  2413. return true
  2414. }
  2415. }
  2416. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  2417. }
  2418. @Builder
  2419. coverHeader() {
  2420. if (this.isShowCoverHeader()) {
  2421. Column() {
  2422. Stack() {
  2423. // 居中标题
  2424. Text('')
  2425. .fontSize(18)
  2426. .fontColor(Color.White)
  2427. .align(Alignment.Center)
  2428. // 左右按钮
  2429. Row() {
  2430. Image($r('app.media.left_back_white'))
  2431. .width(28)
  2432. .height(28)
  2433. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2434. .margin({ left: 12, right: 8 })
  2435. .onClick(() => {
  2436. animateTo({ duration: 555 }, () => {
  2437. this.doSwipBack()
  2438. })
  2439. })
  2440. Blank().flexGrow(1)
  2441. if (this.modeType == 0 && !this.isHistory && !this.isFavMusic) {
  2442. Image($r('app.media.add'))
  2443. .width(25)
  2444. .height(25)
  2445. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2446. .margin({ left: 8, right: 15 })
  2447. .onClick(() => {
  2448. this.showAddDialog()
  2449. })
  2450. }
  2451. }
  2452. .height(48)
  2453. .width('100%')
  2454. .alignItems(VerticalAlign.Center)
  2455. }
  2456. .height(48)
  2457. .width('100%')
  2458. Row() {
  2459. Column() {
  2460. Image(this.currentTitleCover)
  2461. .height(100)
  2462. .width(100)
  2463. .alt(this.imageLabel)
  2464. .borderRadius(8)
  2465. .clickEffect({ level: ClickEffectLevel.HEAVY })
  2466. }
  2467. .alignItems(HorizontalAlign.Start)
  2468. .margin({ left: 30, top: 3, bottom: 15 })
  2469. Column() {
  2470. Column() {
  2471. Text(this.currentTitleName)
  2472. .fontSize(16)
  2473. .maxLines(1)
  2474. .fontWeight(FontWeight.Bold)
  2475. .fontColor($r('app.color.text_color'))
  2476. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2477. if (this.modeType == 3 && ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2478. Text(`艺术家:${this.videoLocalList[0].artist}`)
  2479. .fontSize(14)
  2480. .padding({ top: 8 })
  2481. .maxLines(1)
  2482. .fontWeight(FontWeight.Bold)
  2483. .fontColor($r('app.color.text_color'))
  2484. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2485. if(this.videoLocalList[0].genre){
  2486. Text(`风格:${this.videoLocalList[0].genre}`)
  2487. .fontSize(14)
  2488. .padding({ top: 8 })
  2489. .maxLines(1)
  2490. .visibility(StrUtil.isEmpty(this.videoLocalList[0].genre)||
  2491. this.videoLocalList[0].genre.includes(this.UNKONWN)
  2492. ?Visibility.None:Visibility.Visible)
  2493. .fontWeight(FontWeight.Bold)
  2494. .fontColor($r('app.color.text_color'))
  2495. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2496. }
  2497. if(this.videoLocalList[0].year){
  2498. Text(`发行时间:${this.videoLocalList[0].year}`)
  2499. .fontSize(14)
  2500. .padding({ top: 8 })
  2501. .maxLines(1)
  2502. .visibility(StrUtil.isEmpty(this.videoLocalList[0].year)||
  2503. this.videoLocalList[0].year.includes(this.UNKONWN)
  2504. ?Visibility.None:Visibility.Visible)
  2505. .fontWeight(FontWeight.Bold)
  2506. .fontColor($r('app.color.text_color'))
  2507. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2508. }
  2509. }
  2510. if(this.modeType != 3){
  2511. Row() {
  2512. Text(`共${this.videoLocalList.length}首歌`)
  2513. .fontSize(13)
  2514. .fontWeight(FontWeight.Bold)
  2515. .padding({ top: 8 })
  2516. .fontColor($r('app.color.text_color'))
  2517. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2518. Blank()
  2519. }
  2520. }
  2521. }
  2522. .height('100%')
  2523. .width('100%')
  2524. .justifyContent(FlexAlign.Center)
  2525. .alignItems(HorizontalAlign.Start)
  2526. }
  2527. .height('100%')
  2528. .layoutWeight(1)
  2529. .margin({ left: 20 })
  2530. }
  2531. this.listViewTitle()
  2532. }
  2533. .backgroundImage(this.getCoverTitleBg())
  2534. .height(250)
  2535. .width('100%')
  2536. .backgroundImageSize({ height: '100%', width: '100%' })
  2537. .backgroundBlurStyle(this.isCustomizeBg ? BlurStyle.NONE : BlurStyle.BACKGROUND_ULTRA_THICK)
  2538. .padding({ top: this.topRectHeight, bottom: this.bottomBarHeight + 48 })
  2539. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  2540. .justifyContent(FlexAlign.SpaceBetween)
  2541. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.7, y: 0.7 }).animation({ duration: 500 }),
  2542. TransitionEffect.scale({ x: 0, y: 0 })))
  2543. } else {
  2544. this.listViewTitle()
  2545. }
  2546. }
  2547. getCoverTitleBg(): ResourceStr | image.PixelMap {
  2548. if (this.isCustomizeBg) {
  2549. return ('rgba(255,255,255,0.2)')
  2550. }
  2551. if (this.isDarkMode) {
  2552. return $r('app.color.user_center_card_background')
  2553. }
  2554. return this.currentTitleCover
  2555. }
  2556. @Builder
  2557. listViewTitle() {
  2558. Column() {
  2559. Row({ space: 8 }) {
  2560. Row({ space: 8 }) {
  2561. Image($r("app.media.hm_playlist"))
  2562. .width(25)
  2563. .margin({ left: 8 })
  2564. .fillColor(this.themeColor)
  2565. Text(`共找到${this.artistList.length}位艺术家`)
  2566. .fontColor($r('app.color.text_color'))
  2567. .fontSize(14)
  2568. .opacity(this.opacityItem)
  2569. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  2570. Text(`共找到${this.albumList.length}张专辑`)
  2571. .fontColor($r('app.color.text_color'))
  2572. .opacity(this.opacityItem)
  2573. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2574. .fontSize(14)
  2575. }
  2576. .layoutWeight(1)
  2577. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  2578. Row() {
  2579. TextInput({
  2580. placeholder: this.modeType === 2 ? '输入艺术家名称...' : '输入专辑名称...',
  2581. text: this.searchText
  2582. })
  2583. .height(35)
  2584. .onChange((value: string) => {
  2585. this.onSearchInput(value);
  2586. })
  2587. .layoutWeight(1)
  2588. Text(`取消`)
  2589. .margin({ left: 10, right: 10 })
  2590. .fontColor($r('app.color.text_color'))
  2591. .fontSize(16)
  2592. .onClick(() => {
  2593. this.isSearchMode = false
  2594. this.searchText = ''
  2595. if (this.modeType === 2) {
  2596. this.updateListData(this.artistList)
  2597. } else {
  2598. this.updateListData(this.albumList)
  2599. }
  2600. })
  2601. }
  2602. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  2603. .animation({
  2604. duration: 666,
  2605. curve: 'ease-in-out' // 可选动画曲线
  2606. })
  2607. Blank()
  2608. Image($r("app.media.search"))
  2609. .width(25)
  2610. .visibility(this.modeType === 2 || this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2611. .animation({
  2612. duration: 666,
  2613. curve: 'ease-in-out' // 可选动画曲线
  2614. })// .opacity(this.opacityItem)
  2615. .fillColor(this.themeColor)
  2616. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2617. .onClick(() => {
  2618. this.isSearchMode = true
  2619. })
  2620. Image($r("app.media.top_rank"))
  2621. .width(25)// .opacity(this.opacityItem)
  2622. .fillColor(this.themeColor)
  2623. .animation({
  2624. duration: 666,
  2625. curve: 'ease-in-out' // 可选动画曲线
  2626. })
  2627. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2628. .onClick(() => {
  2629. this.showRankDialog()
  2630. })
  2631. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  2632. .width(25)
  2633. .animation({
  2634. duration: 666,
  2635. curve: 'ease-in-out' // 可选动画曲线
  2636. })
  2637. .fillColor(this.themeColor)
  2638. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2639. .onClick(() => {
  2640. this.isGridMusic = !this.isGridMusic
  2641. })
  2642. }
  2643. .visibility(((this.modeType === 2 || this.modeType === 3) && !this.isCanBack) ? Visibility.Visible :
  2644. Visibility.None)
  2645. .width('100%')
  2646. .padding(10)
  2647. .height(50)
  2648. .border({
  2649. width: { bottom: 1 },
  2650. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  2651. })
  2652. Row({ space: 8 }) {
  2653. Row({ space: 8 }) {
  2654. Image($r("app.media.hm_play"))
  2655. .width(25)
  2656. .margin({ left: 8 })
  2657. .fillColor(this.themeColor)
  2658. Text(`播放全部`)
  2659. .fontColor($r('app.color.text_color'))
  2660. .fontSize(14)
  2661. .animation({
  2662. duration: 666,
  2663. curve: 'ease-in-out' // 可选动画曲线
  2664. })
  2665. Text(`(${Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length}首)`)
  2666. .fontColor($r('app.color.text_color'))
  2667. .fontSize(14)
  2668. .opacity(this.opacityItem)
  2669. .animation({
  2670. duration: 666,
  2671. curve: 'ease-in-out' // 可选动画曲线
  2672. })
  2673. }
  2674. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2675. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  2676. .animation({
  2677. duration: 666,
  2678. curve: 'ease-in-out' // 可选动画曲线
  2679. })
  2680. // .backgroundColor(this.isClickedPLayAll ? $r('app.color.button_click') : Color.Transparent)
  2681. .onTouch((event: TouchEvent) => {
  2682. if (event.type === TouchType.Down) {
  2683. this.isClickedPLayAll = true;
  2684. } else if (event.type === TouchType.Up || event.type === TouchType.Cancel) {
  2685. this.isClickedPLayAll = false;
  2686. }
  2687. })
  2688. .onClick(() => {
  2689. // ToastUtil.showToast('当前的手机的折叠状态 ='+DisplayUtil.getFoldStatus())
  2690. if (this.modeType === 0) {
  2691. if (ArrayUtil.isNotEmpty(this.getCurFileList())) {
  2692. this.doPlay(this.getCurFileList()[0])
  2693. }
  2694. } else {
  2695. if (ArrayUtil.isNotEmpty(this.mediaKuList)) {
  2696. this.doPlay(this.mediaKuList[0])
  2697. }
  2698. }
  2699. })
  2700. Row() {
  2701. TextInput({ placeholder: '输入名称...', text: this.searchText })
  2702. .height(35)
  2703. .onChange((value: string) => {
  2704. this.onSearchInput(value);
  2705. })
  2706. .layoutWeight(1)
  2707. Text(`取消`)
  2708. .margin({ left: 10, right: 10 })
  2709. .fontColor($r('app.color.text_color'))
  2710. .fontSize(16)
  2711. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2712. .onClick(() => {
  2713. this.isSearchMode = false
  2714. this.searchText = ''
  2715. this.updateListData(this.mediaKuList)
  2716. })
  2717. }
  2718. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  2719. .animation({
  2720. duration: 666,
  2721. curve: 'ease-in-out' // 可选动画曲线
  2722. })
  2723. Blank()
  2724. Image($r("app.media.search"))
  2725. .width(25)// .visibility(this.modeType===1?Visibility.Visible:Visibility.None)
  2726. .animation({
  2727. duration: 666,
  2728. curve: 'ease-in-out' // 可选动画曲线
  2729. })// .opacity(this.opacityItem)
  2730. .fillColor(this.themeColor)
  2731. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2732. .onClick(() => {
  2733. this.isSearchMode = true
  2734. })
  2735. Image($r("app.media.refresh"))
  2736. .fillColor(this.themeColor)
  2737. .width(25)
  2738. .visibility(this.isHistory || this.isCanBack || this.isSearchMode ? Visibility.None : Visibility.Visible)
  2739. .animation({
  2740. duration: 666,
  2741. curve: 'ease-in-out' // 可选动画曲线
  2742. })
  2743. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2744. .onClick(() => {
  2745. if (this.isFavMusic) {
  2746. this.getFavList(true)
  2747. } else {
  2748. this.deleteCache(this.currentPath)
  2749. this.getSortedFiles(this.currentPath)
  2750. }
  2751. })
  2752. Image($r("app.media.top_rank"))
  2753. .width(25)
  2754. .visibility(this.isHistory || this.isSearchMode ? Visibility.None :
  2755. Visibility.Visible)// .opacity(this.opacityItem)
  2756. .animation({
  2757. duration: 666,
  2758. curve: 'ease-in-out' // 可选动画曲线
  2759. })
  2760. .fillColor(this.themeColor)
  2761. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2762. .onClick(() => {
  2763. this.showRankDialog()
  2764. })
  2765. Image(this.isMultiSelect ? $r("app.media.cancel_multi") : $r("app.media.top_flower"))
  2766. .width(24)
  2767. .visibility(this.isHistory || this.isSearchMode ? Visibility.None : Visibility.Visible)
  2768. .animation({
  2769. duration: 666,
  2770. curve: 'ease-in-out' // 可选动画曲线
  2771. })
  2772. .fillColor(this.themeColor)
  2773. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2774. .onClick(() => {
  2775. this.isMultiSelect = !this.isMultiSelect
  2776. })
  2777. SymbolGlyph($r('sys.symbol.trash'))
  2778. .fontColor([this.themeColor])
  2779. .fontSize(25)
  2780. .effectStrategy(1)
  2781. .visibility(this.isHistory ? Visibility.Visible : Visibility.None)
  2782. .animation({
  2783. duration: 666,
  2784. curve: 'ease-in-out' // 可选动画曲线
  2785. })
  2786. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2787. .onClick(() => {
  2788. this.clearVideoHistory() //清空播放记录
  2789. })
  2790. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  2791. .width(24)
  2792. .animation({
  2793. duration: 666,
  2794. curve: 'ease-in-out' // 可选动画曲线
  2795. })
  2796. .fillColor(this.themeColor)
  2797. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2798. .onClick(() => {
  2799. this.isGridMusic = !this.isGridMusic
  2800. })
  2801. }
  2802. .width('100%')
  2803. .padding(10)
  2804. .height(50)
  2805. .visibility(this.modeType === 0 || this.modeType === 1 || this.isCanBack ? Visibility.Visible : Visibility.None)
  2806. .border({
  2807. width: { bottom: 1 },
  2808. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  2809. })
  2810. }
  2811. .visibility(this.isShowAllBar ? Visibility.Visible : Visibility.None)
  2812. }
  2813. //搜索功能的实现
  2814. @State searchText: string = ''; // 用户输入内容
  2815. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  2816. @State isSearchMode: boolean = false
  2817. // 实时搜索逻辑(带防抖)
  2818. private onSearchInput(value: string) {
  2819. this.searchText = value.trim();
  2820. let mSearchList: Array<VideoItem> = []
  2821. switch (this.modeType) {
  2822. case 0:
  2823. mSearchList = this.videoLocalList
  2824. break;
  2825. case 1:
  2826. mSearchList = this.mediaKuList
  2827. break;
  2828. case 2:
  2829. mSearchList = this.artistList
  2830. break;
  2831. case 3:
  2832. mSearchList = this.albumList
  2833. break;
  2834. }
  2835. // 新增条件判断:空输入时显示所有数据
  2836. if (this.searchText === '') {
  2837. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  2838. } else {
  2839. this.filteredList = mSearchList.filter((item: VideoItem) => {
  2840. return item.name.toLowerCase().includes(this.searchText.toLowerCase());
  2841. });
  2842. }
  2843. this.updateListData(this.filteredList);
  2844. // this.isSearchMode = false; // 根据业务需求决定是否启用
  2845. }
  2846. @State dragItem: number = -1
  2847. @State scaleItem: number = -1
  2848. @State neighborItem: number = -1
  2849. @State neighborScale: number = -1
  2850. @State offsetY: number = 0
  2851. private dragRefOffset: number = 0
  2852. private ITEM_INTV: number = 78
  2853. scaleSelect(item: number): number {
  2854. if (this.scaleItem === item) {
  2855. return 1.05
  2856. } else if (this.neighborItem === item) {
  2857. return this.neighborScale
  2858. } else {
  2859. return 1
  2860. }
  2861. }
  2862. itemMove(index: number, newIndex: number): void {
  2863. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  2864. return;
  2865. }
  2866. let tmp = this.videoLocalList.splice(index, 1);
  2867. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  2868. this.dataSource.pushArrayData(this.videoLocalList)
  2869. }
  2870. // Grid布局的开始
  2871. private dragRefOffSetX: number = 0;
  2872. private dragRefOffSetY: number = 0;
  2873. private FIX_VP_X: number = 180;
  2874. private FIX_VP_Y: number = 84;
  2875. isDraggable(index: number): boolean {
  2876. return index >= 0;
  2877. }
  2878. getRowEnd(item: number) {
  2879. if (item.toString() === '0') {
  2880. return 1;
  2881. } else {
  2882. return 0;
  2883. }
  2884. }
  2885. // [Start itemMove_start]
  2886. // itemMoveGrid(index: number, newIndex: number): void {
  2887. // if (!this.isDraggable(newIndex)) {
  2888. // return;
  2889. // }
  2890. // let tmp = this.videoLocalList.splice(index, 1);
  2891. // this.videoLocalList.splice(newIndex, 0, tmp[0]);
  2892. // // this.bigItemIndex = this.videoLocalList.findIndex((item) => item === 0);
  2893. // }
  2894. isInLeft(index: number) {
  2895. return index % 2 == 0;
  2896. }
  2897. down(index: number): void {
  2898. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  2899. return;
  2900. }
  2901. this.offsetY -= this.FIX_VP_Y;
  2902. this.dragRefOffSetY += this.FIX_VP_Y;
  2903. this.itemMove(index, index + 1);
  2904. }
  2905. up(index: number): void {
  2906. if (!this.isDraggable(index - 2)) {
  2907. return;
  2908. }
  2909. this.offsetY += this.FIX_VP_Y;
  2910. this.dragRefOffSetY -= this.FIX_VP_Y;
  2911. this.itemMove(index, index - 1);
  2912. }
  2913. left(index: number): void {
  2914. if (this.isInLeft(index)) {
  2915. return;
  2916. }
  2917. if (!this.isDraggable(index - 1)) {
  2918. return;
  2919. }
  2920. this.offsetX += this.FIX_VP_X;
  2921. this.dragRefOffSetX -= this.FIX_VP_X;
  2922. this.itemMove(index, index - 1)
  2923. }
  2924. right(index: number): void {
  2925. if (!this.isInLeft(index)) {
  2926. return;
  2927. }
  2928. if (!this.isDraggable(index + 1)) {
  2929. return;
  2930. }
  2931. this.offsetX -= this.FIX_VP_X;
  2932. this.dragRefOffSetX += this.FIX_VP_X;
  2933. this.itemMove(index, index + 1)
  2934. }
  2935. private scroller: Scroller = new Scroller();
  2936. @State startIndex: number = 0
  2937. @State endIndex: number = 0
  2938. @State scaleValue: number = 1
  2939. @State pinchValue: number = 1
  2940. layoutOptionsForHeader: GridLayoutOptions = {
  2941. regularSize: [1, 1], // 只支持[1, 1]
  2942. irregularIndexes: [0], // 索引为0的GridItem占用一行
  2943. };
  2944. @Builder
  2945. getGridView() {
  2946. Grid(this.scroller, this.layoutOptionsForHeader) {
  2947. GridItem() {
  2948. if (this.isShowCoverHeader()) {
  2949. this.coverHeader()
  2950. } else {
  2951. this.listViewTitle()
  2952. }
  2953. }
  2954. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  2955. GridItem() {
  2956. Stack({ alignContent: Alignment.Center }) {
  2957. this.MusicItemGrid(item, index)
  2958. }
  2959. }
  2960. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  2961. TransitionEffect.scale({ x: 0, y: 0 })))
  2962. .clickEffect({ level: ClickEffectLevel.LIGHT })
  2963. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  2964. .zIndex(this.dragItem === index ? 1 : 0)
  2965. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  2966. .hitTestBehavior(this.isDraggable(this.videoLocalList.indexOf(item)) ? HitTestMode.Default : HitTestMode.None)
  2967. //长按拖动代码
  2968. .gesture(
  2969. GestureGroup(GestureMode.Sequence,
  2970. LongPressGesture({ repeat: true })
  2971. .onAction(() => {
  2972. this.getUIContext().animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  2973. this.scaleItem = index;
  2974. })
  2975. })
  2976. .onActionEnd(() => {
  2977. this.getUIContext().animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  2978. this.scaleItem = -1;
  2979. })
  2980. }),
  2981. PanGesture({ fingers: 1, direction: null, distance: 0 })
  2982. .onActionStart(() => {
  2983. this.dragItem = index;
  2984. this.dragRefOffSetX = 0;
  2985. this.dragRefOffSetY = 0;
  2986. })
  2987. .onActionUpdate((event: GestureEvent) => {
  2988. this.offsetX = event.offsetX - this.dragRefOffSetX;
  2989. this.offsetY = event.offsetY - this.dragRefOffSetY;
  2990. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  2991. let index = this.videoLocalList.indexOf(item);
  2992. if (this.offsetY >= this.FIX_VP_Y / 2 && (this.offsetX <= 44 && this.offsetX >= -44)) {
  2993. this.down(index);
  2994. } else if (this.offsetY <= -this.FIX_VP_Y / 2 && (this.offsetX <= 44 && this.offsetX >= -44)) {
  2995. this.up(index);
  2996. } else if (this.offsetX >= this.FIX_VP_X / 2 && (this.offsetY <= 50 && this.offsetY >= -50)) {
  2997. this.right(index);
  2998. } else if (this.offsetX <= -this.FIX_VP_Y / 2 && (this.offsetY <= 50 && this.offsetY >= -50)) {
  2999. this.left(index);
  3000. }
  3001. })
  3002. // if (this.offsetY > this.FIX_VP_Y * 0.7) {
  3003. // this.scroller.scrollToIndex(index + 10, true,ScrollAlign.CENTER);
  3004. // }
  3005. })
  3006. .onActionEnd(() => {
  3007. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3008. this.dragItem = -1;
  3009. })
  3010. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150 }, () => {
  3011. this.scaleItem = -1;
  3012. })
  3013. })
  3014. )
  3015. .onCancel(() => {
  3016. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3017. this.dragItem = -1;
  3018. })
  3019. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150 }, () => {
  3020. this.scaleItem = -1;
  3021. })
  3022. })
  3023. )
  3024. // [End gesture_start]
  3025. // [EndExclude GridItem_start]
  3026. }, (item: VideoItem) => item.filePath)
  3027. }
  3028. .width(this.isShowHeader ? '100%' : '94%')
  3029. .height('100%')
  3030. .editMode(true)
  3031. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3032. .animation({ duration: 500, curve: Curve.Ease }))
  3033. // .margin({ bottom: this.isCoverOpacity() ? 80 : 175 })
  3034. .margin({
  3035. bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? 45 : 80)
  3036. : (this.isShowCoverHeader() ? 95 : 178)
  3037. })
  3038. .layoutWeight(1)
  3039. .scrollBar(BarState.Off)
  3040. .supportAnimation(true)
  3041. .cachedCount(3)
  3042. // .columnsTemplate('1fr '.repeat(this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM ? 2 : 5))
  3043. .columnsTemplate(
  3044. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  3045. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  3046. )
  3047. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  3048. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  3049. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  3050. .gesture(PinchGesture({ fingers: 2 })
  3051. .onActionEnd((event: GestureEvent) => {
  3052. this.setGridTwoFingers()
  3053. })
  3054. .onActionUpdate(e => {
  3055. this.scaleValue = this.pinchValue * e.scale
  3056. })
  3057. .onActionStart(e => {
  3058. }))
  3059. .enableScrollInteraction(true)
  3060. // 滚轴滑动,记录下滑动时的起始位置和终点位置
  3061. .onScrollIndex((start: number, end: number) => {
  3062. this.startIndex = start
  3063. this.endIndex = end
  3064. })
  3065. .onScrollFrameBegin((offset: number) => {
  3066. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  3067. // if (this.isPhoneLan()) {
  3068. // this.setBarHeightHide(offset)
  3069. // } else
  3070. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  3071. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  3072. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  3073. if (this.isScrollHide) {
  3074. this.setBarHeightHide2(offset)
  3075. } else {
  3076. this.setBarHeightNormal()
  3077. }
  3078. } else {
  3079. this.setBarHeightHide(offset)
  3080. }
  3081. return { offsetRemain: offset };
  3082. })
  3083. //允许拖拽音乐和视频到List或Grid上自动导入视频
  3084. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3085. .onDrop((event?: DragEvent) => {
  3086. try {
  3087. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3088. if (dragData !== undefined) {
  3089. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3090. if (records.length > 0) {
  3091. for (let i = 0; i < records.length; i++) {
  3092. let types = records[i].getTypes();
  3093. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3094. const fileUriUds =
  3095. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3096. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3097. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3098. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3099. this.targetFile = fileUriUds.oriUri;
  3100. this.saveVideoDatas([this.targetFile])
  3101. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3102. }
  3103. }
  3104. }
  3105. } else {
  3106. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3107. }
  3108. } else {
  3109. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3110. }
  3111. } catch (error) {
  3112. const err = error as BusinessError;
  3113. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3114. }
  3115. })
  3116. }
  3117. @State targetFile: string = '';
  3118. setGridTwoFingers() {
  3119. this.pinchValue = this.scaleValue;
  3120. Logger.info('this.pinchValue = ' + this.pinchValue);
  3121. if (this.pinchValue >= 1) {
  3122. this.twoFingerType++
  3123. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  3124. if (this.twoFingerType > 3) {
  3125. this.twoFingerType = 3
  3126. }
  3127. } else {
  3128. this.twoFingerType--
  3129. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  3130. if (this.twoFingerType < 1) {
  3131. this.twoFingerType = 3
  3132. this.isGridMusic = false
  3133. }
  3134. }
  3135. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  3136. this.pinchValue = 1;
  3137. this.scaleValue = 1;
  3138. }
  3139. @State longItemFilePath: string = ''
  3140. @State tempLyricContent: string = ''
  3141. @Builder
  3142. private MusicItemGrid(item: VideoItem, index: number) {
  3143. Button({ type: ButtonType.Normal, stateEffect: false }) {
  3144. Stack() {
  3145. Column() {
  3146. Image(StrUtil.isEmpty(item.pixelMapPath) ? Utility.getMusisBg2(index) : item.pixelMapPath)
  3147. .height(this.getGridHeight())
  3148. .width(this.getGridWight())
  3149. .alt($r('app.media.ic_avatar6'))
  3150. .clip(true)
  3151. .borderRadius({
  3152. topLeft: 12,
  3153. topRight: 12,
  3154. bottomLeft: 0,
  3155. bottomRight: 0
  3156. })
  3157. .draggable(false)
  3158. .opacity(this.opacityItem)// 绑定透明度
  3159. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3160. // .animation({ duration: 500, curve: Curve.Ease }))
  3161. .animation({
  3162. duration: 666,
  3163. curve: 'ease-in-out' // 可选动画曲线
  3164. })
  3165. .margin({
  3166. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3167. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3168. })
  3169. Column() {
  3170. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  3171. .fontSize(this.twoFingerType == 1 ? 14 : this.twoFingerType == 2 ? 16 : 18)
  3172. .maxLines(1)
  3173. .fontWeight(FontWeight.Bold)
  3174. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3175. .animation({
  3176. duration: 555,
  3177. curve: 'Linear',
  3178. })
  3179. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3180. $r('app.color.text_color'))
  3181. Column() {
  3182. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  3183. .fontSize(11)
  3184. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  3185. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3186. .fontColor($r('app.color.text_color'))
  3187. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  3188. .fontSize(11)
  3189. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  3190. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3191. .fontColor($r('app.color.text_color'))
  3192. Row(){
  3193. Column(){
  3194. Text(item.md5Str?.includes('Lossless')?
  3195. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  3196. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  3197. .padding({ top: 3,right:6,left:6,bottom:3 })
  3198. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3199. $r('app.color.text_color'))
  3200. .fontWeight(500)
  3201. .borderRadius(12)
  3202. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  3203. .backgroundColor('#FFC107')
  3204. }
  3205. .margin({ top: 2 ,right:6})
  3206. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  3207. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  3208. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  3209. .fontSize(11)
  3210. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  3211. .maxLines(1)
  3212. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3213. .margin({ top: 2 ,right:18})
  3214. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  3215. || item.type == CommonConstants.TYPE_IS_ALBUM
  3216. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3217. .fontWeight(FontWeight.Medium)
  3218. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3219. $r('app.color.text_color'))
  3220. }
  3221. }
  3222. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  3223. }
  3224. .bindPopup(this.longItemFilePath === item.filePath, {
  3225. builder: this.MenuBuilder(item, index, item.filePath),
  3226. placement: Placement.Top,
  3227. // autoCancel: true,
  3228. mask: { color: '#33000000' },
  3229. // popupColor: Color.Yellow,
  3230. enableArrow: false, //是否显示箭头
  3231. showInSubWindow: false,
  3232. onStateChange: (e) => {
  3233. if (!e.isVisible) {
  3234. this.longItemFilePath = ''
  3235. this.tempLyricContent = ''
  3236. }
  3237. }
  3238. })
  3239. .gesture(LongPressGesture()
  3240. .onAction(async () => {
  3241. //如果是专辑和艺术家的首页,不能长按
  3242. if ((this.modeType === 2 || this.modeType == 3) && !this.isCanBack) {
  3243. return
  3244. }
  3245. //如果是我的收藏 最近播放等也不能长按
  3246. if (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3247. item.name === LocalMusic.STR_HISTORY_MUSIC
  3248. ) {
  3249. return
  3250. }
  3251. this.longItemFilePath = item.filePath
  3252. this.tempLyricContent = await this.getLyricContent(item)
  3253. LogUtil.info('长按this.tempLyricContent = ' + this.tempLyricContent)
  3254. })
  3255. .onActionEnd((event: GestureEvent) => {
  3256. })
  3257. )
  3258. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 55 : 42)
  3259. .width(this.getGridWight())
  3260. .justifyContent(FlexAlign.Center)
  3261. .margin({
  3262. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3263. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3264. })
  3265. }
  3266. .width(this.getGridWight())
  3267. .borderRadius(12)
  3268. .backgroundImage(item.pixelMapPath)
  3269. .backgroundImageSize({ height: '100%', width: '100%' })
  3270. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  3271. .animation({ curve: Curve.Sharp, duration: 300 })
  3272. Checkbox({ name: 'checkbox' + index })
  3273. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  3274. .selectedColor(this.themeColor)
  3275. .shape(CheckBoxShape.CIRCLE)
  3276. .opacity(this.isMultiSelect ? 1 : 0)
  3277. .animation({
  3278. duration: 666,
  3279. curve: 'Smooth' // 可选动画曲线
  3280. })
  3281. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  3282. Visibility.None)
  3283. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  3284. .margin({ left: 20, top: 8, bottom: 8 })
  3285. .width(38)
  3286. .height(38)
  3287. }
  3288. }
  3289. .backgroundColor(Color.Transparent)
  3290. .width('100%')
  3291. .padding({ top: 15 })
  3292. .height(this.getGridAllHeight())
  3293. .onClick(() => {
  3294. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  3295. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3296. this.handleFileSelection(item, !isChecked);
  3297. } else {
  3298. this.doPlay(item, index)
  3299. }
  3300. })
  3301. }
  3302. getGridAllHeight() {
  3303. let heightG = 222
  3304. switch (this.twoFingerType) {
  3305. case 1:
  3306. heightG = 118
  3307. break;
  3308. case 2:
  3309. heightG = 168
  3310. break;
  3311. case 3:
  3312. heightG = 222
  3313. break;
  3314. }
  3315. return heightG
  3316. }
  3317. getGridHeight() {
  3318. let heightG = 150
  3319. switch (this.twoFingerType) {
  3320. case 1:
  3321. heightG = 55
  3322. break;
  3323. case 2:
  3324. heightG = 100
  3325. break;
  3326. case 3:
  3327. heightG = 150
  3328. break;
  3329. }
  3330. return heightG
  3331. }
  3332. getGridWight() {
  3333. let wightG = 158
  3334. switch (this.twoFingerType) {
  3335. case 1:
  3336. wightG = 80
  3337. break;
  3338. case 2:
  3339. wightG = 110
  3340. break;
  3341. case 3:
  3342. wightG = 158
  3343. break;
  3344. }
  3345. return wightG
  3346. }
  3347. @State isShowDetail:boolean = false
  3348. @Builder
  3349. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  3350. Scroll() {
  3351. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  3352. Menu() {
  3353. MenuItem({
  3354. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  3355. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  3356. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  3357. })
  3358. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3359. .onClick(() => {
  3360. if (item) {
  3361. this.doFav(item)
  3362. }
  3363. this.longItemFilePath = ''
  3364. })
  3365. MenuItem({
  3366. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  3367. content: '下一首播放'
  3368. })
  3369. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3370. .onClick(() => {
  3371. this.addToNextPlay(item);
  3372. this.longItemFilePath = ''
  3373. })
  3374. MenuItem({
  3375. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  3376. content: '编辑信息'
  3377. })
  3378. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  3379. height: this.isCoverOpacity() ? '95%' : '88%',
  3380. dragBar: true,
  3381. showClose: true,
  3382. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3383. title: { title: '编辑信息' }
  3384. })
  3385. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3386. .onClick(() => {
  3387. this.isShowEdit = !this.isShowEdit;
  3388. })
  3389. MenuItem({
  3390. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  3391. content: $r('app.string.rename')
  3392. })
  3393. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  3394. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3395. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  3396. .onClick(() => {
  3397. this.showReNameDialog(item, index + '', filePath)
  3398. this.longItemFilePath = ''
  3399. })
  3400. MenuItem({
  3401. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  3402. content: $r('app.string.delete')
  3403. })
  3404. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  3405. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3406. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  3407. .onClick(() => {
  3408. this.showWarnIsDeleteFile(item, index + '', filePath)
  3409. this.longItemFilePath = ''
  3410. })
  3411. MenuItem({
  3412. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  3413. content: $r('app.string.detail')
  3414. })
  3415. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  3416. height:this.isCoverOpacity()?'95%': '95%',
  3417. dragBar: true,
  3418. showClose: true,
  3419. blurStyle:BlurStyle.Thin,
  3420. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3421. backgroundColor:Color.Transparent,
  3422. title: { title: '详情信息' }
  3423. })
  3424. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3425. .onClick(() => {
  3426. this.isShowDetail = !this.isShowDetail
  3427. })
  3428. MenuItem({
  3429. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  3430. content: $r('app.string.share')
  3431. })
  3432. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3433. .onClick(() => {
  3434. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  3435. this.longItemFilePath = ''
  3436. })
  3437. }
  3438. .font({ size: 15, weight: FontWeight.Normal })
  3439. }
  3440. .width(180)
  3441. }
  3442. .height(item.type === CommonConstants.TYPE_IS_DIR ? 150 : 400)
  3443. }
  3444. private listMaxScrollOffsetY: number = 0
  3445. @State selectedIndex: number = -1
  3446. setlistTwoFingers() {
  3447. this.pinchValue = this.scaleValue;
  3448. Logger.info('this.pinchValue = ' + this.pinchValue);
  3449. if (this.pinchValue >= 1) {
  3450. this.twoFingerType++
  3451. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  3452. if (this.twoFingerType > 3) {
  3453. this.twoFingerType = 1
  3454. this.isGridMusic = true
  3455. }
  3456. } else {
  3457. this.twoFingerType--
  3458. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  3459. if (this.twoFingerType < 1) {
  3460. this.twoFingerType = 1
  3461. }
  3462. }
  3463. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  3464. this.pinchValue = 1;
  3465. this.scaleValue = 1;
  3466. }
  3467. @Builder
  3468. getListView() {
  3469. List({ scroller: this.listScroller }) {
  3470. ListItemGroup({ header: this.coverHeader() }) {
  3471. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3472. ListItem() {
  3473. Column() {
  3474. if (item.type === CommonConstants.TYPE_IS_DIR
  3475. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  3476. this.DirItem(item, index)
  3477. } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
  3478. } else {
  3479. this.MusicItem(item, index)
  3480. }
  3481. }
  3482. .shadow(this.scaleItem === index ? {
  3483. radius: 70,
  3484. color: '#15000000',
  3485. offsetX: 0,
  3486. offsetY: 0
  3487. } :
  3488. {
  3489. radius: 0,
  3490. color: '#15000000',
  3491. offsetX: 0,
  3492. offsetY: 0
  3493. })
  3494. .animation({ curve: Curve.Sharp, duration: 300 })
  3495. }
  3496. // .transition(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }))
  3497. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  3498. .animation({ duration: 500 }),
  3499. TransitionEffect.scale({ x: 0, y: 0 })))
  3500. .clickEffect({ level: ClickEffectLevel.LIGHT })
  3501. .swipeAction((
  3502. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  3503. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  3504. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath) } : {}) //左滑
  3505. .onClick(() => {
  3506. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  3507. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3508. this.handleFileSelection(item, !isChecked);
  3509. } else {
  3510. this.doPlay(item, index)
  3511. }
  3512. })
  3513. //拖动List关键代码开始
  3514. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  3515. .zIndex(this.dragItem === index ? 1 : 0)
  3516. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  3517. .gesture(
  3518. GestureGroup(GestureMode.Sequence,
  3519. LongPressGesture({ repeat: true })
  3520. .onAction((event?: GestureEvent) => {
  3521. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3522. this.scaleItem = index
  3523. })
  3524. })
  3525. .onActionEnd(() => {
  3526. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3527. this.scaleItem = -1
  3528. })
  3529. }),
  3530. PanGesture({ fingers: 1, direction: null, distance: 0 })
  3531. .onActionStart(() => {
  3532. this.dragItem = index // 记录当前拖动项索引
  3533. this.dragRefOffset = 0 // 重置偏移基准
  3534. })
  3535. .onActionUpdate((event: GestureEvent) => {
  3536. this.offsetY = event.offsetY - this.dragRefOffset;
  3537. this.neighborItem = -1;
  3538. let indexA = this.videoLocalList.indexOf(item);
  3539. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  3540. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  3541. let value: number = 0;
  3542. if (this.offsetY < 0) {
  3543. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  3544. this.neighborItem = indexA - 1;
  3545. this.neighborScale = 1 - value / 20;
  3546. } else if (this.offsetY > 0) {
  3547. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  3548. this.neighborItem = indexA + 1;
  3549. this.neighborScale = 1 - value / 20;
  3550. }
  3551. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  3552. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3553. this.offsetY -= this.ITEM_INTV;
  3554. this.dragRefOffset += this.ITEM_INTV;
  3555. this.itemMove(indexA, indexA + 1);
  3556. });
  3557. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  3558. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3559. this.offsetY += this.ITEM_INTV;
  3560. this.dragRefOffset -= this.ITEM_INTV;
  3561. this.itemMove(indexA, indexA - 1);
  3562. });
  3563. }
  3564. let curListOffset = this.listScroller.currentOffset()
  3565. // 获取手指信息
  3566. let fingerInfo = event.fingerList[0]
  3567. let clickPercentY =
  3568. (fingerInfo.globalY - Number(this.listArea.globalPosition.y)) / Number(this.listArea.height)
  3569. if (clickPercentY > 0.8 && !this.listScroller.isAtEnd()) {
  3570. let scrollVelocity = clickPercentY > 0.9 ? 4 : 2
  3571. if (this.listMaxScrollOffsetY - curListOffset.yOffset > scrollVelocity + 5) {
  3572. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset += scrollVelocity })
  3573. }
  3574. } else if (clickPercentY < 0.2 && curListOffset.yOffset >= 0) {
  3575. let scrollVelocity = clickPercentY < 0.1 ? 4 : 2
  3576. if (curListOffset.yOffset > scrollVelocity + 5) {
  3577. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset -= scrollVelocity })
  3578. }
  3579. }
  3580. })
  3581. .onActionEnd((event: GestureEvent) => {
  3582. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3583. this.dragItem = -1
  3584. this.neighborItem = -1
  3585. })
  3586. animateTo({
  3587. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  3588. }, () => {
  3589. this.scaleItem = -1
  3590. })
  3591. })
  3592. )
  3593. .onCancel(() => {
  3594. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3595. this.dragItem = -1
  3596. this.neighborItem = -1
  3597. })
  3598. animateTo({
  3599. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  3600. }, () => {
  3601. this.scaleItem = -1
  3602. })
  3603. })
  3604. ) //拖动List关键代码结束
  3605. }, (item: VideoItem) => item.filePath)
  3606. }
  3607. }
  3608. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  3609. .gesture(PinchGesture({ fingers: 2 })
  3610. .onActionEnd((event: GestureEvent) => {
  3611. this.setlistTwoFingers()
  3612. })
  3613. .onActionUpdate(e => {
  3614. this.scaleValue = this.pinchValue * e.scale
  3615. })
  3616. .onActionStart(e => {
  3617. }))
  3618. // .divider({ strokeWidth: 1, color: this.isDarkMode? '#333333':'#ffe9f0f0' })
  3619. .margin({
  3620. bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? 25 : 80)
  3621. : (this.isShowCoverHeader() ? 85 : this.isHiCarSmall()?140:175)
  3622. })
  3623. .cachedCount(6)
  3624. .borderRadius(20)
  3625. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  3626. TransitionEffect.scale({ x: 0, y: 0 })))
  3627. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3628. // .animation({ duration: 500, curve: Curve.Ease }))
  3629. .layoutWeight(1)
  3630. .onScrollIndex((start) => {
  3631. this.selectedIndex = start
  3632. })
  3633. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  3634. .lanes(
  3635. new BreakpointType<number>({
  3636. sm: 1,
  3637. md: 2,
  3638. lg: 2,
  3639. xl: 3,
  3640. xxl: 4
  3641. }).getValue(this.currentBreakpoint),
  3642. new BreakpointType<number>({
  3643. sm: 0,
  3644. md: 12,
  3645. lg: 12,
  3646. xl: 16,
  3647. xxl: 20
  3648. }).getValue(this.currentBreakpoint)
  3649. )
  3650. .onAreaChange((oldValue: Area, newValue: Area) => {
  3651. this.listArea = newValue
  3652. if (this.twoFingerType == 3) {
  3653. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  3654. } else if (this.twoFingerType == 2) {
  3655. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  3656. } else if (this.twoFingerType == 1) {
  3657. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  3658. }
  3659. })
  3660. .onScrollFrameBegin((offset: number) => {
  3661. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  3662. // if (this.isPhoneLan()) {
  3663. // this.setBarHeightHide(offset)
  3664. // } else
  3665. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  3666. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  3667. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  3668. if (this.isScrollHide) {
  3669. this.setBarHeightHide2(offset)
  3670. } else {
  3671. this.setBarHeightNormal()
  3672. }
  3673. } else {
  3674. this.setBarHeightHide(offset)
  3675. }
  3676. return { offsetRemain: offset };
  3677. })
  3678. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  3679. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3680. .onDrop((event?: DragEvent) => {
  3681. try {
  3682. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3683. if (dragData !== undefined) {
  3684. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3685. if (records.length > 0) {
  3686. for (let i = 0; i < records.length; i++) {
  3687. let types = records[i].getTypes();
  3688. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3689. const fileUriUds =
  3690. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3691. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3692. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3693. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3694. this.targetFile = fileUriUds.oriUri;
  3695. this.saveVideoDatas([this.targetFile])
  3696. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3697. }
  3698. }
  3699. }
  3700. } else {
  3701. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3702. }
  3703. } else {
  3704. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3705. }
  3706. } catch (error) {
  3707. const err = error as BusinessError;
  3708. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3709. }
  3710. })
  3711. }
  3712. setBarHeightNormal() {
  3713. this.hideDone = false;
  3714. this.getUIContext().animateTo({
  3715. duration: 300
  3716. }, () => {
  3717. this.bottomBarHeight = 55 + 0;
  3718. this.topBarHeight = 50 + 0;
  3719. this.barOpacity = 1;
  3720. this.barBottomOpacity = 1
  3721. this.currentYOffset = 0;
  3722. this.isHiding = false;
  3723. });
  3724. }
  3725. setBarHeightHide(offset: number) {
  3726. if (offset > 0 && !this.hideDone) {
  3727. this.currentYOffset += offset;
  3728. if (this.currentYOffset <= 100) {
  3729. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  3730. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  3731. this.barOpacity = 1 - this.currentYOffset / 100;
  3732. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  3733. } else {
  3734. this.topBarHeight = 0;
  3735. this.bottomBarHeight = 0;
  3736. this.barBottomOpacity = 0
  3737. this.barOpacity = 0;
  3738. this.hideDone = true;
  3739. }
  3740. this.isHiding = true;
  3741. }
  3742. if (offset < 0 && this.isHiding) {
  3743. this.hideDone = false;
  3744. this.getUIContext().animateTo({
  3745. duration: 300
  3746. }, () => {
  3747. this.bottomBarHeight = 55 + 0;
  3748. this.topBarHeight = 50 + 0;
  3749. this.barOpacity = 1;
  3750. this.barBottomOpacity = 1
  3751. this.currentYOffset = 0;
  3752. this.isHiding = false;
  3753. });
  3754. }
  3755. }
  3756. //这个方法没隐藏bottomBar,只隐藏topbar
  3757. setBarHeightHide2(offset: number) {
  3758. if (offset > 0 && !this.hideDone) {
  3759. this.currentYOffset += offset;
  3760. if (this.currentYOffset <= 100) {
  3761. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  3762. this.barOpacity = 1 - this.currentYOffset / 100;
  3763. } else {
  3764. this.topBarHeight = 0;
  3765. this.barOpacity = 0;
  3766. this.hideDone = true;
  3767. }
  3768. this.isHiding = true;
  3769. }
  3770. if (offset < 0 && this.isHiding) {
  3771. this.hideDone = false;
  3772. this.getUIContext().animateTo({
  3773. duration: 300
  3774. }, () => {
  3775. this.topBarHeight = 50 + 0;
  3776. this.barOpacity = 1;
  3777. this.currentYOffset = 0;
  3778. this.isHiding = false;
  3779. });
  3780. }
  3781. }
  3782. private doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean) {
  3783. switch (item.type) {
  3784. case CommonConstants.TYPE_IS_DIR:
  3785. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  3786. let offsetB = 0
  3787. if (this.isGridMusic) {
  3788. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  3789. let cur = this.scroller.currentOffset()
  3790. if (cur && typeof cur.yOffset === 'number') {
  3791. offsetB = cur.yOffset
  3792. }
  3793. }
  3794. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  3795. } else {
  3796. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  3797. let cur = this.listScroller.currentOffset()
  3798. if (cur && typeof cur.yOffset === 'number') {
  3799. offsetB = cur.yOffset
  3800. }
  3801. }
  3802. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  3803. }
  3804. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  3805. this.showVerifyDialog()
  3806. this.currentTitleName = '私密音频'
  3807. this.currentTitleCover = $r('app.media.ic_avatar5')
  3808. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  3809. this.titleBarModel.setTitleName('最近播放')
  3810. this.currentTitleCover = $r('app.media.ic_avatar2')
  3811. this.currentTitleName = '最近播放'
  3812. //加载动画效果
  3813. this.updateListData(this.historyList, true)
  3814. // this.videoLocalList = this.historyList
  3815. if (ArrayUtil.isEmpty(this.historyList)) {
  3816. ToastUtil.showToast('最近播放记录空空如也')
  3817. } else {
  3818. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  3819. }
  3820. this.isHistory = true
  3821. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3822. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  3823. this.titleBarModel.setTitleName('我的收藏')
  3824. this.currentTitleName = '我的收藏'
  3825. this.currentTitleCover = $r('app.media.ic_avatar1')
  3826. //加载动画效果
  3827. this.updateListData(this.favList)
  3828. if (ArrayUtil.isEmpty(this.favList)) {
  3829. ToastUtil.showToast('无音乐收藏记录')
  3830. } else {
  3831. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  3832. }
  3833. this.isFavMusic = true
  3834. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3835. } else {
  3836. this.currentTitleName = item.name
  3837. this.currentPath = item.filePath
  3838. this.currentTitleCover = $r('app.media.ic_avatar5')
  3839. this.getSortedFiles(this.currentPath)
  3840. }
  3841. //进入歌单的时候的滚动位置在顶部
  3842. if (this.isGridMusic) {
  3843. this.scroller.scrollToIndex(0)
  3844. }
  3845. setTimeout(() => {
  3846. if (this.modeType == 0) {
  3847. if (!this.isGridMusic) {
  3848. this.listScroller.scrollToIndex(0)
  3849. }
  3850. }
  3851. }, 200)
  3852. break;
  3853. case CommonConstants.TYPE_IS_ARTIST:
  3854. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  3855. let offsetA = 0
  3856. if (this.isGridMusic) {
  3857. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  3858. let cur = this.scroller.currentOffset()
  3859. if (cur && typeof cur.yOffset === 'number') {
  3860. offsetA = cur.yOffset
  3861. }
  3862. }
  3863. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  3864. } else {
  3865. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  3866. let cur = this.listScroller.currentOffset()
  3867. if (cur && typeof cur.yOffset === 'number') {
  3868. offsetA = cur.yOffset
  3869. }
  3870. }
  3871. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  3872. }
  3873. let mList = this.artistMap.get(item.name)
  3874. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  3875. Utility.doSortListAscending(mList)
  3876. this.isCanBack = true
  3877. this.titleBarModel.setTitleName(item.name)
  3878. this.currentTitleName = '艺术家:' + item.name
  3879. if (item.pixelMapPath) {
  3880. this.currentTitleCover = item.pixelMapPath
  3881. }
  3882. this.updateListData(mList)
  3883. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3884. }
  3885. //进入歌单的时候的滚动位置在顶部
  3886. if (this.isGridMusic) {
  3887. this.scroller.scrollToIndex(0)
  3888. }
  3889. break;
  3890. case CommonConstants.TYPE_IS_ALBUM:
  3891. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  3892. let offset = 0
  3893. if (this.isGridMusic) {
  3894. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  3895. let cur = this.scroller.currentOffset()
  3896. if (cur && typeof cur.yOffset === 'number') {
  3897. offset = cur.yOffset
  3898. }
  3899. }
  3900. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  3901. } else {
  3902. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  3903. let cur = this.listScroller.currentOffset()
  3904. if (cur && typeof cur.yOffset === 'number') {
  3905. offset = cur.yOffset
  3906. }
  3907. }
  3908. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  3909. }
  3910. let albumList = this.albumMap.get(item.name)
  3911. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  3912. Utility.doSortListAscending(albumList)
  3913. this.isCanBack = true
  3914. this.titleBarModel.setTitleName(item.name)
  3915. this.currentTitleName = '专辑:' + item.name
  3916. this.currentYear = '发行时间:' + albumList[0].year
  3917. if (item.pixelMapPath) {
  3918. this.currentTitleCover = item.pixelMapPath
  3919. }
  3920. this.updateListData(albumList)
  3921. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3922. this.mScrollMap.set(item.name, this.selectedIndex)
  3923. }
  3924. break;
  3925. case CommonConstants.TYPE_IS_CSJAD:
  3926. return
  3927. break;
  3928. case CommonConstants.TYPE_LOCAL:
  3929. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  3930. this.stop();
  3931. }
  3932. if (isFromSonPlayList) { //点击来自右下角的播放列表
  3933. this.currentSong = item
  3934. if (index !== undefined) {
  3935. this.curIndex = index
  3936. }
  3937. } else {
  3938. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  3939. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  3940. this.songList = globalVideoList
  3941. this.sonDataSource.pushArrayData(this.songList)
  3942. this.currentSong = globalVideoList[this.curIndex]
  3943. }
  3944. this.videoUrl = this.currentSong.filePath
  3945. this.name = this.currentSong.name
  3946. this.cover = this.currentSong.pixelMapPath
  3947. this.artist = this.currentSong.artist
  3948. LogUtil.info('this.currentSong.duration =' + this.currentSong.duration)
  3949. LogUtil.info('this.currentSong.sampleRate =' + this.currentSong.sampleRate)
  3950. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  3951. this.startPlayOrResumePlay()
  3952. break;
  3953. }
  3954. }
  3955. @Builder
  3956. PlayController() {
  3957. Column() {
  3958. Line().width('100%').height(1).backgroundColor($r('app.color.index_background'))
  3959. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  3960. Row() {
  3961. Row() {
  3962. RotatingCover({ songLabel: this.currentSong?.pixelMapPath })
  3963. Column() {
  3964. Text(this.currentSong?.name)
  3965. .fontSize(16)
  3966. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3967. .maxLines(1)
  3968. .fontColor($r('app.color.text_color'))
  3969. .fontWeight(500)
  3970. Row() {
  3971. Text(this.currentSong?.artist)
  3972. .margin({ top: 2 })
  3973. .fontSize(13)
  3974. .fontColor($r('app.color.text_color'))
  3975. }
  3976. }
  3977. .alignItems(HorizontalAlign.Start)
  3978. .margin({ right: 22 })
  3979. }
  3980. .padding({ right: 18 })
  3981. .layoutWeight(1)
  3982. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3983. .onClick(() => {
  3984. if (ArrayUtil.isNotEmpty(this.songList)) {
  3985. this.isShowPlay = true;
  3986. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  3987. this.initLyric(lyricPath);
  3988. this.startAutoHide()
  3989. } else {
  3990. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  3991. }
  3992. })
  3993. Row() {
  3994. Image($r('app.media.hm_previous'))
  3995. .height(28)
  3996. .width(28)
  3997. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3998. .margin({ left: 8, right: 16 })
  3999. .fillColor(this.themeColor)
  4000. .displayPriority(2)
  4001. .onClick(() => {
  4002. if (ArrayUtil.isNotEmpty(this.songList)) {
  4003. this.playPrevious()
  4004. } else {
  4005. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4006. }
  4007. })
  4008. //播放进度条
  4009. Stack() {
  4010. Progress({
  4011. value: Math.floor(this.progressValue),
  4012. type: ProgressType.Ring,
  4013. })
  4014. .color(this.themeColor)// 进度条前景色为灰色
  4015. .backgroundColor($r('app.color.index_background'))
  4016. .height(40)
  4017. .aspectRatio(CommonConstants.ASPECT_RATIO)
  4018. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ? $r('app.media.hm_pause') : $r('app.media.hm_play2'))
  4019. .height(38)
  4020. .width(38)
  4021. .displayPriority(3)
  4022. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4023. .fillColor(this.themeColor)
  4024. .onClick(() => {
  4025. if (ArrayUtil.isNotEmpty(this.songList)) {
  4026. this.playOrPause()
  4027. } else {
  4028. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4029. }
  4030. })
  4031. }
  4032. Image($r('app.media.hm_next'))
  4033. .height(28)
  4034. .width(28)
  4035. .margin({
  4036. right: 16,
  4037. left: 16
  4038. })
  4039. .fillColor(this.themeColor)
  4040. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4041. .displayPriority(2)
  4042. .onClick(() => {
  4043. if (ArrayUtil.isNotEmpty(this.songList)) {
  4044. this.playNext()
  4045. } else {
  4046. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4047. }
  4048. })
  4049. Image($r('app.media.hm_playlist'))
  4050. .height(28)
  4051. .width(28)
  4052. .displayPriority(1)
  4053. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4054. .fillColor(this.themeColor)
  4055. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  4056. height: '95%',
  4057. dragBar: true,
  4058. showClose: true,
  4059. blurStyle: BlurStyle.Thin,
  4060. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  4061. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  4062. title: {
  4063. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  4064. + `(${this.songList.length}首)`
  4065. }
  4066. })
  4067. .onClick(() => {
  4068. if (ArrayUtil.isNotEmpty(this.songList)) {
  4069. this.isShowSheet = !this.isShowSheet;
  4070. this.isFrontWhite = false
  4071. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  4072. setTimeout(() => {
  4073. this.playListScroller.scrollToIndex(this.curIndex, true, ScrollAlign.CENTER)
  4074. }, 123)
  4075. } else {
  4076. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4077. }
  4078. })
  4079. }
  4080. }
  4081. .width('100%')
  4082. .height(this.bottomBarHeight)
  4083. .justifyContent(FlexAlign.Center)
  4084. .hitTestBehavior(HitTestMode.Transparent)
  4085. .backgroundColor(this.isCustomizeBg ? Color.Transparent : $r('app.color.bottom_control_background'))
  4086. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  4087. // modalTransition: ModalTransition.DEFAULT,
  4088. transition: AnimationHelper.transitionInDown(666),
  4089. backgroundColor: 'rgba(0, 0, 0, 0.9)',
  4090. })
  4091. .padding({
  4092. left: 16,
  4093. right: 16
  4094. })
  4095. Line()
  4096. .width('100%')
  4097. .height(25)
  4098. .backgroundColor($r('app.color.bottom_control_background'))// .visibility(this.isPhoneLan()?Visibility.None:this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  4099. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  4100. }
  4101. .clickEffect({ level: ClickEffectLevel.HEAVY })
  4102. }
  4103. @State isFrontWhite: boolean = false
  4104. //播放列表布局
  4105. @Builder
  4106. PlayListSheet() {
  4107. Column() {
  4108. this.PlayList()
  4109. }
  4110. .width('100%')
  4111. .height('100%')
  4112. }
  4113. @State titleStr: string = ''
  4114. @State ablumStr: string = ''
  4115. @State artistStr: string = ''
  4116. @State lyricConStr: string = ''
  4117. @State currentEditItem: string = ''
  4118. doUpdateData() {
  4119. setTimeout(() => {
  4120. if (this.modeType === 0) {
  4121. this.deleteCache(this.currentPath)
  4122. this.getSortedFiles(this.currentPath)
  4123. }
  4124. workerInstance.postMessage({ code: 2, data: this.context });
  4125. workerInstance.postMessage({ code: 3, data: this.context });
  4126. workerInstance.postMessage({ code: 4, data: this.context });
  4127. }, 999)
  4128. }
  4129. //编辑信息
  4130. doEdit(item: VideoItem) {
  4131. if (!item) {
  4132. return
  4133. }
  4134. if (StrUtil.isEmpty(this.titleStr)) {
  4135. ToastUtil.showToast('标题不能为空')
  4136. return
  4137. }
  4138. this.table.updateMediaInfo(item.filePath, this.titleStr, this.artistStr, this.ablumStr,
  4139. (success: boolean, error?: string) => {
  4140. this.isShowEdit = false
  4141. if (success) {
  4142. console.log(" onecold 编辑信息成功,数据库已同步");
  4143. ToastUtil.showToast('保存成功')
  4144. this.isShowMoreView = false
  4145. this.name = this.titleStr
  4146. if (item.filePath == this.currentSong?.filePath) {
  4147. this.currentSong.name = this.titleStr
  4148. this.artist = this.artistStr
  4149. this.currentSong.artist = this.artistStr
  4150. this.currentSong.album = this.ablumStr
  4151. }
  4152. this.doUpdateData()
  4153. } else {
  4154. ToastUtil.showToast('保存失败' + error?.toString())
  4155. console.error(" onecold 编辑信息数据库失败原因: " + error);
  4156. }
  4157. });
  4158. let doChangeLyric = false
  4159. if (item.filePath == this.currentSong?.filePath) {
  4160. if (this.lyricConStr !== this.lyricContent) {
  4161. doChangeLyric = true
  4162. }
  4163. } else if (this.lyricConStr !== this.tempLyricContent) {
  4164. doChangeLyric = true
  4165. }
  4166. if (doChangeLyric) {
  4167. let lyricPath = item.filePath.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  4168. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  4169. let isJiaMi = false;
  4170. let realLyricPath = lyricPath
  4171. if (FileUtil.accessSync(jiaMilyricPath)) {
  4172. isJiaMi = true
  4173. realLyricPath = jiaMilyricPath
  4174. console.info("onecold doEdit找到加密本地歌词 ");
  4175. } else {
  4176. isJiaMi = false
  4177. realLyricPath = lyricPath
  4178. console.info("onecold doEdit本地歌词 ");
  4179. }
  4180. this.saveDataToFile(this.lyricConStr, realLyricPath, isJiaMi)
  4181. }
  4182. }
  4183. updateLyricToDB() {
  4184. }
  4185. @Builder
  4186. editSheet(item: VideoItem) {
  4187. Scroll() {
  4188. Column() {
  4189. this.editDetail(item)
  4190. }
  4191. }
  4192. .width('100%')
  4193. .height('100%')
  4194. }
  4195. @Builder
  4196. editDetail(item: VideoItem) {
  4197. Column() {
  4198. if (item) {
  4199. Row() {
  4200. Stack() {
  4201. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') :
  4202. item.pixelMapPath)
  4203. .fillColor(this.themeColor)
  4204. .height(33)
  4205. .width(33)
  4206. .borderRadius('100%')
  4207. .clip(true)
  4208. .opacity(this.opacityItem)// 绑定透明度
  4209. .margin({ left: 20 })
  4210. }
  4211. .width('15%')
  4212. Row() {
  4213. Column() {
  4214. Text(item.name)
  4215. .fontSize(14)
  4216. .maxLines(1)
  4217. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4218. .animation({
  4219. duration: 555,
  4220. curve: 'Linear',
  4221. })
  4222. .fontColor(this.themeColor)
  4223. .margin({ left: 10 })
  4224. Row() {
  4225. Text(item.artist)
  4226. .fontSize(11)
  4227. .maxLines(1)
  4228. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4229. .padding({ top: 8 })
  4230. .fontColor(this.themeColor)
  4231. .margin({ left: 10 })
  4232. }
  4233. }
  4234. .height('100%')
  4235. .width(100)
  4236. .visibility(this.isDarkMode ? Visibility.None : Visibility.Visible)
  4237. .justifyContent(FlexAlign.Center)
  4238. .alignItems(HorizontalAlign.Start)
  4239. Button('本地封面')
  4240. .fontColor(Color.White)
  4241. .fontSize(12)
  4242. .height(38)
  4243. .width(88)
  4244. .backgroundColor(this.themeColor)
  4245. .stateEffect(true)
  4246. .margin({ right: 5, left: 12 })
  4247. .onClick(async () => {
  4248. this.goSelectImage(item)
  4249. })
  4250. Button('获取封面')
  4251. .fontColor(Color.White)
  4252. .fontSize(12)
  4253. .height(38)
  4254. .width(88)
  4255. .backgroundColor(this.themeColor)
  4256. .stateEffect(true)
  4257. .margin({ right: 12, left: 5 })
  4258. .onClick(async () => {
  4259. this.doSearchCover(item)
  4260. })
  4261. }
  4262. .height('100%')
  4263. .justifyContent(FlexAlign.Start)
  4264. .layoutWeight(1)
  4265. }
  4266. .width('100%')
  4267. .height(58)
  4268. Row() {
  4269. Text('标题:')
  4270. .fontSize(14)
  4271. .fontColor($r('app.color.text_color'))
  4272. .margin({ left: 22 })
  4273. TextInput({ text: item.name })
  4274. .height(40)
  4275. .maxLines(1)
  4276. .fontSize(14)
  4277. .layoutWeight(1)
  4278. .fontColor($r('app.color.text_color'))
  4279. .margin({ right: 20, left: 10 })
  4280. .onChange((val: string) => {
  4281. this.titleStr = val
  4282. })
  4283. }
  4284. .width('100%')
  4285. .margin({ top: 10, bottom: 10 })
  4286. .justifyContent(FlexAlign.Start)
  4287. Row() {
  4288. Text('艺术家:')
  4289. .fontSize(14)
  4290. .fontColor($r('app.color.text_color'))
  4291. .margin({ left: 22 })
  4292. TextInput({ text: item.artist })
  4293. .height(40)
  4294. .maxLines(1)
  4295. .fontSize(14)
  4296. .layoutWeight(1)
  4297. .fontColor($r('app.color.text_color'))
  4298. .margin({ right: 20, left: 10 })
  4299. .onChange((val: string) => {
  4300. this.artistStr = val
  4301. })
  4302. }
  4303. .width('100%')
  4304. .margin({ top: 10, bottom: 10 })
  4305. .justifyContent(FlexAlign.Start)
  4306. Row() {
  4307. Text('专辑名:')
  4308. .fontSize(14)
  4309. .fontColor($r('app.color.text_color'))
  4310. .margin({ left: 22 })
  4311. TextInput({ text: item.album })
  4312. .height(40)
  4313. .maxLines(1)
  4314. .fontSize(14)
  4315. .layoutWeight(1)
  4316. .fontColor($r('app.color.text_color'))
  4317. .margin({ right: 20, left: 10 })
  4318. .onChange((val: string) => {
  4319. this.ablumStr = val
  4320. })
  4321. }
  4322. .width('100%')
  4323. .margin({ top: 10, bottom: 10 })
  4324. .justifyContent(FlexAlign.Start)
  4325. Row() {
  4326. Text('歌词:')
  4327. .fontSize(14)
  4328. .fontColor($r('app.color.text_color'))
  4329. .margin({ left: 22 })
  4330. TextArea({ text: item.filePath === this.currentSong?.filePath ? this.lyricContent : this.tempLyricContent })
  4331. .type(TextAreaType.NORMAL)
  4332. .height(275)
  4333. .fontSize(14)
  4334. .layoutWeight(1)
  4335. .fontColor($r('app.color.text_color'))
  4336. .margin({ right: 20, left: 10 })
  4337. .onChange((val: string) => {
  4338. this.lyricConStr = val
  4339. })
  4340. }
  4341. .width('100%')
  4342. .margin({ top: 10, bottom: 10 })
  4343. .justifyContent(FlexAlign.Start)
  4344. Row() {
  4345. Button('保存')
  4346. .fontColor(Color.White)
  4347. .layoutWeight(1)
  4348. .height(50)
  4349. .width(100)
  4350. .backgroundColor(this.themeColor)
  4351. .stateEffect(true)
  4352. .margin({ right: 20, bottom: 20 })
  4353. .onClick(async () => {
  4354. this.doEdit(item)
  4355. })
  4356. Button('取消')
  4357. .fontColor(Color.White)
  4358. .layoutWeight(1)
  4359. .height(50)
  4360. .width(100)
  4361. .backgroundColor(this.themeColor)
  4362. .stateEffect(true)
  4363. .margin({ left: 20, bottom: 20 })
  4364. .onClick(async () => {
  4365. this.isShowEdit = false
  4366. })
  4367. }
  4368. .margin({
  4369. left: 38,
  4370. right: 38,
  4371. top: 10,
  4372. bottom: 10
  4373. })
  4374. .width(250)
  4375. .height(60)
  4376. }
  4377. }
  4378. .margin({ bottom: 20 })
  4379. }
  4380. @Builder
  4381. detailSheet(item:VideoItem) {
  4382. Scroll() {
  4383. Column() {
  4384. this.songDetail(item)
  4385. }
  4386. }
  4387. .width('100%')
  4388. .height('100%')
  4389. }
  4390. @Builder
  4391. songDetail(currentItem:VideoItem) {
  4392. Column() {
  4393. if (currentItem) {
  4394. Row() {
  4395. Stack() {
  4396. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.music_red') :
  4397. currentItem.pixelMapPath)
  4398. .fillColor(this.themeColor)
  4399. .height(33)
  4400. .width(33)
  4401. .borderRadius('100%')
  4402. .clip(true)
  4403. .opacity(this.opacityItem)// 绑定透明度
  4404. .margin({ left: 20 })
  4405. }
  4406. .width('15%')
  4407. Column() {
  4408. Column() {
  4409. Text(currentItem.name)
  4410. .fontSize(14)
  4411. .maxLines(1)
  4412. .animation({
  4413. duration: 555,
  4414. curve: 'Linear',
  4415. })
  4416. .fontColor($r('app.color.text_color'))
  4417. .margin({ left: 10 })
  4418. Row() {
  4419. Text(StrUtil.isEmpty(currentItem.artist) ? currentItem.cTime :
  4420. currentItem.artist + ' ' + currentItem?.album)
  4421. .fontSize(11)
  4422. .padding({ top: 8 })
  4423. .fontColor($r('app.color.text_color'))
  4424. .margin({ left: 10 })
  4425. }
  4426. }
  4427. .height('100%')
  4428. .width('100%')
  4429. .justifyContent(FlexAlign.Center)
  4430. .alignItems(HorizontalAlign.Start)
  4431. }
  4432. .height('100%')
  4433. }
  4434. .width('100%')
  4435. .height(58)
  4436. .justifyContent(FlexAlign.SpaceBetween)
  4437. Row() {
  4438. Text('歌手名:')
  4439. .fontSize(14)
  4440. .fontColor(Color.White)
  4441. .margin({ left: 22 })
  4442. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  4443. .fontSize(14)
  4444. .fontColor(Color.White)
  4445. .margin({ left: 10 })
  4446. .layoutWeight(1)
  4447. }
  4448. .width('100%')
  4449. .margin({ top: 10, bottom: 10 })
  4450. .justifyContent(FlexAlign.Start)
  4451. Row() {
  4452. Text('专辑名:')
  4453. .fontSize(14)
  4454. .fontColor(Color.White)
  4455. .margin({ left: 22 })
  4456. Text(currentItem?.album ?currentItem.album : '未知专辑')
  4457. .fontSize(14)
  4458. .margin({ left: 10 })
  4459. .fontColor(Color.White)
  4460. .layoutWeight(1)
  4461. }
  4462. .width('100%')
  4463. .margin({ top: 10, bottom: 10 })
  4464. .justifyContent(FlexAlign.Start)
  4465. Row() {
  4466. Text('时长:')
  4467. .fontSize(14)
  4468. .fontColor(Color.White)
  4469. .margin({ left: 22 })
  4470. Text(StrUtil.isEmpty(currentItem.duration)?
  4471. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  4472. .fontSize(14)
  4473. .margin({ left: 10 })
  4474. .fontColor(Color.White)
  4475. .layoutWeight(1)
  4476. }
  4477. .width('100%')
  4478. .margin({ top: 10, bottom: 10 })
  4479. .justifyContent(FlexAlign.Start)
  4480. Row() {
  4481. Text('采样率:')
  4482. .fontSize(14)
  4483. .fontColor(Color.White)
  4484. .margin({ left: 22 })
  4485. Text(Utility.convertToKHz(currentItem.sampleRate))
  4486. .fontSize(14)
  4487. .margin({ left: 10 })
  4488. .fontColor(Color.White)
  4489. .layoutWeight(1)
  4490. }
  4491. .width('100%')
  4492. .margin({ top: 10, bottom: 10 })
  4493. .justifyContent(FlexAlign.Start)
  4494. Row() {
  4495. Text('比特率:')
  4496. .fontSize(14)
  4497. .fontColor(Color.White)
  4498. .margin({ left: 22 })
  4499. Text(currentItem.bit_rate)
  4500. .fontSize(14)
  4501. .margin({ left: 10 })
  4502. .fontColor(Color.White)
  4503. .layoutWeight(1)
  4504. }
  4505. .width('100%')
  4506. .margin({ top: 10, bottom: 10 })
  4507. .justifyContent(FlexAlign.Start)
  4508. Row() {
  4509. Text('风格:')
  4510. .fontSize(14)
  4511. .fontColor(Color.White)
  4512. .margin({ left: 22 })
  4513. Text(currentItem.genre)
  4514. .fontSize(14)
  4515. .margin({ left: 10 })
  4516. .fontColor(Color.White)
  4517. .layoutWeight(1)
  4518. }
  4519. .width('100%')
  4520. .margin({ top: 10, bottom: 10 })
  4521. .justifyContent(FlexAlign.Start)
  4522. Row() {
  4523. Text('发行时间:')
  4524. .fontSize(14)
  4525. .fontColor(Color.White)
  4526. .margin({ left: 22 })
  4527. Text(currentItem.year)
  4528. .fontSize(14)
  4529. .margin({ left: 10 })
  4530. .fontColor(Color.White)
  4531. .layoutWeight(1)
  4532. }
  4533. .width('100%')
  4534. .margin({ top: 10, bottom: 10 })
  4535. .justifyContent(FlexAlign.Start)
  4536. Row() {
  4537. Text('质量评分:')
  4538. .fontSize(14)
  4539. .fontColor(Color.White)
  4540. .margin({ left: 22 })
  4541. Text(currentItem.probe_score+"")
  4542. .fontSize(14)
  4543. .margin({ left: 10 })
  4544. .fontColor(Color.White)
  4545. .layoutWeight(1)
  4546. }
  4547. .width('100%')
  4548. .margin({ top: 10, bottom: 10 })
  4549. .justifyContent(FlexAlign.Start)
  4550. Row() {
  4551. Text('音轨号:')
  4552. .fontSize(14)
  4553. .fontColor(Color.White)
  4554. .margin({ left: 22 })
  4555. Text(currentItem.track)
  4556. .fontSize(14)
  4557. .margin({ left: 10 })
  4558. .fontColor(Color.White)
  4559. .layoutWeight(1)
  4560. }
  4561. .width('100%')
  4562. .margin({ top: 10, bottom: 10 })
  4563. .justifyContent(FlexAlign.Start)
  4564. Row() {
  4565. Text('格式:')
  4566. .fontSize(14)
  4567. .fontColor(Color.White)
  4568. .margin({ left: 22 })
  4569. Text(Utility.formatMimeType(currentItem.mimeType))
  4570. .fontSize(14)
  4571. .margin({ left: 10 })
  4572. .fontColor(Color.White)
  4573. .layoutWeight(1)
  4574. }
  4575. .width('100%')
  4576. .margin({ top: 10, bottom: 10 })
  4577. .justifyContent(FlexAlign.Start)
  4578. Row() {
  4579. Text('播放次数:')
  4580. .fontSize(14)
  4581. .fontColor(Color.White)
  4582. .margin({ left: 22 })
  4583. Text(currentItem.playCount?.toString())
  4584. .fontSize(14)
  4585. .margin({ left: 10 })
  4586. .fontColor(Color.White)
  4587. .layoutWeight(1)
  4588. }
  4589. .width('100%')
  4590. .margin({ top: 10, bottom: 10 })
  4591. .justifyContent(FlexAlign.Start)
  4592. Row() {
  4593. Text('流数量:')
  4594. .fontSize(14)
  4595. .fontColor(Color.White)
  4596. .margin({ left: 22 })
  4597. Text(currentItem.nb_streams?.toString())
  4598. .fontSize(14)
  4599. .margin({ left: 10 })
  4600. .fontColor(Color.White)
  4601. .layoutWeight(1)
  4602. }
  4603. .width('100%')
  4604. .margin({ top: 10, bottom: 10 })
  4605. .justifyContent(FlexAlign.Start)
  4606. Row() {
  4607. Text('文件大小:')
  4608. .fontSize(14)
  4609. .fontColor(Color.White)
  4610. .margin({ left: 22 })
  4611. Text(currentItem.size)
  4612. .fontSize(14)
  4613. .margin({ left: 10 })
  4614. .fontColor(Color.White)
  4615. .layoutWeight(1)
  4616. }
  4617. .width('100%')
  4618. .margin({ top: 10, bottom: 10 })
  4619. .justifyContent(FlexAlign.Start)
  4620. Row() {
  4621. Text('文件名:')
  4622. .fontSize(14)
  4623. .fontColor(Color.White)
  4624. .margin({ left: 22 })
  4625. Text(currentItem.fileName)
  4626. .fontSize(14)
  4627. .margin({ left: 10 })
  4628. .fontColor(Color.White)
  4629. .layoutWeight(1)
  4630. }
  4631. .width('100%')
  4632. .margin({ top: 10, bottom: 10 })
  4633. .justifyContent(FlexAlign.Start)
  4634. Row() {
  4635. Text('修改时间:')
  4636. .fontSize(14)
  4637. .fontColor(Color.White)
  4638. .margin({ left: 22 })
  4639. Text(currentItem.cTime)
  4640. .fontSize(14)
  4641. .margin({ left: 10 })
  4642. .fontColor(Color.White)
  4643. .layoutWeight(1)
  4644. }
  4645. .width('100%')
  4646. .margin({ top: 10, bottom: 10 })
  4647. .justifyContent(FlexAlign.Start)
  4648. Row() {
  4649. Text('存放目录:')
  4650. .fontSize(14)
  4651. .fontColor(Color.White)
  4652. .margin({ left: 22 })
  4653. Text(currentItem.filePath)
  4654. .fontSize(12)
  4655. .margin({ left: 10 })
  4656. .fontColor(Color.White)
  4657. .layoutWeight(1)
  4658. }
  4659. .margin({ top: 10, bottom: 10 })
  4660. .width('100%')
  4661. .justifyContent(FlexAlign.Start)
  4662. }
  4663. }
  4664. .margin({ bottom: 20 })
  4665. }
  4666. //定时关闭布局
  4667. @Builder
  4668. TimeCloseSheet() {
  4669. Scroll() {
  4670. Column() {
  4671. this.TimeClose()
  4672. }
  4673. }
  4674. .width('100%')
  4675. .height('100%')
  4676. }
  4677. //倒计时关闭音乐,退出App功能实现。
  4678. @State selectedMinutes: number = 0 // 0表示未开启
  4679. @State remainingSeconds: number = 0
  4680. // 预设时间选项
  4681. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  4682. private formatTime(seconds: number): string {
  4683. const mins = Math.floor(seconds / 60)
  4684. const secs = seconds % 60
  4685. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  4686. }
  4687. // 开始倒计时
  4688. private handleTimeSelect(minutes: number) {
  4689. if (minutes === this.selectedMinutes) {
  4690. this.stopCountdown();
  4691. this.selectedMinutes = 0;
  4692. return;
  4693. }
  4694. this.selectedMinutes = minutes;
  4695. this.remainingSeconds = minutes * 60;
  4696. this.startCountdown(); // 新增调用
  4697. }
  4698. @Builder
  4699. TimeClose() {
  4700. Column() {
  4701. // 倒计时显示区域
  4702. Text(this.selectedMinutes > 0 ?
  4703. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  4704. "定时关闭未开启")
  4705. .fontSize(17)
  4706. .fontColor($r('app.color.text_color'))
  4707. .margin({ top: 2, bottom: 8 });
  4708. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  4709. ForEach(this.presetTimes, (minutes: number, index: number) => {
  4710. // 单行时间选项容器
  4711. Row() {
  4712. // 文字描述区域
  4713. Text(this.getDisplayText(minutes))
  4714. .fontSize(15)
  4715. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  4716. $r('app.color.text_color'))// 选中态颜色变化
  4717. .textAlign(TextAlign.Start)
  4718. .layoutWeight(1); // 占据剩余空间
  4719. // 复选框样式的选择器
  4720. Row() {
  4721. if (minutes === this.selectedMinutes) {
  4722. // 选中状态 - 带勾号的圆形复选框
  4723. Row() {
  4724. // 使用系统内置的勾号图标
  4725. Image($r('sys.media.ohos_ic_public_ok'))
  4726. .width(14)
  4727. .height(14)
  4728. .fillColor(Color.White)
  4729. }
  4730. .width(24)
  4731. .height(24)
  4732. .borderRadius(12)
  4733. .backgroundColor(this.themeColor)
  4734. .justifyContent(FlexAlign.Center)
  4735. .alignItems(VerticalAlign.Center)
  4736. } else {
  4737. // 未选中状态的圆形边框
  4738. Row()
  4739. .width(24)
  4740. .height(24)
  4741. .borderRadius(12)
  4742. .border({
  4743. width: 2,
  4744. color: $r('app.color.text_color'),
  4745. style: BorderStyle.Solid
  4746. })
  4747. .backgroundColor(Color.Transparent)
  4748. }
  4749. }
  4750. .width(24)
  4751. .height(24)
  4752. .margin({ left: 20 })
  4753. .justifyContent(FlexAlign.Center)
  4754. .alignItems(VerticalAlign.Center)
  4755. }
  4756. .width('100%')
  4757. .padding({
  4758. top: 18,
  4759. bottom: 18,
  4760. left: 18,
  4761. right: 18
  4762. })
  4763. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  4764. $r('app.color.bottom_control_background')) // 选中背景高亮
  4765. .borderRadius(12)
  4766. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  4767. .margin({ bottom: 18 })
  4768. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  4769. });
  4770. }
  4771. .width('100%')
  4772. .padding(16)
  4773. }
  4774. }
  4775. // 获取显示文本
  4776. private getDisplayText(minutes: number): string {
  4777. if (minutes === -1) {
  4778. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  4779. }
  4780. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  4781. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  4782. }
  4783. // 处理选择事件
  4784. private handleSelect(minutes: number): void {
  4785. if (minutes === -1) { // 自定义
  4786. // 弹出自定义时间对话框
  4787. DialogHelper.showTextInputDialog({
  4788. title: '自定义时间',
  4789. maskColor: Color.Transparent,
  4790. inputType: InputType.Number,
  4791. text: '',
  4792. onChange: (text) => {
  4793. console.error("onChange: " + text);
  4794. },
  4795. onAction: (action, dialogId, content) => {
  4796. if (action == DialogAction.TWO) {
  4797. const customMinutes = Number(content);
  4798. if (customMinutes > 0) {
  4799. this.handleTimeSelect(customMinutes); // 设置自定义时间
  4800. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  4801. }
  4802. }
  4803. }
  4804. });
  4805. } else {
  4806. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  4807. }
  4808. }
  4809. // 添加定时器引用
  4810. private timerId: number = -1;
  4811. // 启动/重置倒计时
  4812. private startCountdown() {
  4813. // 清除旧定时器
  4814. if (this.timerId !== -1) {
  4815. clearInterval(this.timerId);
  4816. }
  4817. // 创建新定时器
  4818. if (this.selectedMinutes > 0) {
  4819. this.timerId = setInterval(() => {
  4820. if (this.remainingSeconds === 15) {
  4821. this.showConfirmationDialog();
  4822. }
  4823. if (this.remainingSeconds > 0) {
  4824. this.remainingSeconds -= 1;
  4825. } else {
  4826. this.stopCountdown();
  4827. this.handleTimeout();
  4828. }
  4829. }, 1000);
  4830. }
  4831. }
  4832. // 15倒计时后再次提示显示确认是否关闭App对话框
  4833. private showConfirmationDialog() {
  4834. DialogHelper.showAlertDialog({
  4835. backgroundColor: $r('app.color.btn_green'),
  4836. title: '确认关闭',
  4837. maskColor: Color.Transparent,
  4838. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  4839. borderStyle: BorderStyle.Dashed,
  4840. primaryButton: '暂不关闭',
  4841. secondaryButton: '确定',
  4842. onAction: (action) => {
  4843. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  4844. this.stopCountdown();
  4845. this.selectedMinutes = 0
  4846. } else if (action == DialogAction.TWO) {
  4847. }
  4848. }
  4849. })
  4850. }
  4851. // 停止倒计时
  4852. private stopCountdown() {
  4853. if (this.timerId !== -1) {
  4854. clearInterval(this.timerId);
  4855. this.timerId = -1;
  4856. }
  4857. }
  4858. // 超时处理
  4859. private handleTimeout() {
  4860. // 执行播放器关闭逻辑
  4861. this.selectedMinutes = 0;
  4862. ToastUtil.showToast(" 定时关闭已完成");
  4863. this.stop(); // 假设存在的播放器实例
  4864. //退出APP
  4865. const mContext = getContext(this) as common.UIAbilityContext
  4866. mContext.terminateSelf();
  4867. AvSessionController.getInstance(true).unregisterSessionListener()
  4868. }
  4869. //倒计时关闭音乐,退出App功能实现结束。
  4870. //播放列表的拖动List 重新排序
  4871. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  4872. //左滑操作 移动文件 重命名 删除等操作
  4873. @Builder
  4874. sonButton(item: VideoItem, index: number, filePath: string) {
  4875. Row() {
  4876. //加入下一首播放
  4877. Button() {
  4878. Image($r('app.media.next_to_play'))
  4879. .fillColor(Color.White)
  4880. .width(20)
  4881. }
  4882. .width(40)
  4883. .height(40)
  4884. .type(ButtonType.Circle)
  4885. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  4886. .backgroundColor(this.themeColor)
  4887. .margin(5)
  4888. .onClick(() => {
  4889. this.addToNextPlay(item);
  4890. })
  4891. Button() {
  4892. Image($r('app.media.close'))
  4893. .fillColor(Color.White)
  4894. .width(20)
  4895. }
  4896. .width(40)
  4897. .height(40)
  4898. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  4899. .type(ButtonType.Circle)
  4900. .backgroundColor(this.themeColor)
  4901. .margin(5)
  4902. .onClick(() => {
  4903. this.songList.splice(Number(index), 1)
  4904. this.sonDataSource.pushArrayData(this.songList)
  4905. })
  4906. Button() {
  4907. Image($r('app.media.share2'))
  4908. .fillColor(Color.White)
  4909. .width(20)
  4910. }
  4911. .width(40)
  4912. .height(40)
  4913. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  4914. .type(ButtonType.Circle)
  4915. .backgroundColor(this.themeColor)
  4916. .margin(5)
  4917. .onClick(() => {
  4918. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  4919. })
  4920. }
  4921. }
  4922. itemMoveSon(index: number, newIndex: number): void {
  4923. if (newIndex < 0 || newIndex >= this.songList.length) {
  4924. return;
  4925. }
  4926. let tmp = this.songList.splice(index, 1);
  4927. this.songList.splice(newIndex, 0, tmp[0]);
  4928. this.sonDataSource.pushArrayData(this.songList)
  4929. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  4930. }
  4931. @Builder
  4932. PlayList() {
  4933. List({ scroller: this.playListScroller }) {
  4934. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  4935. ListItem() {
  4936. this.MusicItemSon(item, index)
  4937. }
  4938. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  4939. .animation({
  4940. duration: 666,
  4941. curve: 'ease-in-out' // 可选动画曲线
  4942. })
  4943. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  4944. TransitionEffect.scale({ x: 0, y: 0 })))
  4945. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  4946. //拖动List关键代码开始
  4947. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  4948. .zIndex(this.dragItem === index ? 1 : 0)
  4949. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  4950. .gesture(
  4951. GestureGroup(GestureMode.Sequence,
  4952. LongPressGesture({ repeat: true })
  4953. .onAction((event?: GestureEvent) => {
  4954. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  4955. this.scaleItem = index
  4956. })
  4957. })
  4958. .onActionEnd(() => {
  4959. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  4960. this.scaleItem = -1
  4961. })
  4962. }),
  4963. PanGesture({ fingers: 1, direction: null, distance: 0 })
  4964. .onActionStart(() => {
  4965. this.dragItem = index // 记录当前拖动项索引
  4966. this.dragRefOffset = 0 // 重置偏移基准
  4967. })
  4968. .onActionUpdate((event: GestureEvent) => {
  4969. this.offsetY = event.offsetY - this.dragRefOffset;
  4970. this.neighborItem = -1;
  4971. let indexA = this.songList.indexOf(item);
  4972. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  4973. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  4974. let value: number = 0;
  4975. if (this.offsetY < 0) {
  4976. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  4977. this.neighborItem = indexA - 1;
  4978. this.neighborScale = 1 - value / 20;
  4979. } else if (this.offsetY > 0) {
  4980. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  4981. this.neighborItem = indexA + 1;
  4982. this.neighborScale = 1 - value / 20;
  4983. }
  4984. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  4985. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4986. this.offsetY -= this.ITEM_INTV;
  4987. this.dragRefOffset += this.ITEM_INTV;
  4988. this.itemMoveSon(indexA, indexA + 1);
  4989. });
  4990. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  4991. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4992. this.offsetY += this.ITEM_INTV;
  4993. this.dragRefOffset -= this.ITEM_INTV;
  4994. this.itemMoveSon(indexA, indexA - 1);
  4995. });
  4996. }
  4997. })
  4998. .onActionEnd((event: GestureEvent) => {
  4999. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5000. this.dragItem = -1
  5001. this.neighborItem = -1
  5002. })
  5003. animateTo({
  5004. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5005. }, () => {
  5006. this.scaleItem = -1
  5007. })
  5008. })
  5009. )
  5010. .onCancel(() => {
  5011. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5012. this.dragItem = -1
  5013. this.neighborItem = -1
  5014. })
  5015. animateTo({
  5016. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5017. }, () => {
  5018. this.scaleItem = -1
  5019. })
  5020. })
  5021. ) //拖动List关键代码结束
  5022. .onClick(() => {
  5023. this.doPlay(item, index, true)
  5024. })
  5025. }, (item: VideoItem) => item.filePath)
  5026. }
  5027. .width('100%')
  5028. .height('100%')
  5029. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  5030. // .animation({ duration: 500, curve: Curve.Ease }))
  5031. .cachedCount(10)
  5032. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5033. .gesture(PinchGesture({ fingers: 2 })
  5034. .onActionEnd((event: GestureEvent) => {
  5035. this.setlistTwoFingers()
  5036. })
  5037. .onActionUpdate(e => {
  5038. this.scaleValue = this.pinchValue * e.scale
  5039. })
  5040. .onActionStart(e => {
  5041. }))
  5042. .padding({
  5043. bottom: 0
  5044. })
  5045. }
  5046. @Builder
  5047. private MusicItemSon(item: VideoItem, index?: number) {
  5048. Button({ type: ButtonType.Normal, stateEffect: true }) {
  5049. Row() {
  5050. Stack() {
  5051. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  5052. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  5053. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  5054. .alt($r('app.media.music_red'))
  5055. .fillColor(this.themeColor)
  5056. .borderRadius('100%')
  5057. .clip(true)
  5058. .margin({ left: 20 })
  5059. }
  5060. .width('15%')
  5061. Column() {
  5062. Column() {
  5063. Text(item.name)
  5064. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5065. .fontColor(this.curIndex === index ? this.themeColor :
  5066. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  5067. .maxLines(1)
  5068. .margin({ left: this.twoFingerType == 3 ? 18 : 10 })
  5069. Row() {
  5070. Column(){
  5071. Text(item.md5Str?.includes('Lossless')?
  5072. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5073. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5074. .padding({ top: 3,right:6,left:6,bottom:3 })
  5075. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5076. $r('app.color.text_color'))
  5077. .fontWeight(500)
  5078. .borderRadius(12)
  5079. .margin({ left: this.twoFingerType == 3 ? 12 : 10 })
  5080. .backgroundColor('#FFC107')
  5081. }
  5082. .padding({ top: 8 })
  5083. Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
  5084. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5085. .padding({ top: 8 })
  5086. .fontColor(this.curIndex === index ? this.themeColor :
  5087. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  5088. .margin({ left: this.twoFingerType == 3 ? 5 : 3 })
  5089. Blank()
  5090. Text(item.size)
  5091. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5092. .padding({ top: 8 })
  5093. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  5094. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  5095. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  5096. .margin({ left: 10 })
  5097. }
  5098. }
  5099. .height('100%')
  5100. .width('100%')
  5101. .justifyContent(FlexAlign.Center)
  5102. .alignItems(HorizontalAlign.Start)
  5103. }
  5104. .height('100%')
  5105. .width('65%')
  5106. Column() {
  5107. ImageAnimator()
  5108. .images(this.imagesF)// 动画数组
  5109. .duration(1000)// 持续
  5110. .state(this.animationState)// 动画状态
  5111. .fillMode(FillMode.Forwards)
  5112. .width(18)
  5113. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  5114. Visibility.None)
  5115. .height(18)
  5116. .iterations(-1) // 播放次数
  5117. }
  5118. .width('20%')
  5119. }
  5120. }
  5121. .backgroundColor(Color.Transparent)
  5122. .width('100%')
  5123. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  5124. .shadow(this.scaleItem === index ? {
  5125. radius: 70,
  5126. color: '#15000000',
  5127. offsetX: 0,
  5128. offsetY: 0
  5129. } :
  5130. {
  5131. radius: 0,
  5132. color: '#15000000',
  5133. offsetX: 0,
  5134. offsetY: 0
  5135. })
  5136. .animation({ curve: Curve.Sharp, duration: 300 })
  5137. }
  5138. @Builder
  5139. MusicPlayBuilder() {
  5140. Column() {
  5141. this.IjkMusicPlayerView()
  5142. }
  5143. .height('100%')
  5144. .width('100%')
  5145. .onDisAppear(() => {
  5146. this.translateY = 0;
  5147. })
  5148. .translate({ y: this.translateY })
  5149. .gesture(
  5150. PanGesture(this.panOption)
  5151. .onActionUpdate((event?: GestureEvent) => {
  5152. if (event) {
  5153. // 只允许向下滑动,向上滑动时限制为0
  5154. this.translateY = Math.max(0, event.offsetY);
  5155. }
  5156. })
  5157. .onActionEnd((event?: GestureEvent) => {
  5158. // 使用更低的阈值和滑动速度判断
  5159. const minDistance = 100; // 最小滑动距离 100vp
  5160. const minVelocity = 500; // 最小滑动速度
  5161. // 获取滑动速度(如果可用)
  5162. const velocity = event?.velocityY || 0;
  5163. // 判断是否应该关闭:距离足够 或者 速度足够快
  5164. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  5165. if (shouldClose) {
  5166. // 添加关闭动画
  5167. this.getUIContext().animateTo({
  5168. duration: 300,
  5169. curve: Curve.Smooth
  5170. }, () => {
  5171. this.isShowPlay = false;
  5172. this.translateY = 0;
  5173. })
  5174. } else {
  5175. // 回弹动画
  5176. this.getUIContext().animateTo({
  5177. duration: 300,
  5178. curve: Curve.Smooth
  5179. }, () => {
  5180. this.translateY = 0;
  5181. })
  5182. }
  5183. })
  5184. )
  5185. }
  5186. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  5187. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  5188. HeightBreakpoint.HEIGHT_LG;
  5189. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  5190. @State topBarHeight: number = 50
  5191. @State barOpacity: number = 1
  5192. @State barBottomOpacity: number = 1
  5193. private hideDone: boolean = false;
  5194. @State currentYOffset: number = 0;
  5195. @State bottomBarHeight: number = 60;
  5196. private isHiding: boolean = false;
  5197. //是否是Pura X外屏,或者小屏幕
  5198. isPuraWP() {
  5199. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  5200. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  5201. }
  5202. //是否是Pura X外屏,或者小屏幕,手机横屏
  5203. isCoverOpacity() {
  5204. if (this.isPuraWP()) {
  5205. return true
  5206. }
  5207. if (this.isPhoneLan()) {
  5208. return true
  5209. }
  5210. if (deviceInfo.marketName.includes('Pura X')
  5211. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  5212. return true
  5213. }
  5214. return false
  5215. }
  5216. //是不是手机横屏
  5217. isPhoneLan() {
  5218. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  5219. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  5220. LogUtil.info('hicar isPhoneLan width= ' + this.windowWidth);
  5221. LogUtil.info('hicar isPhoneLan height= ' + this.windowHeight);
  5222. LogUtil.info(`twocold hicarWindow size: ${this.windowWidth}x${this.windowHeight}, this.isHiCarStatus: ${this.isHiCarStatus}`);
  5223. LogUtil.info(`twocold hicar Window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall: ${this.isHiCarSmall()}`);
  5224. if (this.isHiCarStatus) {
  5225. return false
  5226. }
  5227. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  5228. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  5229. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD) { //如果是手机横屏,返回true
  5230. return true
  5231. }
  5232. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  5233. && this.currentBreakpoint !== BreakpointTypeEnum.SM) {
  5234. if (DisplayUtil.getFoldStatus() === 0) {
  5235. return true
  5236. }
  5237. }
  5238. return false
  5239. }
  5240. //是不是1920x720的hicar的屏幕分辨率
  5241. isHiCarKuanBianPing(){
  5242. const hiCarAspectRatios: HiCarAspectRatio[] = [
  5243. { ratio: 1920 / 720, name: "1920x720" },
  5244. ];
  5245. const currentRatio: number = this.windowWidth / this.windowHeight;
  5246. const RATIO_TOLERANCE: number = 0.18; // 宽高比容差
  5247. LogUtil.info('twocold currentRatio = ' + currentRatio)
  5248. for (const hiCarRatio of hiCarAspectRatios) {
  5249. LogUtil.info('twocold hiCarRatio= ' + hiCarRatio.ratio)
  5250. LogUtil.info('twocold Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  5251. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  5252. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  5253. return true&&this.isHiCarStatus;
  5254. }
  5255. }
  5256. return false;
  5257. }
  5258. //是不是hicar的屏幕分辨率
  5259. isHiCarSmall() {
  5260. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  5261. return false
  5262. const hiCarAspectRatios: HiCarAspectRatio[] = [
  5263. { ratio: 800 / 480, name: "800x480" },
  5264. { ratio: 1280 / 720, name: "1280x720" },
  5265. { ratio: 1920 / 720, name: "1920x720" },
  5266. ];
  5267. const currentRatio: number = this.windowWidth / this.windowHeight;
  5268. const RATIO_TOLERANCE: number = 0.18; // 宽高比容差
  5269. LogUtil.info('twocold currentRatio = ' + currentRatio)
  5270. for (const hiCarRatio of hiCarAspectRatios) {
  5271. LogUtil.info('twocold hiCarRatio= ' + hiCarRatio.ratio)
  5272. LogUtil.info('twocold Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  5273. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  5274. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  5275. return true&&this.isHiCarStatus;
  5276. }
  5277. }
  5278. return false;
  5279. }
  5280. isHiCar() {
  5281. return this.isHiCarStatus;
  5282. // const hiCarAspectRatios: HiCarAspectRatio[] = [
  5283. // { ratio: 800 / 480, name: "800x480" },
  5284. // { ratio: 762 / 752, name: "762x752" },
  5285. // { ratio: 968 / 1280, name: "968x1280" },
  5286. // { ratio: 1200 / 1200, name: "1200x1200" },
  5287. // { ratio: 1280 / 720, name: "1280x720" },
  5288. // { ratio: 1920 / 720, name: "1920x720" },
  5289. // { ratio: 1920 / 1080, name: "1920x1080" }
  5290. // ];
  5291. // const currentRatio: number = this.windowWidth / this.windowHeight;
  5292. // const RATIO_TOLERANCE: number = 0.18; // 宽高比容差
  5293. // LogUtil.info('twocold currentRatio = ' + currentRatio)
  5294. //
  5295. // for (const hiCarRatio of hiCarAspectRatios) {
  5296. // LogUtil.info('twocold hiCarRatio= ' + hiCarRatio.ratio)
  5297. // LogUtil.info('twocold Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  5298. // if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  5299. // // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  5300. // return true&&this.isHiCarStatus;
  5301. // }
  5302. // }
  5303. //
  5304. // return false;
  5305. }
  5306. //是不是正常的手机竖屏
  5307. isPhonePortrait() {
  5308. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  5309. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  5310. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  5311. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  5312. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  5313. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  5314. return true
  5315. }
  5316. return false
  5317. }
  5318. @State showSpeedDialog: boolean = false
  5319. @State longPressSpeed: number = 3 //长按默认倍数
  5320. @Builder
  5321. SpeedDialog() {
  5322. Stack() {
  5323. Column() {
  5324. Text('已切换至' + this.longPressSpeed + '倍速播放')
  5325. .fontColor(Color.White)
  5326. .visibility(Visibility.Hidden)
  5327. }
  5328. .backgroundColor(Color.Black)
  5329. .borderRadius(20)
  5330. .padding({
  5331. top: 10,
  5332. right: 20,
  5333. left: 15,
  5334. bottom: 20
  5335. })
  5336. .opacity(0.6)
  5337. Text('已切换至' + this.longPressSpeed + '倍速播放')
  5338. .fontColor(Color.White)
  5339. }
  5340. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  5341. .zIndex(5)
  5342. .margin({ top: 80 })
  5343. }
  5344. @Builder
  5345. IjkMusicPlayerView() {
  5346. Column() {
  5347. Column() {
  5348. Column() {
  5349. //播放标题
  5350. Column() {
  5351. this.PlayTitle()
  5352. }
  5353. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  5354. .width('100%')
  5355. .margin({ top: 0 })
  5356. .height(PlayConstants.HEIGHT)
  5357. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  5358. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  5359. if (this.showSpeedDialog) {
  5360. this.SpeedDialog()
  5361. }
  5362. Stack() {
  5363. //手势拖动快进
  5364. Column()
  5365. .width(CommonConstants.FULL_PERCENT)
  5366. .height('100%')
  5367. .gesture(
  5368. GestureGroup(GestureMode.Parallel,
  5369. // 长按屏幕倍数播放
  5370. LongPressGesture({ repeat: true })
  5371. .onAction(() => {
  5372. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  5373. this.showSpeedDialog = true;
  5374. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  5375. }
  5376. })
  5377. .onActionEnd(() => {
  5378. this.showSpeedDialog = false;
  5379. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  5380. }),
  5381. //双击屏幕暂停或者播放
  5382. TapGesture({ count: 2 })
  5383. .onAction((event: GestureEvent) => {
  5384. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  5385. ToastUtil.showToast('已暂停')
  5386. }
  5387. this.playOrPause()
  5388. })
  5389. )
  5390. )
  5391. }
  5392. .height('65%')
  5393. Swiper() {
  5394. this.CoverInfo()
  5395. this.PlayerLyrics()
  5396. }
  5397. .onChange((index: number) => {
  5398. this.currentSwiperIndex = index
  5399. })
  5400. .indicator(false)
  5401. // .indicator(this.currentBreakpoint === BreakpointTypeEnum.SM ?
  5402. // new DotIndicator()
  5403. // .top(this.isCoverOpacity()?0:10)
  5404. //
  5405. // .selectedColor($r('app.color.select_swiper'))
  5406. // .color($r('app.color.slider_track')):false
  5407. // )
  5408. .displayCount(new BreakpointType({
  5409. sm: 1,
  5410. md: 2,
  5411. lg: 2,
  5412. xl: 2,
  5413. xxl: 2
  5414. }).getValue(this.currentBreakpoint))
  5415. .clip(false)
  5416. .loop(false)
  5417. .autoPlay(false)
  5418. // .interval(8000)
  5419. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  5420. .height('100%')
  5421. .hitTestBehavior(HitTestMode.Transparent)
  5422. Image($r('app.media.icon_replay'))
  5423. .objectFit(ImageFit.Auto)
  5424. .width('120px')
  5425. .height('120px')
  5426. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  5427. .border({ width: 0 })
  5428. .visibility(Visibility.None)
  5429. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  5430. .onClick(() => {
  5431. this.startPlayOrResumePlay();
  5432. })
  5433. }
  5434. .width(CommonConstants.FULL_PERCENT)
  5435. .height(CommonConstants.FULL_PERCENT)
  5436. .justifyContent(FlexAlign.End)
  5437. }
  5438. .justifyContent(FlexAlign.End)
  5439. .margin({ bottom: 8 })
  5440. }
  5441. // .backgroundImage(this.imageLabelBg)
  5442. .backgroundImage(this.isPuraWP() && this.currentSwiperIndex === 0 ?
  5443. (StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover) : this.imageLabelBg)
  5444. .backgroundImageSize(this.isPuraWP() ? { width: '100%' } : { height: '150%', width: '100%' })
  5445. // .backgroundImagePosition(Alignment.Center)
  5446. .animation({
  5447. duration: 666,
  5448. curve: 'ease-in-out' // 可选动画曲线
  5449. })
  5450. .backgroundBlurStyle(this.isPuraWP() && this.currentSwiperIndex === 0 ? BlurStyle.NONE :
  5451. BlurStyle.BACKGROUND_ULTRA_THICK)
  5452. .hitTestBehavior(HitTestMode.Transparent)
  5453. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  5454. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  5455. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  5456. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  5457. .onClick(() => {
  5458. // this.startAutoHide()
  5459. this.is_auto_hide_progress = false
  5460. setTimeout(() => {
  5461. this.is_auto_hide_progress = true
  5462. }, 6000)
  5463. })
  5464. }
  5465. @State progressValue: number = 0;
  5466. @State currentTime: string = "00:00";
  5467. @State totalTime: string = "00:00";
  5468. @State loadingVisible: Visibility = Visibility.None;
  5469. @State replayVisible: Visibility = Visibility.None;
  5470. @State slideEnable: boolean = false;
  5471. @State aspRatio: number = 0.5;
  5472. @State mContext: object | undefined = undefined;
  5473. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  5474. @State mFirst: boolean = true;
  5475. @State mDestroyPage: boolean = false;
  5476. @State playSpeed: number = 1;
  5477. @State oldSeconds: number = 0;
  5478. @State isSeekTo: boolean = false;
  5479. @State isCurrentTime: boolean = false;
  5480. @State videoWidth: string = '100%';
  5481. @State videoHeight: string = '100%';
  5482. @State initAspectRatio: number = 1;
  5483. @State videoAspectRatio: number = this.initAspectRatio;
  5484. private videoUrl: string = '';
  5485. private last: number = 0;
  5486. @State videoParentAspectRatio: number = this.initAspectRatio;
  5487. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  5488. @State CONTROL_PlayStatus: number = PlayStatus.INIT;
  5489. @State PROGRESS_MAX_VALUE: number = 100;
  5490. @State updateProgressTimer: number = 0;
  5491. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  5492. @State name: string = '';
  5493. // @State loop: boolean = false;
  5494. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  5495. @State multiple: string = '1.0X';
  5496. xcomponentController: XComponentController = new XComponentController()
  5497. private panOptionBright: PanGestureOptions =
  5498. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  5499. private panOptionVolume: PanGestureOptions =
  5500. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  5501. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  5502. //手势的音量控制和亮度控制
  5503. private positionX: number = PlayConstants.POSITION_X;
  5504. private positionY: number = PlayConstants.POSITION_Y;
  5505. private windowClass: window.Window = globalThis.windowClass
  5506. @State volume: number = 0.3;
  5507. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  5508. @State bright: number = PlayConstants.BRIGHT;
  5509. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  5510. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  5511. @State screenWidth: number = 0
  5512. @State screenHeight: number = 0
  5513. @State statusBarHeight: number = 0
  5514. @State isYesFull: boolean = false
  5515. private seekValue: number = 0
  5516. @State isVideoLock: boolean = false; // Whether the video playback is locked
  5517. eventHub = getContext().eventHub;
  5518. //投播组件
  5519. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  5520. private castController: avSession.AVCastController | undefined = undefined;
  5521. @State isCastPlaying: boolean = false;
  5522. @State currentTime2: number = 0;
  5523. @State currentStringTime: string = '00:00';
  5524. @State duration: number = 0;
  5525. @State isReady: boolean = false;
  5526. @State durationTime: number = 0;
  5527. @State durationStringTime: string = '00:00';
  5528. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  5529. // @State isPlaying: boolean = false;
  5530. private castSeek: boolean = false;
  5531. private castItem: avSession.AVQueueItem | undefined = undefined;
  5532. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  5533. @State imageLabel: PixelMap | Resource = CommonConstants.musicBgList[0];
  5534. @State imageLabelBg: PixelMap | Resource = CommonConstants.musicBgList[0];
  5535. @State rotateAngle2: number = 0
  5536. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  5537. @State cover: string | undefined = '';
  5538. @State artist: string | undefined = ''
  5539. // 1.初始化controller
  5540. private lyricController: LyricController = new LyricController()
  5541. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  5542. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  5543. private parser = new LyricParser()
  5544. @State randomColor: string = 'rgb(0,0,0)'
  5545. @State randomShakenX: number = 0
  5546. @State randomShakenY: number = 0
  5547. @State lyricTextSize: number = 24
  5548. @State lyricContent: string = ''
  5549. @State isDebug: boolean = false
  5550. @State isHightLightCenter: boolean = true
  5551. /**
  5552. * 初始化歌词加载与展示逻辑
  5553. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  5554. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  5555. * @param isApi2 是否使用API2获取歌词(可选)
  5556. *
  5557. * 主要流程:
  5558. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  5559. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  5560. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  5561. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  5562. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  5563. * 6. 解析失败或读取失败时,清空歌词显示。
  5564. *
  5565. * 注意事项:
  5566. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  5567. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  5568. * - 歌词内容解析后通过lyricController驱动UI渲染。
  5569. */
  5570. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean) {
  5571. if (StrUtil.isEmpty(lyricPath)) {
  5572. return
  5573. }
  5574. this.initPipLyricSetting()
  5575. this.lyricControllerSingle
  5576. .setTextSize(15)
  5577. .setCacheSize(4)
  5578. .setTextColor("#FFFFFF")
  5579. .setHighlightColor("#FFFFFF")
  5580. .setHighlightScale(1.2)
  5581. .setEmptyHint("")
  5582. .setAlignMode('center')
  5583. .setAnimationDuration(500)
  5584. .setSingleLine(true)
  5585. this.lyricContent = ''
  5586. this.lyricController
  5587. .setTextSize(this.currentLyricSize)
  5588. .setCacheSize(4)
  5589. .setTextColor("#DDDDDD")
  5590. .setHighlightColor("#FFFFFF")
  5591. .setEmptyHint("")
  5592. .setAnimationDuration(1000)
  5593. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  5594. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 0)
  5595. this.setBlurDegree(this.blurDegree, false)
  5596. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  5597. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  5598. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  5599. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  5600. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  5601. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  5602. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  5603. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  5604. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  5605. this.lyricController.setTextWeight(this.lyricTextWeight)
  5606. this.showSingleLyric = false
  5607. this.timeOffset = 0
  5608. this.lyricController.setLyric(null)
  5609. this.lyricControllerSingle.setLyric(null)
  5610. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  5611. console.log("onecold lyricPath =" + lyricPath)
  5612. let neiqianLrc = ''
  5613. let lyContent = this.currentSong?.lyricContent
  5614. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  5615. neiqianLrc = lyContent
  5616. }else{
  5617. neiqianLrc = LrcParser.getLyrics(this.videoUrl); //获取内嵌歌词
  5618. }
  5619. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast) {
  5620. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  5621. //赋值给this.lyricContent,播控中心才可以显示歌词
  5622. this.lyricContent = neiqianLrc
  5623. // 将文件内容按行分割成字符串数组
  5624. let lines = neiqianLrc.split('\n').map(line => line.trim());
  5625. // 3.解析歌词
  5626. let lyric = this.parser.parse(lines);
  5627. // 4.设置歌词
  5628. this.lyricController.setLyric(lyric);
  5629. this.lyricControllerXF.setLyric(lyric)
  5630. this.lyricControllerSingle.setLyric(lyric)
  5631. return
  5632. }
  5633. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  5634. && !Utility.isVideoByExtension(this.videoUrl))) {
  5635. if (this.currentSong !== undefined) {
  5636. // ToastUtil.showShort('正在为你搜索在线歌词!')
  5637. //判断是不是赞助会员,是会员的话才开启歌词功能
  5638. // if (!this.isDebug) {
  5639. // if (!Utility.isNoble()) {
  5640. // LogUtil.debug("onecold 不是赞助会员")
  5641. // return
  5642. // }
  5643. // if(!Utility.isPassInstallTime(33)){
  5644. // LogUtil.debug("onecold not pass time")
  5645. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  5646. // return
  5647. // }
  5648. // }
  5649. let artist = this.currentSong?.artist
  5650. if (artist === undefined) {
  5651. artist = ''
  5652. }
  5653. if (isApi2 === undefined) {
  5654. isApi2 = false
  5655. }
  5656. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  5657. // LogUtil.debug("onecold res =" + res)
  5658. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  5659. if (StrUtil.isNotEmpty(res)) {
  5660. this.lyricContent = res
  5661. let lines = res.split('\n').map(line => line.trim());
  5662. // 3.解析歌词
  5663. let lyric = this.parser.parse(lines);
  5664. // 4.设置歌词
  5665. this.lyricController.setLyric(lyric);
  5666. this.lyricControllerXF.setLyric(lyric)
  5667. this.lyricControllerSingle.setLyric(lyric)
  5668. this.showSingleLyric = true
  5669. // 4.保存歌词文件lyric到本地
  5670. this.saveDataToFile(res, jiaMilyricPath, true)
  5671. } else {
  5672. this.lyricController.setLyric(null)
  5673. this.lyricControllerXF.setLyric(null)
  5674. this.lyricControllerSingle.setLyric(null)
  5675. if (isOnLineAndToast) {
  5676. ToastUtil.showShort('未获取到歌词!')
  5677. }
  5678. }
  5679. } else {
  5680. this.lyricController.setLyric(null)
  5681. this.lyricControllerXF.setLyric(null)
  5682. this.lyricControllerSingle.setLyric(null)
  5683. if (isOnLineAndToast) {
  5684. ToastUtil.showShort('未获取到歌词!')
  5685. }
  5686. }
  5687. })
  5688. } else {
  5689. this.lyricController.setLyric(null)
  5690. this.lyricControllerXF.setLyric(null)
  5691. this.lyricControllerSingle.setLyric(null)
  5692. if (isOnLineAndToast) {
  5693. ToastUtil.showShort('未获取到歌词!')
  5694. }
  5695. }
  5696. return
  5697. }
  5698. try {
  5699. let isJiaMi = false;
  5700. let realLyricPath = lyricPath
  5701. if (FileUtil.accessSync(jiaMilyricPath)) {
  5702. isJiaMi = true
  5703. realLyricPath = jiaMilyricPath
  5704. console.info("onecold 找到加密本地歌词 ");
  5705. } else {
  5706. isJiaMi = false
  5707. realLyricPath = lyricPath
  5708. console.info("onecold 找到本地歌词 ");
  5709. }
  5710. // 3.读取文件内容并指定编码为 UTF-8
  5711. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_WRITE);
  5712. let arrayBuffer = new ArrayBuffer(4096);
  5713. fs.read(file.fd, arrayBuffer)
  5714. .then((readLen: number) => {
  5715. console.info("read file data succeed");
  5716. // let buf = buffer.from(arrayBuffer, 0, readLen);
  5717. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  5718. // 检查 buf 是否为空
  5719. if (buf.length === 0) {
  5720. throw new Error("Buffer is empty after reading the file");
  5721. }
  5722. try {
  5723. // 检测文件编码
  5724. // let detectedEncoding = chardet.detect(buf);
  5725. // console.info("onecoldT Detected encoding: " + detectedEncoding);
  5726. let detectedEncoding = this.detect(arrayBuffer)
  5727. console.info("onecoldT Detected encoding: " + detectedEncoding);
  5728. // 使用检测到的编码解码,解决中文乱码问题
  5729. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  5730. console.info("onecoldT Detected textDecoder: " + textDecoder);
  5731. let fileContent = textDecoder.decode(buf);
  5732. console.info(`onecoldT The content of file1: ${fileContent}`);
  5733. //解密
  5734. if (isJiaMi) {
  5735. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  5736. }
  5737. console.info(`onecold The content of file2: ${fileContent}`);
  5738. this.lyricContent = fileContent
  5739. // 将文件内容按行分割成字符串数组
  5740. let lines = fileContent.split('\n').map(line => line.trim());
  5741. console.info(`onecold The content of file: ${fileContent}`);
  5742. // 3.解析歌词
  5743. let lyric = this.parser.parse(lines);
  5744. // 4.设置歌词
  5745. this.lyricController.setLyric(lyric);
  5746. this.lyricControllerXF.setLyric(lyric)
  5747. this.lyricControllerSingle.setLyric(lyric)
  5748. this.showSingleLyric = true
  5749. console.info(`The content of file: ${fileContent}`);
  5750. } catch (chardetError) {
  5751. console.error("chardet.detect failed with error: " + chardetError.message);
  5752. this.lyricController.setLyric(null);
  5753. this.lyricControllerXF.setLyric(null)
  5754. this.lyricControllerSingle.setLyric(null)
  5755. }
  5756. })
  5757. .catch((err: BusinessError) => {
  5758. this.lyricController.setLyric(null)
  5759. this.lyricControllerXF.setLyric(null)
  5760. this.lyricControllerSingle.setLyric(null)
  5761. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  5762. })
  5763. .catch((err: Error) => {
  5764. this.lyricController.setLyric(null)
  5765. this.lyricControllerXF.setLyric(null)
  5766. this.lyricControllerSingle.setLyric(null)
  5767. console.error("read file 2 data failed with error message: " + err.message);
  5768. })
  5769. .finally(() => {
  5770. fs.closeSync(file);
  5771. });
  5772. } catch (error) {
  5773. this.lyricController.setLyric(null)
  5774. this.lyricControllerSingle.setLyric(null)
  5775. this.lyricControllerXF.setLyric(null)
  5776. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  5777. }
  5778. }
  5779. detect(data: ArrayBuffer): string {
  5780. //创建检测对象
  5781. let detector: UniversalDetector = new UniversalDetector();
  5782. // 传入检测数据并实时判断编码格式
  5783. detector.handleData(data, 0, data.byteLength);
  5784. // 标记检测数据 读取结束
  5785. detector.dataEnd();
  5786. // 获取检测结果
  5787. let detected: string = detector.getDetectedCharset();
  5788. // 释放资源
  5789. detector.reset();
  5790. return detected;
  5791. }
  5792. //初始化悬浮歌词的自定义设置
  5793. initPipLyricSetting() {
  5794. this.lyricControllerXF
  5795. .setTextSize(this.currentLyricSize)
  5796. .setCacheSize(4)
  5797. .setTextColor("#DDDDDD")
  5798. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  5799. .setEmptyHint("")
  5800. .setAnimationDuration(1000)
  5801. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  5802. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 2)
  5803. this.setBlurDegree(this.blurDegreePip, true)
  5804. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  5805. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  5806. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  5807. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  5808. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  5809. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  5810. this.lyricControllerXF.setHightLightCenter(true)
  5811. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  5812. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  5813. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  5814. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  5815. if (this.pipBgIndex === 0) {
  5816. if (this.cover) {
  5817. this.pipBg = this.cover
  5818. } else {
  5819. this.pipBg = this.imageColor
  5820. }
  5821. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  5822. }
  5823. }
  5824. //根据item返回歌词内容
  5825. async getLyricContent(item: VideoItem): Promise<string> {
  5826. try {
  5827. let filePath = item.filePath;
  5828. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  5829. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  5830. let isJiaMi = false;
  5831. let realLyricPath = lyricPath;
  5832. if (FileUtil.accessSync(jiaMilyricPath)) {
  5833. isJiaMi = true;
  5834. realLyricPath = jiaMilyricPath;
  5835. console.info("onecold 找到加密本地歌词");
  5836. } else {
  5837. console.info("onecold 找到本地歌词");
  5838. }
  5839. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_WRITE);
  5840. let arrayBuffer = new ArrayBuffer(4096);
  5841. const readLen = await fs.read(file.fd, arrayBuffer);
  5842. console.info("read file data succeed");
  5843. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  5844. if (buf.length === 0) {
  5845. throw new Error("Buffer is empty after reading the file");
  5846. }
  5847. // let detectedEncoding = chardet.detect(buf);
  5848. let detectedEncoding = this.detect(arrayBuffer)
  5849. console.info("Detected encoding: " + detectedEncoding);
  5850. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  5851. let fileContent = textDecoder.decode(buf);
  5852. console.info(`onecold The content of file1: ${fileContent}`);
  5853. if (isJiaMi) {
  5854. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  5855. }
  5856. console.info(`onecold The content of file2: ${fileContent}`);
  5857. fs.closeSync(file);
  5858. return fileContent;
  5859. } catch (error) {
  5860. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  5861. return '';
  5862. }
  5863. }
  5864. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  5865. if (StrUtil.isEmpty(filePath)) {
  5866. return
  5867. }
  5868. try {
  5869. //将content进行加密
  5870. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  5871. let lyricContent = ''
  5872. if (isJiaMi) {
  5873. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  5874. } else {
  5875. lyricContent = content
  5876. }
  5877. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  5878. // 清空文件内容
  5879. await fileIo.truncate(file.fd, 0);
  5880. await fileIo.write(file.fd, lyricContent);
  5881. await fileIo.close(file);
  5882. console.log('onecold lyric file Data saved successfully.');
  5883. } catch (error) {
  5884. console.error('onecold lyric file Failed to save data:', error);
  5885. }
  5886. }
  5887. /**
  5888. * Get largest proportion color of an image.
  5889. */
  5890. getImageColor() {
  5891. if (!this.context) {
  5892. return;
  5893. }
  5894. let bg = Utility.getMusisBg()
  5895. this.imageLabel = bg
  5896. ColorConversion.setSysBarLightBackground(true);
  5897. this.context.resourceManager.getMediaContent(bg)
  5898. .then((value: Uint8Array) => {
  5899. let buffer = value.buffer as ArrayBuffer;
  5900. image.createImageSource(buffer).createPixelMap().then((pixelMap) => {
  5901. effectKit.createColorPicker(pixelMap, (error, colorPicker) => {
  5902. if (error) {
  5903. Logger.error('Failed to create color picker.');
  5904. } else {
  5905. let color = colorPicker.getLargestProportionColor();
  5906. let colorArr = ColorConversion.dealColor(color.red, color.green, color.blue);
  5907. this.imageColor = `rgba(${colorArr[0]}, ${colorArr[1]}, ${colorArr[2]}, 1)`;
  5908. }
  5909. })
  5910. let headFilter = effectKit.createEffect(pixelMap);
  5911. if (headFilter !== null) {
  5912. headFilter.blur(15);
  5913. headFilter.getEffectPixelMap().then((value) => {
  5914. this.imageLabelBg = value;
  5915. })
  5916. }
  5917. })
  5918. .catch((error: BusinessError) => {
  5919. Logger.error(`${error.code} + ${error.message}`)
  5920. })
  5921. })
  5922. .catch((error: BusinessError) => {
  5923. Logger.error(`${error.code} + ${error.message}`)
  5924. })
  5925. }
  5926. setImageColor(cover: string) {
  5927. if (!this.context) {
  5928. return;
  5929. }
  5930. if (cover === undefined) {
  5931. return;
  5932. }
  5933. ImageUtil.imagePathToPixelMap(cover).then((value) => {
  5934. let headFilter = effectKit.createEffect(value);
  5935. if (headFilter !== null) {
  5936. headFilter.blur(15);
  5937. headFilter.getEffectPixelMap().then((value) => {
  5938. this.imageLabelBg = value;
  5939. })
  5940. }
  5941. }).catch((error: BusinessError) => {
  5942. Logger.error(`${error.code} + ${error.message}`)
  5943. })
  5944. }
  5945. setImageColor2(cover: string) {
  5946. if (!this.context) {
  5947. return;
  5948. }
  5949. if (cover === undefined) {
  5950. return;
  5951. }
  5952. LogUtils.getInstance().LOGI("setImageColor2--> cover ==" + cover);
  5953. ImageUtils.getImageDealData(getContext(this), cover, this.videoUrl).then((data) => {
  5954. this.imageColor = data.imageColor;
  5955. if (data.blurPixelMap) {
  5956. this.imageLabelBg = data.blurPixelMap;
  5957. }
  5958. })
  5959. }
  5960. // 定义开始旋转的方法
  5961. // 定时器用于一百毫秒执行一次旋转角度
  5962. @State timer: number = 0
  5963. @State rotateAngle: number = 0
  5964. //封面旋转动画
  5965. animationRoFun() {
  5966. if (this.isPlaying && !this.isCoverRectangle) {
  5967. this.timer = setInterval(() => {
  5968. this.rotateAngle += 1
  5969. }, 100)
  5970. this.startRotation()
  5971. } else {
  5972. clearInterval(this.timer)
  5973. this.stopRotation()
  5974. }
  5975. }
  5976. // 定义开始旋转的方法
  5977. startRotation() {
  5978. if (this.isPlaying) {
  5979. animateTo({
  5980. duration: 777,
  5981. iterations: 1,
  5982. curve: Curve.Linear
  5983. }, () => {
  5984. this.rotateAngle2 = 0
  5985. })
  5986. }
  5987. }
  5988. // 回调,暂停和播放按钮回调,下一首和上一首
  5989. playChange() {
  5990. // if(this.isCoverRectangle){
  5991. // return
  5992. // }
  5993. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  5994. this.setIsPlaying(true)
  5995. this.animationState = AnimationStatus.Running
  5996. } else {
  5997. this.setIsPlaying(false)
  5998. this.animationState = AnimationStatus.Paused
  5999. }
  6000. }
  6001. // 定义停止旋转的方法
  6002. stopRotation() {
  6003. if (this.isCoverRectangle) {
  6004. this.rotateAngle = 0
  6005. } else {
  6006. //唱针以左上角为点选择逆时针40度
  6007. animateTo({
  6008. duration: 1000,
  6009. curve: Curve.Linear,
  6010. iterations: 1,
  6011. }, () => {
  6012. this.rotateAngle2 = -40;
  6013. });
  6014. }
  6015. }
  6016. @Builder
  6017. private LyricsTopItem() {
  6018. Row() {
  6019. Stack() {
  6020. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  6021. .height(55)
  6022. .width(55)
  6023. .alt(this.imageLabel)
  6024. .borderRadius(8)
  6025. .clickEffect({ level: ClickEffectLevel.HEAVY })
  6026. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  6027. }
  6028. .width('18%')
  6029. Column() {
  6030. Column() {
  6031. Text(this.name)
  6032. .fontSize(16)
  6033. .maxLines(1)
  6034. .fontWeight(FontWeight.Bolder)
  6035. .fontColor(this.currentLyricColor)
  6036. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  6037. Row() {
  6038. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  6039. .fontSize(13)
  6040. .fontWeight(FontWeight.Bold)
  6041. .padding({ top: 8 })
  6042. .fontColor(this.currentLyricColor)
  6043. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  6044. Blank()
  6045. }
  6046. }
  6047. .height('100%')
  6048. .width('100%')
  6049. .justifyContent(FlexAlign.Center)
  6050. .alignItems(HorizontalAlign.Start)
  6051. }
  6052. .height('100%')
  6053. .width('65%')
  6054. Column() {
  6055. Image($r('app.media.lyric'))
  6056. .width(28)
  6057. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6058. .margin({ right: 30 })
  6059. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6060. .onClick(() => {
  6061. this.isLyricSetting = !this.isLyricSetting;
  6062. })
  6063. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  6064. height: this.isCoverOpacity() ? '95%' : '88%',
  6065. dragBar: true,
  6066. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6067. showClose: true,
  6068. blurStyle: BlurStyle.Thin,
  6069. backgroundColor: Color.Transparent,
  6070. // title: { title: $r('app.string.lyric_setting') }
  6071. })
  6072. }
  6073. .width('18%')
  6074. }
  6075. .width('82%')
  6076. .height(58)
  6077. .justifyContent(FlexAlign.SpaceBetween)
  6078. }
  6079. //歌词显示
  6080. @Builder
  6081. PlayerLyrics() {
  6082. Column() {
  6083. Column() {
  6084. this.LyricsTopItem()
  6085. }
  6086. .height(this.isPuraWP() ? 15 : 58)
  6087. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  6088. Visibility.None : Visibility.Visible)
  6089. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  6090. .width("100%")
  6091. Column() {
  6092. LyricView2({
  6093. controller: this.lyricController,
  6094. enableSeek: true,
  6095. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  6096. seekLineColor: "#80ffffff", // 滑动定位线颜色
  6097. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  6098. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  6099. if (!this.isPlaying) {
  6100. this.startPlayOrResumePlay()
  6101. } else {
  6102. this.isSeekTo = true;
  6103. this.mDestroyPage = false;
  6104. this.showLoadIng();
  6105. this.seekTo(position + "");
  6106. this.isSeekTo = false;
  6107. }
  6108. return true
  6109. }
  6110. })
  6111. .width("100%")
  6112. .layoutWeight(1)
  6113. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  6114. if (this.isPhoneLan()) {
  6115. Column() {
  6116. this.playCenterView()
  6117. }
  6118. .margin({ bottom: 20, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  6119. }
  6120. }
  6121. .position({
  6122. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  6123. (this.isPuraWP() ? 58 : 99)
  6124. })
  6125. .justifyContent(FlexAlign.Center)
  6126. .height(this.isCoverOpacity() ? '95%' : '80%')
  6127. }
  6128. }
  6129. @Builder
  6130. SingleLyricView() {
  6131. Column() {
  6132. Column() {
  6133. LyricView2({
  6134. controller: this.lyricControllerSingle,
  6135. enableSeek: false,
  6136. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  6137. seekLineColor: "#80ffffff", // 滑动定位线颜色
  6138. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  6139. })
  6140. }
  6141. .height(66)
  6142. .margin({ bottom: 20 })
  6143. }
  6144. }
  6145. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  6146. @Builder
  6147. BottomControl() {
  6148. Column() {
  6149. //播放 暂停,下一首,上一首
  6150. this.playCenterView()
  6151. //播放进度条
  6152. this.playProgressView()
  6153. }
  6154. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 100) }) // 将 固定在底部
  6155. }
  6156. //播放控制上一首 下一首 暂停和播放
  6157. @Builder
  6158. playCenterView() {
  6159. Row() {
  6160. Row({ space: 20 }) {
  6161. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6162. //更多功能
  6163. Image($r('app.media.menu'))
  6164. .width(24)
  6165. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  6166. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  6167. height: this.isCoverOpacity() ? '95%' : '93%',
  6168. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6169. dragBar: true,
  6170. showClose: true,
  6171. blurStyle: BlurStyle.Thin,
  6172. backgroundColor: Color.Transparent,
  6173. })
  6174. }
  6175. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6176. .backgroundColor(Color.Transparent)
  6177. .onClick(() => {
  6178. this.isShowMoreView = !this.isShowMoreView;
  6179. })
  6180. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6181. Image($r('app.media.ic_previous'))
  6182. .width(33)
  6183. .clickEffect({ level: ClickEffectLevel.HEAVY })
  6184. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6185. }
  6186. .onClick(async () => {
  6187. this.playPrevious()
  6188. })
  6189. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6190. .backgroundColor(Color.Transparent)
  6191. .margin({ left: 5 })
  6192. }
  6193. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6194. Column() {
  6195. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  6196. (this.isCircleBtn ? $r('app.media.hm_pause') : $r('app.media.ic_public_play'))
  6197. : (this.isCircleBtn ? $r('app.media.hm_play2') : $r('app.media.ic_public_pause')))
  6198. .width(this.isPhoneLan() ? 48 : 60)
  6199. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6200. .fillColor(Color.White)
  6201. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6202. .onClick(async () => {
  6203. this.playOrPause()
  6204. })
  6205. }
  6206. }
  6207. .backgroundColor(Color.Transparent)
  6208. .layoutWeight(1)
  6209. .margin({ left: 38, right: 38 })
  6210. Row({ space: 20 }) {
  6211. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6212. Image($r('app.media.ic_next'))
  6213. .width(33)
  6214. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6215. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6216. .onClick(() => {
  6217. this.playNext();
  6218. })
  6219. }
  6220. .backgroundColor(Color.Transparent)
  6221. .margin({ right: 5 })
  6222. .width(33)
  6223. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6224. //添加或取消收藏
  6225. Image(Utility.getIsFav(this.favList, this.currentSong) ?
  6226. $r('app.media.add_fac_light') : $r('app.media.add_fac'))
  6227. .width(24)
  6228. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  6229. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6230. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6231. .onClick(async () => {
  6232. if (this.currentSong) {
  6233. this.doFav(this.currentSong)
  6234. }
  6235. })
  6236. }
  6237. .backgroundColor(Color.Transparent)
  6238. .width(24)
  6239. }
  6240. // .margin({ left: 5 })
  6241. }
  6242. .width('100%')
  6243. .margin({ left: 10, right: 10, bottom: this.isCoverOpacity() ? 0 : 20 })
  6244. .justifyContent(FlexAlign.Center)
  6245. }
  6246. //播放进度条
  6247. @Builder
  6248. playProgressView() {
  6249. Row() {
  6250. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6251. Column() {
  6252. if (this.playType === 0) {
  6253. Image($r('app.media.loop'))
  6254. .width($r('app.float.control_image_width'))
  6255. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6256. } else if (this.playType === 1) {
  6257. Image($r('app.media.single'))
  6258. .width($r('app.float.control_image_width'))
  6259. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6260. } else if (this.playType === 2) {
  6261. Image($r('app.media.normal_play'))
  6262. .width($r('app.float.control_image_width'))
  6263. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6264. } else if (this.playType === 3) {
  6265. Image($r('app.media.random'))
  6266. .width($r('app.float.control_image_width'))
  6267. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6268. }
  6269. }
  6270. }
  6271. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  6272. .animation({
  6273. duration: 666,
  6274. curve: 'ease-in-out' // 可选动画曲线
  6275. })
  6276. .backgroundColor(Color.Transparent)
  6277. .margin({ left: 20, right: 10 })
  6278. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6279. .onClick(async () => {
  6280. this.setLoopMode()
  6281. })
  6282. Text(this.currentTime)
  6283. .fontSize($r('app.float.slider_font_size'))
  6284. .fontColor(Color.White)
  6285. .margin(3)
  6286. Slider({
  6287. value: this.progressValue,
  6288. min: 0,
  6289. max: this.PROGRESS_MAX_VALUE,
  6290. step: 1,
  6291. style: SliderStyle.OutSet
  6292. })
  6293. .width('600px')
  6294. .blockColor('rgba(255,255,255,1)')
  6295. .trackColor('rgba(255,255,255,0.3)')
  6296. .selectedColor(Color.White)
  6297. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  6298. .layoutWeight(1)
  6299. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  6300. .showSteps(false)
  6301. .showTips(true)
  6302. .enabled(this.slideEnable)
  6303. .onChange((value: number, mode: SliderChangeMode) => {
  6304. // if (mode == 2) {
  6305. this.isSeekTo = true;
  6306. this.mDestroyPage = false;
  6307. this.showLoadIng();
  6308. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  6309. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  6310. this.seekTo(seekValue + "");
  6311. // this.setProgress()
  6312. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  6313. this.isSeekTo = false;
  6314. // }
  6315. })
  6316. Text(this.totalTime)
  6317. .fontSize($r('app.float.slider_font_size'))
  6318. .fontColor(Color.White)
  6319. .margin(3)
  6320. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  6321. //播放列表
  6322. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6323. Image($r('app.media.hm_playlist'))
  6324. .width($r('app.float.control_image_width'))
  6325. .fillColor(Color.White)
  6326. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6327. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  6328. height: '95%',
  6329. dragBar: true,
  6330. showClose: true,
  6331. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6332. blurStyle: BlurStyle.Thin,
  6333. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  6334. title: {
  6335. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  6336. + `(${this.songList.length}首)`
  6337. }
  6338. })
  6339. }
  6340. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  6341. .animation({
  6342. duration: 666,
  6343. curve: 'ease-in-out' // 可选动画曲线
  6344. })
  6345. .backgroundColor(Color.Transparent)
  6346. .margin({ right: 20, left: 10 })
  6347. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6348. .onClick(() => {
  6349. this.isShowSheetView = !this.isShowSheetView;
  6350. if (this.isPlayListBgGrass) {
  6351. this.isFrontWhite = true
  6352. } else {
  6353. this.isFrontWhite = false
  6354. }
  6355. setTimeout(() => {
  6356. this.playListScroller.scrollToIndex(this.curIndex, true, ScrollAlign.CENTER)
  6357. }, 123)
  6358. })
  6359. }
  6360. //x5的竖屏模式需要99%
  6361. .width(this.isPhonePortrait() ? '93.4%'
  6362. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  6363. .height(this.isPhoneLan() ? 25 : 33)
  6364. .animation({
  6365. duration: 666,
  6366. curve: 'ease-in-out' // 可选动画曲线
  6367. })
  6368. }
  6369. isBigScreen() {
  6370. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  6371. return true
  6372. }
  6373. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  6374. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  6375. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  6376. return false
  6377. } else {
  6378. return true
  6379. }
  6380. return false
  6381. }
  6382. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  6383. @State isCoverRectangle: boolean = false
  6384. @State isCoverTop: boolean = true
  6385. @Builder
  6386. CoverInfo() {
  6387. Column() {
  6388. //如果是方形,判断是不是封面在顶部,如果不是顶部,显示musicNameInfo, 如果是圆形显示musicNameInfo
  6389. if (this.isCoverRectangle) {
  6390. if (!this.isCoverTop) {
  6391. this.musicNameInfo(false)
  6392. }
  6393. } else {
  6394. this.musicNameInfo(false)
  6395. }
  6396. Stack() {
  6397. // 唱片旋转效果
  6398. Image($r('app.media.ic_music_disc'))
  6399. .width(250)
  6400. .height(250)
  6401. .margin({ right: 20, left: 20 })
  6402. .aspectRatio(1)
  6403. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  6404. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  6405. .borderRadius('100%')
  6406. .align(Alignment.Center)
  6407. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  6408. .rotate({
  6409. angle: this.rotateAngle,
  6410. centerX: "50%",
  6411. centerY: "50%",
  6412. })
  6413. .animation({
  6414. duration: 100,
  6415. curve: Curve.Linear
  6416. })
  6417. .shadow({
  6418. radius: 30,
  6419. color: this.randomColor
  6420. })
  6421. Column() {
  6422. if (this.isCoverTop && !this.isCoverOpacity() && this.isCoverRectangle) {
  6423. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel :
  6424. this.cover)// .height(this.isCoverOpacity() ? 250 : this.isCoverRectangle ? 320 : 162)
  6425. .width(this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '86%')
  6426. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  6427. .alt(this.imageLabel)
  6428. .margin({ right: 8, left: 8, top: 8 })
  6429. .aspectRatio(1)
  6430. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  6431. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  6432. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  6433. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  6434. .animation({ duration: 500 }),
  6435. TransitionEffect.scale({ x: 0, y: 0 })))
  6436. .align(Alignment.Center)//
  6437. .clip(true)
  6438. .rotate({
  6439. x: 0,
  6440. y: 0,
  6441. z: 1,
  6442. angle: this.rotateAngle
  6443. })
  6444. .onClick(() => {
  6445. this.getImageColor()
  6446. })
  6447. this.musicNameInfo(false)
  6448. } else {
  6449. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  6450. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:220):(this.isCoverOpacity() ? 250 : this.isCoverRectangle ? 320 : 162))
  6451. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  6452. .alt(this.imageLabel)
  6453. .margin({ right: 20, left: 20 })
  6454. .aspectRatio(1)
  6455. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  6456. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  6457. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  6458. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  6459. .animation({ duration: 500 }),
  6460. TransitionEffect.scale({ x: 0, y: 0 })))
  6461. .align(Alignment.Center)//
  6462. .clip(true)
  6463. .rotate({
  6464. x: 0,
  6465. y: 0,
  6466. z: 1,
  6467. angle: this.rotateAngle
  6468. })
  6469. .onClick(() => {
  6470. this.getImageColor()
  6471. })
  6472. if (this.isPhoneLan()) {
  6473. Text(this.name)
  6474. .fontSize(18)
  6475. .fontWeight(FontWeight.Bold)
  6476. .margin({ top: 13 })
  6477. .textOverflow({ overflow: TextOverflow.Ellipsis })
  6478. .maxLines(1)
  6479. .width('99%')
  6480. .textAlign(TextAlign.Center)
  6481. .fontColor(Color.White)
  6482. }
  6483. }
  6484. }
  6485. // 唱针以左上角为点选择逆时针40度
  6486. Image($r('app.media.ic_music_cover_hand'))
  6487. .height(130)
  6488. .margin({ bottom: 220, top: 0 })
  6489. .align(Alignment.Top)
  6490. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  6491. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  6492. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  6493. Column({ space: 8 }) {
  6494. Text(this.name)
  6495. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  6496. .fontWeight(FontWeight.Bold)
  6497. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6498. .maxLines(1)
  6499. .width('48%')
  6500. .textAlign(TextAlign.Center)
  6501. .fontColor(Color.White)
  6502. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  6503. Text(this.artist)
  6504. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  6505. .fontColor(Color.White)
  6506. .fontWeight(FontWeight.Bold)
  6507. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  6508. }
  6509. .justifyContent(FlexAlign.Start)
  6510. .zIndex(1)
  6511. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  6512. }
  6513. .margin({
  6514. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  6515. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  6516. top: this.isCoverOpacity() ? 0 : 20
  6517. })
  6518. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  6519. this.SingleLyricView()
  6520. }
  6521. if (this.isPhoneLan()) {
  6522. Column() {
  6523. this.playProgressView()
  6524. }
  6525. .position({ left: 40, bottom: 48 })
  6526. } else {
  6527. this.BottomControl()
  6528. }
  6529. }
  6530. .width(CommonConstants.FULL_PERCENT)
  6531. .clip(true)
  6532. }
  6533. @Builder
  6534. private musicNameInfo(isHidden: boolean) {
  6535. Column({ space: 8 }) {
  6536. Text(this.name)
  6537. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22)
  6538. .fontWeight(FontWeight.Bold)
  6539. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6540. .maxLines(1)
  6541. .width('99%')
  6542. .textAlign(TextAlign.Center)
  6543. .fontColor(Color.White)
  6544. Text(this.artist + ' ' + this.currentSong?.album)
  6545. .fontSize(this.isCoverOpacity() ? 12 : 15)
  6546. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6547. .fontColor(Color.White)
  6548. .textAlign(TextAlign.Center)
  6549. .width('99%')
  6550. .maxLines(1)
  6551. }
  6552. .margin({ top: this.isCoverOpacity() ? 20 : isHidden ? 40 : 20 })
  6553. .zIndex(1)
  6554. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  6555. }
  6556. @Builder
  6557. private PlayTitle() {
  6558. Row() {
  6559. Row() {
  6560. Image($r('app.media.ic_back_down'))
  6561. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  6562. .hitTestBehavior(HitTestMode.Transparent)
  6563. Text(this.name + ' ' + this.artist)
  6564. .fontColor(Color.White)
  6565. .fontSize($r('app.float.title_font_size'))
  6566. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6567. .maxLines(1)
  6568. .visibility(Visibility.None)
  6569. .margin({ left: 2, right: 30 })
  6570. }
  6571. .layoutWeight(1)
  6572. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6573. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  6574. .onClick(() => {
  6575. this.isShowPlay = false;
  6576. })
  6577. Column() {
  6578. AVCastPicker({
  6579. normalColor: Color.White,
  6580. onStateChange: this.onStateVastChange
  6581. })
  6582. .width(24)
  6583. .height(24)
  6584. }
  6585. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  6586. }
  6587. .width(PlayConstants.ROW_WIDTH)
  6588. }
  6589. @Builder
  6590. lyricSettingSheet(isPip: boolean) {
  6591. Scroll() {
  6592. this.lyricSetting(isPip)
  6593. }
  6594. .width('100%')
  6595. .height('100%')
  6596. }
  6597. @Builder
  6598. lyricSetting(isPip: boolean) {
  6599. Column() {
  6600. // 时间调节模块
  6601. if (!isPip) {
  6602. this.BuildTimeControls()
  6603. }
  6604. // 字号控制模块
  6605. this.BuildFontControls(isPip)
  6606. }
  6607. }
  6608. // 歌词时间偏移状态
  6609. @State timeOffset: number = 0.0
  6610. @State currentLyricColor: string = '#FFFFFF'
  6611. @State currentLyricColorPip: string = '#FFFFFF'
  6612. @State currentHighLightLyricColor: string = '#FF4081'
  6613. @State currentHighLightLyricColorPip: string = '#FF4081'
  6614. // 歌词字号状态
  6615. @State currentLyricSize: number = 20
  6616. @State currentLyricSizePip: number = 20
  6617. // 高亮歌词放大倍数
  6618. @State currentHightLyricSize: number = 1.2
  6619. @State currentHightLyricSizePip: number = 1.2
  6620. @State currentLyricLineSpace: number = 10
  6621. @State currentLyricLineSpacePip: number = 10
  6622. @State currentLyricAlignMode: number = 1
  6623. @State currentLyricAlignModePip: number = 1
  6624. @State blurDegree: number = 2
  6625. @State blurDegreePip: number = 2
  6626. @State isShowSelectColor: boolean = false
  6627. @State isShowHLSelectColor: boolean = false
  6628. @State isShowPipBgSelectColor: boolean = false
  6629. @State pipLyWidth: number = 330
  6630. @State pipLyHeight: number = 120
  6631. // 构建颜色选择器
  6632. @Builder
  6633. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  6634. Row({ space: 10 }) {
  6635. HSBColorPicker({
  6636. color: '#FFFFFF',
  6637. radius: 8,
  6638. layout: HSBColorPickerLayout.COLUMN,
  6639. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  6640. '#fa7105'],
  6641. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  6642. this.changeLyricColor(value, isPip, isBGPip)
  6643. })
  6644. .height(250)
  6645. .layoutWeight(1)
  6646. .padding(25)
  6647. }
  6648. .width('66%')
  6649. }
  6650. @State isOpenPip: boolean = false
  6651. @State pipBgIndex: number = 0
  6652. // 构建字号控制器
  6653. @Builder
  6654. BuildFontControls(isPip: boolean) {
  6655. Column() {
  6656. if (isPip) {
  6657. Column() {
  6658. Row() {
  6659. Text('悬浮歌词')
  6660. .margin({ left: 18 })
  6661. .fontSize(15)
  6662. .fontColor(Color.White)
  6663. .fontWeight(480)
  6664. .layoutWeight(1)
  6665. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  6666. .selectedColor(this.themeColor)
  6667. .switchPointColor(Color.White)
  6668. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6669. .margin({ right: 18 })
  6670. .onChange((checked: boolean) => {
  6671. this.isOpenPip = checked;
  6672. if (this.isOpenPip) {
  6673. this.startPip()
  6674. } else {
  6675. this.stopPip()
  6676. }
  6677. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  6678. })
  6679. .width(50)
  6680. .height(30);
  6681. }
  6682. .height(55)
  6683. }
  6684. .backgroundColor(Color.Transparent)
  6685. .borderRadius(15)
  6686. .margin({
  6687. left: 30,
  6688. right: 30,
  6689. top: 0,
  6690. bottom: 20
  6691. })
  6692. .padding(0)
  6693. .border({
  6694. color: Color.White,
  6695. width: 1.8
  6696. })
  6697. }
  6698. Row() {
  6699. Text(`歌词居中:`)
  6700. .fontSize(14)
  6701. .fontColor(Color.White)
  6702. .margin({ left: 2 })
  6703. Row() {
  6704. ForEach(['居中', '居左'], (size: string, index: number) => {
  6705. Button(size)
  6706. .width(60)
  6707. .height(28)
  6708. .fontSize(12)
  6709. .fontColor('#FFFFFF')
  6710. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  6711. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  6712. .border({
  6713. color: (!isPip && this.currentLyricAlignMode === index) ||
  6714. (isPip && this.currentLyricAlignModePip === index) ?
  6715. '#007DFF' : '#DDDDDD',
  6716. width: 1.8
  6717. })
  6718. .onClick(() => {
  6719. this.setLyricAlignMode(index, isPip)
  6720. })
  6721. .margin({ left: 10, right: 8 })
  6722. })
  6723. }
  6724. .width('76%')
  6725. Blank()
  6726. }
  6727. .margin({
  6728. top: 10,
  6729. bottom: 10,
  6730. right: 20,
  6731. left: 20
  6732. })
  6733. if (isPip) {
  6734. Row() {
  6735. Text(`悬浮背景:`)
  6736. .fontSize(14)
  6737. .fontColor(Color.White)
  6738. Select([
  6739. { value: CommonConstants.PIP_LYRIC_BG[0] },
  6740. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  6741. .font({ size: 13, weight: FontWeight.Medium })
  6742. .fontColor(Color.White)
  6743. .margin({ left: 10 })
  6744. .selected(this.pipBgIndex)
  6745. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  6746. .onSelect(async (_index: number, text?: string | undefined) => {
  6747. this.pipBgIndex = _index
  6748. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  6749. if (this.pipBgIndex === 0) {
  6750. if (this.cover) {
  6751. this.pipBg = this.cover
  6752. } else {
  6753. this.pipBg = this.imageColor
  6754. }
  6755. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  6756. } else {
  6757. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  6758. }
  6759. })
  6760. Column() {
  6761. }
  6762. .backgroundColor(this.pipBg)
  6763. .margin({ left: 10, right: 10 })
  6764. .borderRadius(20)
  6765. .height(28)
  6766. .width(28)
  6767. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6768. Row() {
  6769. SymbolGlyph($r('sys.symbol.paintbrush'))
  6770. .fontColor([Color.White])
  6771. .effectStrategy(1)
  6772. Text(`选择颜色`)
  6773. .fontSize(13)
  6774. .margin({ left: 10 })
  6775. .fontColor(Color.White)
  6776. }
  6777. }
  6778. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  6779. .backgroundColor(Color.Transparent)
  6780. .border({
  6781. color: '#FFFFFF',
  6782. radius: 20,
  6783. width: 1.8
  6784. })
  6785. .height(36)
  6786. .width(110)
  6787. .onClick(() => {
  6788. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  6789. })
  6790. .bindPopup(this.isShowPipBgSelectColor, {
  6791. builder: this.SelectColor(false, isPip, true),
  6792. placement: Placement.Top,
  6793. mask: { color: '#33000000' },
  6794. enableArrow: false, //是否显示箭头
  6795. showInSubWindow: false,
  6796. onStateChange: (e) => {
  6797. if (!e.isVisible) {
  6798. this.isShowPipBgSelectColor = false
  6799. }
  6800. }
  6801. })
  6802. }
  6803. .width('76%')
  6804. .margin({ bottom: 5, right: 45, left: 20 })
  6805. }
  6806. if (!isPip) {
  6807. Row() {
  6808. Text(`高亮居中:`)
  6809. .fontSize(14)
  6810. .fontColor(Color.White)
  6811. Column() {
  6812. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  6813. .selectedColor(this.themeColor)
  6814. .switchPointColor(Color.White)
  6815. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6816. .onChange((checked: boolean) => {
  6817. this.isHightLightCenter = checked;
  6818. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  6819. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  6820. })
  6821. .width(50)
  6822. .height(30)
  6823. .alignSelf(ItemAlign.Start)
  6824. .margin({ left: 12 })
  6825. Blank()
  6826. }
  6827. .width('76%')
  6828. }
  6829. .margin({
  6830. left: 20,
  6831. right: 15,
  6832. top: 10,
  6833. bottom: 10
  6834. })
  6835. }
  6836. Row() {
  6837. Text(`歌词颜色:`)
  6838. .fontSize(14)
  6839. .fontColor(Color.White)
  6840. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  6841. .fontSize(15)
  6842. .fontColor(Color.White)
  6843. .margin({ left: 12, right: 12 })
  6844. Column() {
  6845. }
  6846. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  6847. .margin({ right: 12 })
  6848. .borderRadius(20)
  6849. .height(28)
  6850. .width(28)
  6851. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6852. Row() {
  6853. SymbolGlyph($r('sys.symbol.paintbrush'))
  6854. .fontColor([Color.White])
  6855. .effectStrategy(1)
  6856. Text(`选择颜色`)
  6857. .fontSize(13)
  6858. .margin({ left: 10 })
  6859. .fontColor(Color.White)
  6860. }
  6861. }
  6862. .backgroundColor(Color.Transparent)
  6863. .border({
  6864. color: '#FFFFFF',
  6865. radius: 20,
  6866. width: 1.8
  6867. })
  6868. .height(36)
  6869. .width(110)
  6870. .onClick(() => {
  6871. this.isShowSelectColor = !this.isShowSelectColor
  6872. })
  6873. .bindPopup(this.isShowSelectColor, {
  6874. builder: this.SelectColor(false, isPip),
  6875. placement: Placement.Top,
  6876. mask: { color: '#33000000' },
  6877. enableArrow: false, //是否显示箭头
  6878. showInSubWindow: false,
  6879. onStateChange: (e) => {
  6880. if (!e.isVisible) {
  6881. this.isShowSelectColor = false
  6882. }
  6883. }
  6884. })
  6885. }
  6886. .width('76%')
  6887. .margin({
  6888. top: 10,
  6889. bottom: 10,
  6890. right: 45,
  6891. left: 20
  6892. })
  6893. Row() {
  6894. Text(`高亮颜色:`)
  6895. .fontSize(14)
  6896. .fontColor(Color.White)
  6897. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  6898. .fontSize(15)
  6899. .fontColor(Color.White)
  6900. .margin({ left: 12, right: 12 })
  6901. Column() {
  6902. }
  6903. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  6904. .margin({ right: 12 })
  6905. .borderRadius(20)
  6906. .height(28)
  6907. .width(28)
  6908. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6909. Row() {
  6910. SymbolGlyph($r('sys.symbol.paintbrush'))
  6911. .fontColor([Color.White])
  6912. .effectStrategy(1)
  6913. Text(`选择颜色`)
  6914. .fontSize(13)
  6915. .margin({ left: 10 })
  6916. .fontColor(Color.White)
  6917. }
  6918. }
  6919. .backgroundColor(Color.Transparent)
  6920. .border({
  6921. color: '#FFFFFF',
  6922. radius: 20,
  6923. width: 1.8
  6924. })
  6925. .height(36)
  6926. .width(110)
  6927. .onClick(() => {
  6928. this.isShowHLSelectColor = !this.isShowHLSelectColor
  6929. })
  6930. .bindPopup(this.isShowHLSelectColor, {
  6931. builder: this.SelectColor(true, isPip),
  6932. placement: Placement.Top,
  6933. mask: { color: '#33000000' },
  6934. enableArrow: false, //是否显示箭头
  6935. showInSubWindow: false,
  6936. onStateChange: (e) => {
  6937. if (!e.isVisible) {
  6938. this.isShowHLSelectColor = false
  6939. }
  6940. }
  6941. })
  6942. }
  6943. .width('76%')
  6944. .margin({
  6945. top: 10,
  6946. bottom: 10,
  6947. right: 45,
  6948. left: 20
  6949. })
  6950. if (isPip) {
  6951. Row() {
  6952. Text(`显示宽度:`)
  6953. .fontSize(14)
  6954. .fontColor(Color.White)
  6955. Slider({
  6956. value: this.pipLyWidth,
  6957. min: 10,
  6958. max: 800,
  6959. step: 1,
  6960. style: SliderStyle.OutSet
  6961. })
  6962. .blockColor(this.themeColor)
  6963. .trackColor($r('app.color.speed_text_color'))
  6964. .selectedColor(Color.White)
  6965. .trackThickness(6)
  6966. .onChange((value: number) => {
  6967. this.pipLyWidth = value
  6968. if (this.pipController) {
  6969. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  6970. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  6971. }
  6972. })
  6973. .width('76%')
  6974. }
  6975. .margin({
  6976. left: 20,
  6977. right: 15,
  6978. top: 5,
  6979. bottom: 5
  6980. })
  6981. Row() {
  6982. Text(`显示高度:`)
  6983. .fontSize(14)
  6984. .fontColor(Color.White)
  6985. Slider({
  6986. value: this.pipLyHeight,
  6987. min: 10,
  6988. max: 1000,
  6989. step: 1,
  6990. style: SliderStyle.OutSet
  6991. })
  6992. .blockColor(this.themeColor)
  6993. .trackColor($r('app.color.speed_text_color'))
  6994. .selectedColor(Color.White)
  6995. .trackThickness(6)
  6996. .onChange((value: number) => {
  6997. this.pipLyHeight = value
  6998. if (this.pipController) {
  6999. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  7000. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  7001. }
  7002. })
  7003. .width('76%')
  7004. }
  7005. .margin({
  7006. left: 20,
  7007. right: 15,
  7008. top: 5,
  7009. bottom: 5
  7010. })
  7011. }
  7012. Row() {
  7013. Text(`歌词字号:`)
  7014. .fontSize(14)
  7015. .fontColor(Color.White)
  7016. Slider({
  7017. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  7018. min: 12,
  7019. max: 30,
  7020. step: 0.1,
  7021. style: SliderStyle.OutSet
  7022. })
  7023. .blockColor(this.themeColor)
  7024. .trackColor($r('app.color.speed_text_color'))
  7025. .selectedColor(Color.White)
  7026. .trackThickness(6)
  7027. .onChange((value: number) => {
  7028. this.setLyricTextSize(value, isPip)
  7029. })
  7030. .width('76%')
  7031. }
  7032. .margin({
  7033. left: 20,
  7034. right: 15,
  7035. top: 5,
  7036. bottom: 5
  7037. })
  7038. Row() {
  7039. Text(`高亮倍数:`)
  7040. .fontSize(14)
  7041. .fontColor(Color.White)
  7042. Slider({
  7043. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  7044. min: 1,
  7045. max: 2,
  7046. step: 0.1,
  7047. style: SliderStyle.OutSet
  7048. })
  7049. .blockColor(this.themeColor)
  7050. .trackColor($r('app.color.speed_text_color'))
  7051. .selectedColor(Color.White)
  7052. .trackThickness(6)
  7053. .onChange((value: number) => {
  7054. this.setHighLyricTextSize(value, isPip)
  7055. })
  7056. .width('76%')
  7057. }
  7058. .margin({
  7059. left: 20,
  7060. right: 15,
  7061. top: 5,
  7062. bottom: 5
  7063. })
  7064. Row() {
  7065. Text(`歌词间隙:`)
  7066. .fontSize(14)
  7067. .fontColor(Color.White)
  7068. Slider({
  7069. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  7070. min: 0,
  7071. max: 100,
  7072. step: 1,
  7073. style: SliderStyle.OutSet
  7074. })
  7075. .blockColor(this.themeColor)
  7076. .trackColor($r('app.color.speed_text_color'))
  7077. .selectedColor(Color.White)
  7078. .trackThickness(6)
  7079. .onChange((value: number) => {
  7080. this.setLyricLineSpace(value, isPip)
  7081. })
  7082. .width('76%')
  7083. }
  7084. .margin({
  7085. left: 20,
  7086. right: 15,
  7087. top: 5,
  7088. bottom: 5
  7089. })
  7090. //取值间隔为100,默认为400,取值越大,字体越粗
  7091. Row() {
  7092. Text(`歌词字重:`)
  7093. .fontSize(14)
  7094. .fontColor(Color.White)
  7095. Slider({
  7096. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  7097. min: 100,
  7098. max: 900,
  7099. step: 100,
  7100. style: SliderStyle.OutSet
  7101. })
  7102. .blockColor(this.themeColor)
  7103. .trackColor($r('app.color.speed_text_color'))
  7104. .selectedColor(Color.White)
  7105. .trackThickness(6)
  7106. .onChange((value: number) => {
  7107. if (isPip) {
  7108. this.lyricTextWeightPip = value
  7109. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  7110. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  7111. } else {
  7112. this.lyricTextWeight = value
  7113. this.lyricController.setTextWeight(this.lyricTextWeight)
  7114. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  7115. }
  7116. })
  7117. .width('76%')
  7118. }
  7119. .margin({
  7120. left: 20,
  7121. right: 15,
  7122. top: 5,
  7123. bottom: 5
  7124. })
  7125. if (!isPip) {
  7126. Row() {
  7127. Text(`歌词模糊:`)
  7128. .fontSize(14)
  7129. .fontColor(Color.White)
  7130. Slider({
  7131. value: isPip ? this.blurDegreePip : this.blurDegree,
  7132. min: 0,
  7133. max: 5,
  7134. step: 0.1,
  7135. style: SliderStyle.OutSet
  7136. })
  7137. .blockColor(this.themeColor)
  7138. .trackColor($r('app.color.speed_text_color'))
  7139. .selectedColor(Color.White)
  7140. .trackThickness(6)
  7141. .onChange((value: number) => {
  7142. this.setBlurDegree(value, isPip)
  7143. })
  7144. .width('76%')
  7145. }
  7146. .margin({
  7147. left: 20,
  7148. right: 15,
  7149. top: 5,
  7150. bottom: 15
  7151. })
  7152. }
  7153. Row() {
  7154. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  7155. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  7156. }
  7157. .justifyContent(FlexAlign.Center)
  7158. .margin({ top: 3, bottom: 10 })
  7159. }
  7160. }
  7161. private setBlurDegree(index: number, isPip: boolean) {
  7162. if (isPip) {
  7163. this.blurDegreePip = index
  7164. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  7165. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  7166. } else {
  7167. this.blurDegree = index
  7168. this.lyricController.setBlurDegree(this.blurDegree)
  7169. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  7170. }
  7171. }
  7172. private setLyricAlignMode(index: number, isPip: boolean) {
  7173. if (isPip) {
  7174. this.currentLyricAlignModePip = index
  7175. if (this.currentLyricAlignModePip === 1) {
  7176. this.lyricControllerXF.setAlignMode("left")
  7177. } else {
  7178. this.lyricControllerXF.setAlignMode("center")
  7179. }
  7180. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  7181. } else {
  7182. this.currentLyricAlignMode = index
  7183. if (this.currentLyricAlignMode === 1) {
  7184. this.lyricController.setAlignMode("left")
  7185. } else {
  7186. this.lyricController.setAlignMode("center")
  7187. }
  7188. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  7189. }
  7190. }
  7191. private setLyricTextSize(index: number, isPip: boolean) {
  7192. if (isPip) {
  7193. this.currentLyricSizePip = index
  7194. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  7195. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  7196. } else {
  7197. this.currentLyricSize = index
  7198. this.lyricController.setTextSize(this.currentLyricSize)
  7199. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  7200. }
  7201. }
  7202. private setHighLyricTextSize(scale: number, isPip: boolean) {
  7203. if (isPip) {
  7204. this.currentHightLyricSizePip = scale
  7205. this.lyricControllerXF
  7206. .setHighlightScale(this.currentHightLyricSizePip)
  7207. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  7208. } else {
  7209. this.currentHightLyricSize = scale
  7210. this.lyricController
  7211. .setHighlightScale(this.currentHightLyricSize)
  7212. PreferencesUtil.putSync('HighLyricTextSize', scale)
  7213. }
  7214. }
  7215. private setLyricLineSpace(index: number, isPip: boolean) {
  7216. if (isPip) {
  7217. this.currentLyricLineSpacePip = index
  7218. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  7219. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  7220. } else {
  7221. this.currentLyricLineSpace = index
  7222. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  7223. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  7224. }
  7225. }
  7226. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  7227. LogUtil.info('onecold isBG = ' + isBG)
  7228. if (isBG) { //如果是设置悬浮背景
  7229. this.pipBg = color
  7230. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  7231. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  7232. return
  7233. }
  7234. if (isPip) {
  7235. this.currentLyricColorPip = color
  7236. this.lyricControllerXF
  7237. .setTextColor(this.currentLyricColorPip)
  7238. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  7239. } else {
  7240. this.currentLyricColor = color
  7241. this.lyricController
  7242. .setTextColor(this.currentLyricColor)
  7243. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  7244. }
  7245. }
  7246. private changeLyricHightLightColor(color: string, isPip: boolean) {
  7247. if (isPip) {
  7248. this.currentHighLightLyricColorPip = color
  7249. this.lyricControllerXF
  7250. .setHighlightColor(this.currentHighLightLyricColorPip)
  7251. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  7252. } else {
  7253. this.currentHighLightLyricColor = color
  7254. this.lyricController
  7255. .setHighlightColor(this.currentHighLightLyricColor)
  7256. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  7257. }
  7258. }
  7259. // 构建时间控制器
  7260. @Builder
  7261. BuildTimeControls() {
  7262. Column() {
  7263. // 时间显示
  7264. Text(this.getTimeText())
  7265. .fontSize(18)
  7266. .fontColor(Color.White)
  7267. .margin({ bottom: 10 })
  7268. Row() {
  7269. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  7270. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  7271. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  7272. }
  7273. .justifyContent(FlexAlign.Center)
  7274. }
  7275. .margin({ top: 12, bottom: 8 })
  7276. }
  7277. // 精度按钮组件
  7278. @Builder
  7279. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  7280. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7281. Column() {
  7282. Image(icon)
  7283. .width(28)
  7284. .margin({ bottom: 5 })
  7285. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  7286. Text(label)
  7287. .fontSize(12)
  7288. .fontColor('#FFFFFF')
  7289. }
  7290. }
  7291. .backgroundColor(Color.Transparent)
  7292. .enabled(!this.isButtonDisabled(step))
  7293. .onClick(() => this.handlePrecisionAdjust(step))
  7294. .padding(5)
  7295. .width(66)
  7296. .height(66)
  7297. .margin({ left: 18, right: 18 })
  7298. .border({
  7299. color: '#FFFFFF',
  7300. width: 1.8
  7301. })
  7302. }
  7303. private handlePrecisionAdjust(step: number) {
  7304. if (step === 0) {
  7305. this.timeOffset = 0
  7306. return
  7307. }
  7308. // 精度处理:保留1位小数
  7309. const newOffset = Number((this.timeOffset + step).toFixed(5))
  7310. // 边界保护(±15.0秒)
  7311. if (newOffset < -30.0 || newOffset > 30.0) {
  7312. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  7313. return
  7314. }
  7315. // 状态更新
  7316. this.timeOffset = newOffset
  7317. }
  7318. // 按钮禁用逻辑
  7319. private isButtonDisabled(step: number): boolean {
  7320. const futureOffset = this.timeOffset + step
  7321. return (futureOffset < -30.0) || (futureOffset > 30.0)
  7322. }
  7323. // 时间显示文本升级
  7324. private getTimeText(): string {
  7325. const absValue = Math.abs(this.timeOffset)
  7326. return this.timeOffset === 0
  7327. ? '歌词时间已重置'
  7328. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  7329. }
  7330. // 导入 本地歌词 搜索歌词
  7331. @Builder
  7332. pushLyricButton(icon: Resource, step: number, label: string) {
  7333. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7334. Row() {
  7335. Image(icon)
  7336. .width(14)
  7337. .margin({ left: 13 })
  7338. Text(label)
  7339. .fontSize(12)
  7340. .margin({ left: 6 })
  7341. .fontColor('#FFFFFF')
  7342. }
  7343. }
  7344. .onClick(() => {
  7345. switch (step) {
  7346. case 0:
  7347. this.callFilePickerSelectFileForLyric()
  7348. break;
  7349. case 1:
  7350. //判断是不是赞助会员
  7351. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  7352. this.isLyricSetting = false
  7353. this.showTipsDialog()
  7354. return
  7355. }
  7356. if (StrUtil.isNotEmpty(this.videoUrl)) {
  7357. ToastUtil.showToast('正在获取')
  7358. this.isLyricSetting = false
  7359. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  7360. this.initLyric(lyricPath, true);
  7361. }
  7362. break;
  7363. }
  7364. })
  7365. .padding(5)
  7366. .width(110)
  7367. .backgroundColor(Color.Transparent)
  7368. .height(40)
  7369. .margin({ left: 6, right: 6 })
  7370. .border({
  7371. color: '#FFFFFF',
  7372. radius: 20,
  7373. width: 1.8
  7374. })
  7375. }
  7376. showVipDialog() {
  7377. DialogHelper.showCustomContentDialog({
  7378. dialogId: 'vip',
  7379. title: "友情提示",
  7380. autoCancel: false, //点击遮障层时,不关闭弹窗
  7381. backCancel: true, //点击返回键,不关闭弹窗
  7382. contentBuilder: () => {
  7383. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  7384. },
  7385. buttons: [],
  7386. })
  7387. }
  7388. //去赞助的自定义内容
  7389. @Builder
  7390. customVipBuilder(content: string) {
  7391. Column() {
  7392. Text(content)
  7393. .fontColor(Color.Gray)
  7394. .fontSize(16)
  7395. .alignSelf(ItemAlign.Start)
  7396. .margin({ bottom: 15 })
  7397. .fontSize(16)
  7398. Row() {
  7399. Button('取消')
  7400. .fontColor(Color.White)
  7401. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  7402. .height(50)
  7403. .layoutWeight(1)
  7404. .stateEffect(true)
  7405. .margin({ right: 6 })
  7406. .onClick(() => {
  7407. DialogHelper.closeDialog('vip'); //关闭弹框
  7408. })
  7409. Button('开通')
  7410. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  7411. .layoutWeight(1)
  7412. .height(50)
  7413. .backgroundColor(this.themeColor)
  7414. .stateEffect(true)
  7415. .margin({ left: 6 })
  7416. .onClick(() => {
  7417. DialogHelper.closeDialog('vip'); //关闭弹框
  7418. this.isShowPlay = false
  7419. this.mType = 1 //跳转到用户中心
  7420. // router.pushUrl({
  7421. // url: 'pages/VipPage'
  7422. // }, router.RouterMode.Single);
  7423. })
  7424. }
  7425. }
  7426. .width("100%")
  7427. .padding(10)
  7428. }
  7429. showTipsDialog() {
  7430. DialogHelper.showCustomContentDialog({
  7431. dialogId: 'tips',
  7432. title: "友情提示",
  7433. autoCancel: false, //点击遮障层时,不关闭弹窗
  7434. backCancel: true, //点击返回键,不关闭弹窗
  7435. contentBuilder: () => {
  7436. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  7437. },
  7438. buttons: [],
  7439. })
  7440. }
  7441. @Builder
  7442. customTipsBuilder(content: string) {
  7443. Column() {
  7444. Text(content)
  7445. .fontColor(Color.Gray)
  7446. .fontSize(16)
  7447. .alignSelf(ItemAlign.Start)
  7448. .margin({ bottom: 15 })
  7449. .fontSize(16)
  7450. Row() {
  7451. Button('取消')
  7452. .fontColor(Color.White)
  7453. .backgroundColor(this.themeColor)
  7454. .height(50)
  7455. .layoutWeight(1)
  7456. .stateEffect(true)
  7457. .margin({ right: 6 })
  7458. .onClick(() => {
  7459. DialogHelper.closeDialog('tips'); //关闭弹框
  7460. })
  7461. Button('跳转')
  7462. .fontColor(Color.White)//
  7463. .layoutWeight(1)
  7464. .height(50)
  7465. .backgroundColor(this.themeColor)
  7466. .stateEffect(true)
  7467. .margin({ left: 6 })
  7468. .onClick(() => {
  7469. DialogHelper.closeDialog('tips'); //关闭弹框
  7470. this.isShowPlay = false
  7471. this.mType = 3
  7472. // router.pushUrl({
  7473. // url: 'pages/SettingPage'
  7474. // }, router.RouterMode.Single);
  7475. })
  7476. }
  7477. }
  7478. .width("100%")
  7479. .padding(10)
  7480. }
  7481. @Builder
  7482. PlayMoreSheet() {
  7483. Column() {
  7484. this.MoreList()
  7485. }
  7486. .width('100%')
  7487. .height('100%')
  7488. }
  7489. @Builder
  7490. MoreList() {
  7491. Scroll() {
  7492. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  7493. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  7494. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7495. Row() {
  7496. if (more.id === 3&&this.currentSong) {
  7497. Image(more.image)
  7498. .width(24)
  7499. .height(24)
  7500. .margin({ left: 10, right: 10 })
  7501. Text(more.title)
  7502. .fontSize(16)
  7503. .fontColor(Color.White)
  7504. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  7505. height: this.isCoverOpacity() ? '95%' : '95%',
  7506. dragBar: true,
  7507. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7508. showClose: true,
  7509. blurStyle: BlurStyle.Thin,
  7510. backgroundColor: Color.Transparent,
  7511. title: { title: '歌曲信息' }
  7512. })
  7513. } else if (more.id === 15 && this.currentSong) { //编辑信息
  7514. Image(more.image)
  7515. .width(24)
  7516. .height(24)
  7517. .margin({ left: 10, right: 10 })
  7518. Text(more.title)
  7519. .fontSize(16)
  7520. .fontColor(Color.White)
  7521. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  7522. height: this.isCoverOpacity() ? '95%' : '93%',
  7523. dragBar: true,
  7524. showClose: true,
  7525. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7526. // blurStyle:BlurStyle.Thin,
  7527. // backgroundColor:Color.Transparent,
  7528. title: { title: '编辑信息' }
  7529. })
  7530. } else if (more.id === 5) { //定时关闭
  7531. Image(more.image)
  7532. .width(24)
  7533. .height(24)
  7534. .margin({ left: 10, right: 10 })
  7535. Text(more.title)
  7536. .fontSize(16)
  7537. .fontColor(Color.White)
  7538. .onClick(() => {
  7539. this.doMore(more.id)
  7540. })
  7541. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  7542. height: this.isCoverOpacity() ? '95%' : '95%',
  7543. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7544. dragBar: true,
  7545. showClose: true,
  7546. title: { title: $r('app.string.time_close') }
  7547. })
  7548. } else if (more.id === 2) { //歌词设置
  7549. Image(more.image)
  7550. .width(24)
  7551. .height(24)
  7552. .margin({ left: 10, right: 10 })
  7553. Text(more.title)
  7554. .fontSize(16)
  7555. .fontColor(Color.White)
  7556. } else if (more.id === 16) { //悬浮歌词设置
  7557. Image(more.image)
  7558. .width(24)
  7559. .height(24)
  7560. .margin({ left: 10, right: 10 })
  7561. Text(more.title)
  7562. .fontSize(16)
  7563. .fontColor(Color.White)
  7564. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  7565. height: this.isCoverOpacity() ? '95%' : '95%',
  7566. dragBar: true,
  7567. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7568. showClose: true,
  7569. blurStyle: BlurStyle.Thin,
  7570. backgroundColor: Color.Transparent,
  7571. title: { title: '悬浮歌词' }
  7572. })
  7573. } else if (more.id === 11) {
  7574. Image(more.image)
  7575. .width(24)
  7576. .height(24)
  7577. .margin({ left: 10, right: 10 })
  7578. Text(more.title)
  7579. .fontSize(16)
  7580. .fontColor(Color.White)
  7581. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  7582. height: this.isCoverOpacity() ? '95%' : '60%',
  7583. dragBar: true,
  7584. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7585. showClose: true,
  7586. blurStyle: BlurStyle.Thin,
  7587. backgroundColor: Color.Transparent,
  7588. title: { title: '跳过头尾' }
  7589. })
  7590. } else if (more.id === 12) { //投播
  7591. AVCastPicker({
  7592. customPicker: (): void => this.TPImageBuilder(more),
  7593. onStateChange: (state) => {
  7594. if (state == AVCastPickerState.STATE_APPEARING) {
  7595. console.log(' The picker starts showing.');
  7596. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  7597. console.log(' The picker finishes presenting.');
  7598. }
  7599. },
  7600. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  7601. sessionType: 'video'
  7602. })
  7603. .id('AVCastPicker')
  7604. } else {
  7605. Image(more.image)
  7606. .width(24)
  7607. .height(24)
  7608. .margin({ left: 10, right: 10 })
  7609. .onClick(() => {
  7610. this.doMore(more.id)
  7611. })
  7612. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  7613. .fontSize(16)
  7614. .fontColor(Color.White)
  7615. .onClick(() => {
  7616. this.doMore(more.id)
  7617. })
  7618. Select([//倍速
  7619. { value: '0.25x' },
  7620. { value: '0.5x' },
  7621. { value: '0.75x' },
  7622. { value: '1x' },
  7623. { value: '1.25x' },
  7624. { value: '1.5x' },
  7625. { value: '1.75x' },
  7626. { value: '2x' },
  7627. { value: '3x' }])
  7628. .font({ size: 16, weight: FontWeight.Medium })
  7629. .fontColor($r('sys.color.white'))
  7630. .margin({ left: 25 })
  7631. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  7632. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  7633. .value(Utility.optimizedFormat(this.playSpeed))
  7634. .onSelect(async (_index: number, text?: string | undefined) => {
  7635. let speed = parseFloat(text?.replace('x', '') || '1');
  7636. if (!CommonConstants.video_speed_list.includes(speed)) {
  7637. speed = 1;
  7638. }
  7639. this.playSpeed = speed
  7640. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  7641. })
  7642. Slider({
  7643. value: this.volume,
  7644. min: 0,
  7645. max: 1,
  7646. step: 0.1,
  7647. style: SliderStyle.OutSet
  7648. })
  7649. .margin({ left: 18, right: 8 })
  7650. .blockColor(this.themeColor)
  7651. .trackColor($r('app.color.speed_text_color'))
  7652. .selectedColor(Color.White)
  7653. .trackThickness(9)
  7654. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  7655. .onChange((value: number) => {
  7656. this.volume = value;
  7657. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  7658. PreferencesUtil.putSync('DefalutVolume',this.volume)
  7659. })
  7660. .layoutWeight(1)
  7661. Blank()
  7662. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  7663. .selectedColor(this.themeColor)
  7664. .switchPointColor(Color.White)
  7665. .margin({ right: 15 })
  7666. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7667. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  7668. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  7669. if (more.id == 6) {
  7670. this.isMusicMemoryPlay = checked;
  7671. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  7672. if (this.isMusicMemoryPlay) {
  7673. ToastUtil.showToast('记忆播放已开启')
  7674. } else {
  7675. ToastUtil.showToast('记忆播放已关闭')
  7676. }
  7677. }
  7678. })
  7679. .width(48)
  7680. .height(24);
  7681. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  7682. .selectedColor(this.themeColor)
  7683. .switchPointColor(Color.White)
  7684. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7685. .margin({ right: 15 })
  7686. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  7687. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  7688. if (more.id == 7) {
  7689. this.isMusicBGCover = checked;
  7690. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  7691. if (this.isMusicBGCover) {
  7692. ToastUtil.showToast('播放背景随音乐封面已开启')
  7693. } else {
  7694. ToastUtil.showToast('播放背景随音乐封面已关闭')
  7695. }
  7696. }
  7697. })
  7698. .width(48)
  7699. .height(24);
  7700. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  7701. .selectedColor(this.themeColor)
  7702. .switchPointColor(Color.White)
  7703. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7704. .margin({ right: 15 })
  7705. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  7706. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  7707. if (more.id == 8) {
  7708. this.isSavePlayMode = checked;
  7709. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  7710. if (this.isSavePlayMode) {
  7711. ToastUtil.showToast('保存播放模式已开启')
  7712. } else {
  7713. ToastUtil.showToast('保存播放模式已关闭')
  7714. }
  7715. }
  7716. })
  7717. .width(48)
  7718. .height(24);
  7719. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  7720. .selectedColor(this.themeColor)
  7721. .switchPointColor(Color.White)
  7722. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7723. .margin({ right: 15 })
  7724. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  7725. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  7726. if (more.id == 13) {
  7727. this.isCoverRectangle = checked;
  7728. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  7729. if (this.isCoverRectangle) {
  7730. ToastUtil.showToast('封面方形已开启')
  7731. this.animationRoFun()
  7732. } else {
  7733. ToastUtil.showToast('封面圆形已开启')
  7734. this.animationRoFun()
  7735. }
  7736. }
  7737. })
  7738. .width(48)
  7739. .height(24);
  7740. }
  7741. }
  7742. .width('100%')
  7743. .height(45)
  7744. .padding(15)
  7745. .backgroundColor(Color.Transparent)
  7746. .borderRadius(12)
  7747. .margin({ bottom: 6 })
  7748. }
  7749. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  7750. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  7751. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  7752. .backgroundColor(Color.Transparent)
  7753. .onClick(() => {
  7754. this.doMore(more.id)
  7755. })
  7756. });
  7757. }
  7758. .width('100%')
  7759. .padding(16)
  7760. }.margin({ bottom: 18 })
  7761. }
  7762. @Builder
  7763. TPImageBuilder(more: MoreItem): void {
  7764. Row() {
  7765. Image($r('app.media.tuoping'))
  7766. .width(22)
  7767. .height(22)
  7768. .margin({ left: 10, right: 10 })
  7769. Text(more.title)
  7770. .fontSize(16)
  7771. .fontColor(Color.White)
  7772. }
  7773. .width('100%')
  7774. .layoutWeight(1)
  7775. .alignItems(VerticalAlign.Center)
  7776. .justifyContent(FlexAlign.Start)
  7777. }
  7778. private moreItems: MoreItem[] = [
  7779. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  7780. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  7781. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  7782. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  7783. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  7784. { id: 15, image: $r('app.media.rename2'), title: '编辑信息' },
  7785. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  7786. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  7787. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  7788. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  7789. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  7790. { id: 4, image: $r('app.media.share2'), title: '分享' },
  7791. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  7792. { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  7793. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  7794. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  7795. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  7796. ];
  7797. @State isShowMoreView: boolean = false;
  7798. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  7799. @State isShowTimeCloseMore: boolean = false
  7800. @State isShowDetailMore: boolean = false
  7801. @State isMusicBGCover: boolean = true
  7802. @State isSavePlayMode: boolean = true
  7803. @State isLyricSetting: boolean = false
  7804. @State isJumpSetting: boolean = false
  7805. @State isShowEdit: boolean = false
  7806. @State showPipLyric: boolean = false
  7807. async setRingTone() {
  7808. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  7809. return
  7810. }
  7811. // 确定后的逻辑
  7812. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  7813. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  7814. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  7815. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  7816. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  7817. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  7818. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  7819. , this.videoUrl, this.name).then(res => {
  7820. LogUtil.info('onecold setFlag :' + res);
  7821. });
  7822. }
  7823. doMore(moreId: number) {
  7824. switch (moreId) {
  7825. case 2: //歌词
  7826. this.isLyricSetting = !this.isLyricSetting;
  7827. this.isShowMoreView = false
  7828. break;
  7829. case 3: //详情
  7830. this.isShowDetailMore = !this.isShowDetailMore;
  7831. break;
  7832. case 4: //分享
  7833. if (this.currentSong !== undefined) {
  7834. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  7835. }
  7836. this.isShowMoreView = false
  7837. break;
  7838. case 5: //定时关闭
  7839. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  7840. break;
  7841. case 10: //设为铃声
  7842. this.setRingTone()
  7843. this.isShowMoreView = false
  7844. break;
  7845. case 11: //跳过头尾
  7846. this.isJumpSetting = !this.isJumpSetting;
  7847. break;
  7848. case 13: //倍速
  7849. break;
  7850. case 14: //搜索封面
  7851. if (this.currentSong !== undefined) {
  7852. this.doSearchCover(this.currentSong)
  7853. }
  7854. this.isShowMoreView = false
  7855. break;
  7856. case 15: //编辑信息
  7857. this.isShowEdit = !this.isShowEdit;
  7858. break;
  7859. case 16: //悬浮歌词
  7860. this.showPipLyric = !this.showPipLyric;
  7861. break;
  7862. case 17: //横屏模式
  7863. if (this.isLandscape) {
  7864. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  7865. } else {
  7866. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  7867. }
  7868. this.isShowMoreView = false
  7869. break;
  7870. }
  7871. }
  7872. /**
  7873. * 切换横竖屏
  7874. *
  7875. */
  7876. setOrientation(orientation: number) {
  7877. this.windowClass.setPreferredOrientation(orientation).then(() => {
  7878. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  7879. }).catch((err: BusinessError) => {
  7880. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  7881. });
  7882. }
  7883. /**
  7884. * 画中画功能(悬浮歌词功能)
  7885. *
  7886. */
  7887. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  7888. pipController?: PiPWindow.PiPController;
  7889. navigationId: string = '';
  7890. @State curState: string = '';
  7891. @State curError: ResourceStr = '';
  7892. @State pipBg: string = '#E8E8E8'
  7893. @State buttonAction: string = '';
  7894. //开启画中画功能
  7895. async startPip() {
  7896. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  7897. if (!this.pipController) {
  7898. await this.createPipController();
  7899. }
  7900. if (!this.pipController) {
  7901. Logger.info(`[${TAG}] pipController create error`);
  7902. return;
  7903. }
  7904. await this.pipController.startPiP();
  7905. }
  7906. async stopPip() {
  7907. if (!this.pipController) {
  7908. Logger.info(`[${TAG}] pipController is not exist`);
  7909. return;
  7910. }
  7911. this.isOpenPip = false
  7912. await this.pipController.stopPiP();
  7913. }
  7914. async createPipController() {
  7915. this.pipController = await PiPWindow.create({
  7916. context: getContext(this),
  7917. componentController: this.xcomponentController,
  7918. navigationId: this.navigationId,
  7919. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  7920. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  7921. customUIController: this.nodeController,
  7922. });
  7923. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  7924. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  7925. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  7926. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  7927. this.onStateChange(state, reason);
  7928. });
  7929. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  7930. this.onActionEvent(event, status);
  7931. });
  7932. }
  7933. destroyPipController() {
  7934. if (!this.pipController) {
  7935. return;
  7936. }
  7937. this.pipController.off('stateChange');
  7938. this.pipController.off('controlPanelActionEvent');
  7939. this.pipController = undefined;
  7940. }
  7941. onStateChange(state: PiPWindow.PiPState, reason: string) {
  7942. switch (state) {
  7943. case PiPWindow.PiPState.ABOUT_TO_START:
  7944. this.curState = 'ABOUT_TO_START';
  7945. this.curError = $r('app.string.current_error_hint');
  7946. break;
  7947. case PiPWindow.PiPState.STARTED:
  7948. this.curState = 'STARTED';
  7949. this.curError = $r('app.string.current_error_hint');
  7950. break;
  7951. case PiPWindow.PiPState.ABOUT_TO_STOP:
  7952. this.curState = 'ABOUT_TO_STOP';
  7953. this.curError = $r('app.string.current_error_hint');
  7954. break;
  7955. case PiPWindow.PiPState.STOPPED:
  7956. this.curState = 'STOPPED';
  7957. this.curError = $r('app.string.current_error_hint');
  7958. this.stopPip()
  7959. this.destroyPipController()
  7960. break;
  7961. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  7962. this.curState = 'ABOUT_TO_RESTORE';
  7963. this.curError = $r('app.string.current_error_hint');
  7964. break;
  7965. case PiPWindow.PiPState.ERROR:
  7966. this.curState = 'ERROR';
  7967. this.curError = reason;
  7968. break;
  7969. default:
  7970. break;
  7971. }
  7972. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  7973. }
  7974. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  7975. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  7976. switch (event) {
  7977. case 'playbackStateChanged':
  7978. if (status === 0) {
  7979. this.pause();
  7980. } else {
  7981. this.startPlayOrResumePlay();
  7982. }
  7983. break;
  7984. case 'nextVideo':
  7985. // 切换到下一个视频
  7986. this.playNext()
  7987. break;
  7988. case 'previousVideo':
  7989. // 切换到上一个视频
  7990. this.playPrevious()
  7991. break;
  7992. case 'previousVideo':
  7993. // 切换到上一个视频
  7994. this.playPrevious()
  7995. break;
  7996. default:
  7997. }
  7998. this.buttonAction = event + `-status:${status}`;
  7999. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  8000. }
  8001. /**
  8002. * 画中画功能(悬浮歌词功能)结束
  8003. *
  8004. */
  8005. doSearchCover(item: VideoItem) {
  8006. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  8007. this.isShowMoreView = false
  8008. this.showTipsDialog()
  8009. return
  8010. }
  8011. if (item !== undefined) {
  8012. let artist = item?.artist
  8013. if (StrUtil.isEmpty(artist) || artist === undefined) {
  8014. artist = ''
  8015. }
  8016. this.searchCover(item, item.name, artist)
  8017. }
  8018. }
  8019. searchCover(item: VideoItem, title: string, artist: string) {
  8020. NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  8021. LogUtil.debug("onecold res =" + res)
  8022. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  8023. if (item.filePath == this.currentSong?.filePath) {
  8024. this.cover = res
  8025. if (this.currentSong) {
  8026. this.currentSong.pixelMapPath = res
  8027. }
  8028. }
  8029. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  8030. if (success) {
  8031. this.doUpdateData()
  8032. console.log(" onecold 更新音乐封面成功,数据库已同步");
  8033. } else {
  8034. console.error(" onecold 更新音乐封面数据库失败原因: " + error);
  8035. }
  8036. });
  8037. LogUtil.debug("onecold this.cover =" + this.cover)
  8038. }
  8039. })
  8040. }
  8041. @State jumpTopTime: number = 0
  8042. @State jumpEndTime: number = 0
  8043. @State isOpenJump: boolean = false
  8044. @Builder
  8045. JumpTopEndSheet() {
  8046. Scroll() {
  8047. Column() {
  8048. Column() {
  8049. Text('仅对本播放列表有效')
  8050. .fontSize(16)
  8051. .fontColor($r('app.color.text_color'))
  8052. // 跳过头尾
  8053. Column() {
  8054. Row() {
  8055. Text('跳过片头:')
  8056. .fontSize(16)
  8057. .fontColor($r('app.color.text_color'))
  8058. Text(this.jumpTopTime + 's')
  8059. .fontSize(16)
  8060. .fontColor($r('app.color.text_color'))
  8061. }
  8062. .margin({ bottom: 5 })
  8063. Row() {
  8064. Slider({
  8065. value: this.jumpTopTime,
  8066. min: 0,
  8067. max: 120,
  8068. step: 1,
  8069. style: SliderStyle.OutSet
  8070. })
  8071. .blockColor(this.themeColor)
  8072. .trackColor($r('app.color.speed_text_color'))
  8073. .selectedColor(Color.White)
  8074. .trackThickness(8)
  8075. .onChange((value: number) => {
  8076. this.jumpTopTime = value;
  8077. })
  8078. .width('85%')
  8079. }
  8080. .alignItems(VerticalAlign.Top)
  8081. }
  8082. .margin({ top: 10, bottom: 10 })
  8083. // 跳过头尾
  8084. Column() {
  8085. Row() {
  8086. Text('跳过片尾:')
  8087. .fontSize(16)
  8088. .fontColor($r('app.color.text_color'))
  8089. Text(this.jumpEndTime + 's')
  8090. .fontSize(16)
  8091. .fontColor($r('app.color.text_color'))
  8092. }
  8093. .margin({ bottom: 5 })
  8094. Row() {
  8095. Slider({
  8096. value: this.jumpEndTime,
  8097. min: 0,
  8098. max: 120,
  8099. step: 1,
  8100. style: SliderStyle.OutSet
  8101. })
  8102. .blockColor(this.themeColor)
  8103. .trackColor($r('app.color.speed_text_color'))
  8104. .selectedColor(Color.White)
  8105. .trackThickness(8)
  8106. .onChange((value: number) => {
  8107. this.jumpEndTime = value;
  8108. })
  8109. .width('85%')
  8110. }
  8111. .alignItems(VerticalAlign.Top)
  8112. }
  8113. .margin({ top: 10, bottom: 10 })
  8114. Row() {
  8115. Button('保存设置')
  8116. .fontColor(Color.White)
  8117. .layoutWeight(1)
  8118. .height(40)
  8119. .width(80)
  8120. .backgroundColor(this.themeColor)
  8121. .stateEffect(true)
  8122. .margin({ left: 0, bottom: 20 })
  8123. .onClick(async () => {
  8124. if (!Utility.isNoble()) {
  8125. this.isJumpSetting = false
  8126. this.isShowMoreView = false
  8127. this.showVipDialog()
  8128. return
  8129. }
  8130. if (this.currentSong === undefined) {
  8131. return
  8132. }
  8133. if (this.modeType === 0) {
  8134. let parentPath = FileUtil.getParentPath(this.videoUrl)
  8135. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  8136. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  8137. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  8138. } else if (this.modeType === 1) { //媒体库
  8139. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  8140. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  8141. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  8142. } else if (this.modeType === 2) { //艺术家
  8143. if (this.currentSong?.artist) {
  8144. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  8145. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  8146. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  8147. }
  8148. } else if (this.modeType === 3) { //专辑
  8149. if (this.currentSong?.album) {
  8150. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  8151. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  8152. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  8153. }
  8154. }
  8155. ToastUtil.showShort("保存成功")
  8156. this.isJumpSetting = false
  8157. })
  8158. }
  8159. .margin({
  8160. left: 38,
  8161. right: 38,
  8162. top: 10,
  8163. bottom: 10
  8164. })
  8165. .width(120)
  8166. .height(50)
  8167. }
  8168. }
  8169. }
  8170. .width('100%')
  8171. .height('100%')
  8172. }
  8173. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  8174. private onStateVastChange(state: AVCastPickerState) {
  8175. if (state == AVCastPickerState.STATE_APPEARING) {
  8176. console.log('The picker starts showing.');
  8177. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  8178. console.log('The picker finishes presenting.');
  8179. }
  8180. }
  8181. private showSelectLyric() {
  8182. DialogHelper.showActionSheetDialog({
  8183. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  8184. // sheets: ["本地歌词", "搜索歌词"],
  8185. sheets: [
  8186. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  8187. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  8188. ],
  8189. maskColor: Color.Transparent,
  8190. backgroundColor: $r('app.color.bg_card'),
  8191. transition: AnimationHelper.transitionInDown(666),
  8192. onAction: (index) => {
  8193. switch (index) {
  8194. case 0:
  8195. this.callFilePickerSelectFileForLyric()
  8196. break;
  8197. case 1:
  8198. if (StrUtil.isNotEmpty(this.videoUrl)) {
  8199. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  8200. this.initLyric(lyricPath);
  8201. }
  8202. break;
  8203. }
  8204. }
  8205. })
  8206. }
  8207. // 拉起picker选择文件管理器
  8208. async callFilePickerSelectFileForLyric(): Promise<void> {
  8209. try {
  8210. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  8211. DocumentSelectOptions.maxSelectNumber = 1
  8212. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  8213. let documentPicker = new picker.DocumentViewPicker();
  8214. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  8215. Logger.info(TAG,
  8216. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  8217. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  8218. this.saveVideoDatasLyric(DocumentSelectResult)
  8219. }
  8220. }).catch((err: BusinessError) => {
  8221. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  8222. });
  8223. } catch (err) {
  8224. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  8225. }
  8226. }
  8227. async saveVideoDatasLyric(uris: string[]) {
  8228. if (ArrayUtil.isEmpty(uris)) {
  8229. return
  8230. }
  8231. let newUris: string[] = [];
  8232. for (let i = 0; i < uris.length; i++) {
  8233. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  8234. Logger.info(TAG, 'filePath uri: ' + filePath);
  8235. newUris.push(filePath)
  8236. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  8237. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  8238. fileIo.copyFileSync(file.fd, file2.fd)
  8239. fileIo.closeSync(file);
  8240. fileIo.closeSync(file2);
  8241. this.initLyric(filePath)
  8242. }
  8243. }
  8244. private initDelayPlay(context: object) {
  8245. this.mContext = context;
  8246. }
  8247. startPipLyric() {
  8248. if (this.pipController) {
  8249. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  8250. PiPWindow.PiPControlStatus.PLAY);
  8251. }
  8252. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  8253. if (this.isOpenPip) {
  8254. this.startPip()
  8255. } else {
  8256. this.stopPip()
  8257. }
  8258. }
  8259. private startPlayOrResumePlay() {
  8260. this.startPipLyric()
  8261. this.mDestroyPage = false;
  8262. this.animationState = AnimationStatus.Running
  8263. LogUtils.getInstance().LOGI("startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  8264. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  8265. this.stopProgressTask();
  8266. this.startProgressTask();
  8267. this.play(this.videoUrl.toString());
  8268. }
  8269. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  8270. this.mIjkMediaPlayer.start();
  8271. this.setProgress()
  8272. this.CONTROL_PlayStatus = PlayStatus.PLAY
  8273. }
  8274. this.setIsPlaying(true)
  8275. this.updateSessionPlayState(true)
  8276. this.watchStatus();
  8277. this.updateLastPlayTimeStr(this.videoUrl)
  8278. }
  8279. updateLastPlayTimeStr(filePath: string) {
  8280. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  8281. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  8282. if (success) {
  8283. this.getHistoryList(false)
  8284. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  8285. } else {
  8286. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  8287. }
  8288. });
  8289. }
  8290. private completionNum(num: number): string | number {
  8291. if (num < 10) {
  8292. return '0' + num;
  8293. } else {
  8294. return num;
  8295. }
  8296. }
  8297. private stringForTime(timeMs: number): string {
  8298. let totalSeconds: number | string = (timeMs / 1000);
  8299. let newSeconds: number | string = totalSeconds % 60;
  8300. let minutes: number | string = (totalSeconds / 60) % 60;
  8301. let hours: number | string = totalSeconds / 3600;
  8302. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  8303. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  8304. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  8305. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  8306. if (this.isCurrentTime) {
  8307. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  8308. this.oldSeconds = newSeconds
  8309. } else {
  8310. newSeconds = this.oldSeconds
  8311. }
  8312. }
  8313. newSeconds = this.completionNum(newSeconds);
  8314. if (hours > 0) {
  8315. return hours + ":" + minutes + ":" + newSeconds;
  8316. } else {
  8317. return minutes + ":" + newSeconds;
  8318. }
  8319. }
  8320. private setProgress() {
  8321. let position = this.mIjkMediaPlayer.getCurrentPosition();
  8322. let duration = this.mIjkMediaPlayer.getDuration();
  8323. let pos = 0;
  8324. if (duration > 0) {
  8325. this.slideEnable = true;
  8326. let curPercent = position / duration;
  8327. pos = curPercent * 100;
  8328. if (pos > this.PROGRESS_MAX_VALUE) {
  8329. this.progressValue = this.PROGRESS_MAX_VALUE
  8330. } else {
  8331. this.progressValue = pos;
  8332. }
  8333. }
  8334. // LogUtils.getInstance()
  8335. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  8336. this.totalTime = this.stringForTime(duration);
  8337. if (position > duration) {
  8338. position = duration;
  8339. }
  8340. this.isCurrentTime = true;
  8341. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  8342. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  8343. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  8344. this.currentTime = this.stringForTime(position);
  8345. this.isCurrentTime = false
  8346. if (this.mIjkMediaPlayer.isPlaying()) {
  8347. this.randomColor =
  8348. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  8349. // 判断是否播放到结束时间
  8350. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  8351. if (position >= duration - this.jumpEndTime * 1000) {
  8352. this.playNext()
  8353. }
  8354. }
  8355. } else {
  8356. this.randomColor = 'rbg(0,0,0)'
  8357. }
  8358. }
  8359. private startProgressTask() {
  8360. let that = this;
  8361. this.updateProgressTimer = setInterval(() => {
  8362. //LogUtils.getInstance().LOGI("startProgressTask");
  8363. if (!that.mDestroyPage) {
  8364. that.setProgress();
  8365. }
  8366. }, 300);
  8367. }
  8368. private stopProgressTask() {
  8369. LogUtils.getInstance().LOGI("stopProgressTask");
  8370. clearInterval(this.updateProgressTimer);
  8371. }
  8372. private showLoadIng() {
  8373. this.loadingVisible = Visibility.Visible;
  8374. this.replayVisible = Visibility.None;
  8375. }
  8376. private hideLoadIng() {
  8377. this.loadingVisible = Visibility.None;
  8378. this.replayVisible = Visibility.None;
  8379. }
  8380. private showRePlay() {
  8381. this.loadingVisible = Visibility.None;
  8382. this.replayVisible = Visibility.Visible;
  8383. }
  8384. private async play(url: string) {
  8385. let that = this;
  8386. that.showLoadIng();
  8387. //设置XComponent回调的context
  8388. if (!!this.mContext) {
  8389. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  8390. }
  8391. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  8392. this.mIjkMediaPlayer.reset();
  8393. }
  8394. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  8395. //设置debug模式
  8396. this.mIjkMediaPlayer.setDebug(false);
  8397. //初始化配置
  8398. this.mIjkMediaPlayer.native_setup();
  8399. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  8400. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  8401. this.mIjkMediaPlayer.setVolume('1', '1');
  8402. }else{
  8403. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  8404. }
  8405. //设置视频源
  8406. this.mIjkMediaPlayer.setDataSource(url);
  8407. //设置视频源http请求头
  8408. let headers = new Map([
  8409. ["user_agent", "Mozilla/5.0 BiliDroid/7.30.0 (bbcallen@gmail.com)"],
  8410. ["referer", "https://www.bilibili.com"]
  8411. ]);
  8412. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  8413. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  8414. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  8415. // }
  8416. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  8417. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  8418. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  8419. const fileSize = await this.getFileSize(this.videoUrl);
  8420. let bufferSize = 1 * 1024 * 1024; // 默认缓冲区大小为2MB
  8421. if (fileSize > 3 * 1024 * 1024 * 1024) { // 文件大于3GB
  8422. bufferSize = 25 * 1024 * 1024; // 设置缓冲区大小为25MB
  8423. }
  8424. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  8425. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  8426. //停止预读的最小帧数
  8427. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  8428. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  8429. // 设置其他缓冲相关选项
  8430. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  8431. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  8432. //启动预加载
  8433. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  8434. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  8435. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  8436. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  8437. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  8438. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  8439. // 因此需要播放器丢包,才不会累积延时
  8440. // 这个和第三个参数packet-buffering无关。
  8441. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  8442. // 无限制收流
  8443. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  8444. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  8445. // 屏幕常亮
  8446. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  8447. // 设置超时
  8448. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  8449. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  8450. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  8451. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  8452. // 变速播放
  8453. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  8454. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  8455. let Speed = this.mIjkMediaPlayer.getSpeed()
  8456. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  8457. //是否开启循环播放
  8458. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  8459. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  8460. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  8461. if (height === 0) {
  8462. return;
  8463. }
  8464. const va = width / height;
  8465. const vpa = that.videoParentAspectRatio;
  8466. if (vpa > va) {
  8467. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  8468. } else {
  8469. that.videoWidth = '100%';
  8470. }
  8471. if (width && height) {
  8472. that.videoAspectRatio = width / height;
  8473. }
  8474. LogUtils.getInstance()
  8475. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  8476. that.hideLoadIng();
  8477. }
  8478. }
  8479. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  8480. let mOnPreparedListener: OnPreparedListener = {
  8481. onPrepared: async () => {
  8482. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  8483. try {
  8484. // this.cover = this.songList[this.curIndex].pixelMapPath
  8485. // this.artist = this.songList[this.curIndex].artist
  8486. // this.videoUrl = this.songList[this.curIndex].filePath
  8487. let isBgCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  8488. if (isBgCover && this.cover !== undefined && StrUtil.isNotEmpty(this.cover)) {
  8489. this.setImageColor2(this.cover)
  8490. } else {
  8491. this.getImageColor();
  8492. }
  8493. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  8494. await this.initLyric(lyricPath);
  8495. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  8496. this.avSessionController.initAvSession(false);
  8497. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  8498. this.setAvSessionListener();
  8499. this.updateSessionPlayState(true)
  8500. this.setCurrentPlayMode()
  8501. }, 500)
  8502. let timeoutPlay = 0
  8503. if (StrUtil.isNotEmpty(this.videoUrl) &&
  8504. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  8505. timeoutPlay = 1000
  8506. }
  8507. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  8508. if (this.modeType === 0) { //文件夹
  8509. let parentPath = FileUtil.getParentPath(this.videoUrl)
  8510. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  8511. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  8512. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  8513. } else if (this.modeType === 1) { //媒体库
  8514. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  8515. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  8516. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  8517. } else if (this.modeType === 2) { //艺术家
  8518. if (this.currentSong?.artist) {
  8519. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  8520. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  8521. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  8522. }
  8523. } else if (this.modeType === 3) { //专辑
  8524. if (this.currentSong?.album) {
  8525. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  8526. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  8527. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  8528. }
  8529. }
  8530. this.duration = this.mIjkMediaPlayer.getDuration()
  8531. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  8532. if (this.mIjkMediaPlayer != null) {
  8533. if (this.jumpTopTime * 1000 <= this.duration) {
  8534. // 调用 seekTo 方法,跳到指定时间
  8535. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  8536. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  8537. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  8538. }
  8539. }, timeoutPlay)
  8540. } else {
  8541. // 提示用户无法跳过
  8542. ToastUtil.showToast('跳过时间超过视频时长');
  8543. }
  8544. }
  8545. } else {
  8546. this.jumpTopTime = 0
  8547. this.jumpEndTime = 0
  8548. console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  8549. console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  8550. console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  8551. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  8552. //记忆播放(每一首都会记忆播放)
  8553. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  8554. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  8555. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  8556. this.restorePlaybackPosition() //读取播放记忆功能
  8557. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  8558. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  8559. this.restorePlaybackPosition() //读取播放记忆功能
  8560. }
  8561. this.isFirstStartPlay = false
  8562. }, timeoutPlay)
  8563. } else {
  8564. this.isFirstStartPlay = false
  8565. }
  8566. }
  8567. this.saveLastPlayList()
  8568. } catch (error) {
  8569. let err: BusinessError = error as BusinessError;
  8570. console.error('onecold failed with err: ' + JSON.stringify(err));
  8571. }
  8572. }
  8573. }
  8574. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  8575. let mOnTimedTextListener: OnTimedTextListener = {
  8576. onTimedText: () => {
  8577. }
  8578. }
  8579. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  8580. let mOnCompletionListener: OnCompletionListener = {
  8581. onCompletion: () => {
  8582. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  8583. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  8584. this.playNext()
  8585. } else if (this.playType == 1) { //1:单片重复播放
  8586. this.CONTROL_PlayStatus = PlayStatus.INIT
  8587. that.startPlayOrResumePlay();
  8588. } else if (this.playType == 2) { //2:正常播放,单曲播完
  8589. that.showRePlay();
  8590. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  8591. that.progressValue = this.PROGRESS_MAX_VALUE;
  8592. that.slideEnable = false;
  8593. that.stop();
  8594. // ToastUtil.showToast('开始重新播放')
  8595. } else if (this.playType == 3) { //3:随机播放
  8596. this.randomPlay()
  8597. }
  8598. }
  8599. }
  8600. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  8601. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  8602. onBufferingUpdate: (percent: number) => {
  8603. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  8604. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  8605. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  8606. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  8607. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  8608. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  8609. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  8610. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  8611. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  8612. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  8613. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  8614. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  8615. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  8616. let Looping = this.mIjkMediaPlayer.isLooping()
  8617. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  8618. }
  8619. }
  8620. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  8621. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  8622. onSeekComplete: () => {
  8623. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  8624. that.startPlayOrResumePlay();
  8625. }
  8626. }
  8627. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  8628. let mOnInfoListener: OnInfoListener = {
  8629. onInfo: (what: number, extra: number) => {
  8630. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  8631. that.hideLoadIng();
  8632. }
  8633. }
  8634. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  8635. let mOnErrorListener: OnErrorListener = {
  8636. onError: (what: number, extra: number) => {
  8637. this.stopProgressTask();
  8638. LogUtils.getInstance().LOGI("OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  8639. that.hideLoadIng();
  8640. if (StrUtil.isNotEmpty(this.videoUrl) && !FileUtil.accessSync(this.videoUrl)) {
  8641. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  8642. } else {
  8643. ToastUtil.showToast(getContext()
  8644. .resourceManager
  8645. .getStringByNameSync("Honey_the_video_is_playing_errant_The_system_is_wandering"))
  8646. }
  8647. }
  8648. }
  8649. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  8650. this.mIjkMediaPlayer.setMessageListener();
  8651. this.mIjkMediaPlayer.prepareAsync();
  8652. this.mIjkMediaPlayer.start();
  8653. }
  8654. //保存最后播放的那首歌和已经对应的播放列表
  8655. saveLastPlayList() {
  8656. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  8657. PreferencesUtil.putSync('LastMusicList', this.songList)
  8658. }
  8659. // 清空播放记录
  8660. clearVideoHistory() {
  8661. this.table.clearPlayHistory((success: boolean, error?: string) => {
  8662. if (success) {
  8663. this.historyList = [];
  8664. this.updateListData(this.historyList)
  8665. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  8666. ToastUtil.showToast('清空播放记录成功')
  8667. } else {
  8668. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  8669. }
  8670. });
  8671. }
  8672. public async setAvSessionListener() {
  8673. if (!this.avSessionController) {
  8674. return;
  8675. }
  8676. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  8677. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  8678. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  8679. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  8680. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  8681. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  8682. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  8683. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  8684. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  8685. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  8686. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  8687. }
  8688. setLoopMode() {
  8689. let itype = this.playType + 1
  8690. if (itype >= 4) {
  8691. this.playType = 0
  8692. ToastUtil.showToast('连续播放')
  8693. } else if (itype === 1) {
  8694. this.playType = 1
  8695. ToastUtil.showToast('单曲循环')
  8696. } else if (itype === 2) {
  8697. this.playType = 2
  8698. ToastUtil.showToast('单曲播完')
  8699. } else if (itype === 3) {
  8700. this.playType = 3
  8701. ToastUtil.showToast('随机播放')
  8702. } else if (itype === 0) {
  8703. this.playType = 0
  8704. ToastUtil.showToast('连续播放')
  8705. }
  8706. PreferencesUtil.putSync('musicPlayType', this.playType)
  8707. this.setCurrentPlayMode()
  8708. }
  8709. private sessionSetLoopModeCallback = (mode: number) => {
  8710. if (this.mIjkMediaPlayer != null) {
  8711. ToastUtil.showToast('当前播放模式:' + mode)
  8712. Logger.info('onecold 当前播放模式= ' + mode)
  8713. let hmPlayMode = mode + 1
  8714. if (hmPlayMode >= 4) {
  8715. hmPlayMode = 0
  8716. }
  8717. if (hmPlayMode === 1) {
  8718. this.playType = 1
  8719. ToastUtil.showToast('单曲循环')
  8720. } else if (hmPlayMode === 0) {
  8721. this.playType = 2
  8722. ToastUtil.showToast('单曲播完')
  8723. } else if (hmPlayMode === 3) {
  8724. this.playType = 3
  8725. ToastUtil.showToast('随机播放')
  8726. } else if (hmPlayMode === 2) {
  8727. this.playType = 0
  8728. ToastUtil.showToast('连续播放')
  8729. }
  8730. PreferencesUtil.putSync('musicPlayType', this.playType)
  8731. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  8732. let playBackState: avSession.AVPlaybackState = {
  8733. loopMode: hmPlayMode,
  8734. };
  8735. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  8736. console.info(`set setLoopMode AVPlaybackState successfully`);
  8737. }).catch((err: BusinessError) => {
  8738. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  8739. });
  8740. }
  8741. }
  8742. setCurrentPlayMode() {
  8743. if (!this.avSessionController) {
  8744. return;
  8745. }
  8746. let mLoopMode = 0
  8747. switch (this.playType) {
  8748. case 0:
  8749. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  8750. break;
  8751. case 1:
  8752. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  8753. break;
  8754. case 2:
  8755. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  8756. break;
  8757. case 3:
  8758. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  8759. break;
  8760. }
  8761. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  8762. let playBState: avSession.AVPlaybackState = {
  8763. loopMode: mLoopMode,
  8764. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  8765. };
  8766. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  8767. console.info(`set setLoopMode AVPlaybackState successfully`);
  8768. }).catch((err: BusinessError) => {
  8769. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  8770. });
  8771. }
  8772. private sessionToggleFavoriteCallback = (assetId: string) => {
  8773. if (this.mIjkMediaPlayer != null && this.currentSong) {
  8774. console.info(`on toggleFavorite `);
  8775. // 应用收到收藏命令,进行收藏处理。
  8776. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  8777. this.doFav(this.currentSong)
  8778. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  8779. let playbackState: avSession.AVPlaybackState = {
  8780. isFavorite: !this.isFac,
  8781. };
  8782. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  8783. console.info(`SetAVPlaybackState successfully`);
  8784. }).catch((err: BusinessError) => {
  8785. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  8786. });
  8787. }
  8788. }
  8789. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  8790. device: avSession.OutputDeviceInfo) => {
  8791. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  8792. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  8793. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  8794. await this.startCasting();
  8795. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  8796. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  8797. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  8798. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  8799. if (device) {
  8800. this.endCasting();
  8801. }
  8802. }
  8803. };
  8804. private async startCasting() {
  8805. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  8806. this.setPlaybackStateChangeListener();
  8807. this.pause();
  8808. this.initQueueItem();
  8809. this.prepare();
  8810. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  8811. refToIsCasting?.set(true);
  8812. this.castSeek = true;
  8813. this.isCastPlaying = true;
  8814. }
  8815. async changeCasting() {
  8816. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  8817. this.initQueueItem();
  8818. this.prepare();
  8819. this.setPlaybackStateChangeListener();
  8820. this.isCastPlaying = true;
  8821. this.castSeek = true;
  8822. }
  8823. public endCasting() {
  8824. this.avSessionController.getAvSession()?.stopCasting();
  8825. this.stopCast();
  8826. this.isCastPlaying = false;
  8827. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  8828. refToIsCasting?.set(false);
  8829. this.pause();
  8830. this.setIsPlaying(false);
  8831. // if (this.curIndex === this.curSource.index) {
  8832. // this.play
  8833. // this.seek(this.currentTime * 1000);
  8834. // this.setIsPlaying(true);
  8835. // } else {
  8836. // this.pauseVideo();
  8837. // this.setIsPlaying(false);
  8838. // }
  8839. }
  8840. public setIsPlaying(isPlayer: boolean) {
  8841. this.isPlaying = isPlayer;
  8842. }
  8843. private setPlaybackStateChangeListener(): void {
  8844. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  8845. this.castController?.on('endOfStream', this.reloadCasting);
  8846. this.castController?.on('playNext', this.playNextCallback);
  8847. this.castController?.on('playPrevious', this.playPreviousCallback);
  8848. }
  8849. private updateSessionPlayState(isPlay: boolean): void {
  8850. // if(!this.isBgPlayOpen)
  8851. // return
  8852. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  8853. this.setAVSessionPlayState({
  8854. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  8855. position: {
  8856. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  8857. updateTime: new Date().getTime()
  8858. }
  8859. });
  8860. }
  8861. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  8862. this.avSessionController.setAvSessionPlayState(playbackState)
  8863. }
  8864. private positionChange(position: number) {
  8865. this.currentTime2 = position / 1000;
  8866. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  8867. }
  8868. private playDurationChange(duration: number) {
  8869. this.duration = duration;
  8870. this.durationTime = Math.floor(this.duration / 1000);
  8871. this.durationStringTime = secondToTime((this.durationTime));
  8872. }
  8873. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  8874. const duration = playbackState?.extras?.duration;
  8875. if (typeof duration === 'number') {
  8876. this.playDurationChange(duration as number);
  8877. }
  8878. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  8879. this.positionChange(playbackState?.position?.elapsedTime);
  8880. }
  8881. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  8882. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  8883. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  8884. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  8885. this.isCastPlaying = false;
  8886. }
  8887. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  8888. this.isCastPlaying = true;
  8889. }
  8890. };
  8891. private reloadCasting = async () => {
  8892. let item = this.songList[this.curIndex];
  8893. let uri = fileUri.getUriFromPath(item.filePath);
  8894. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  8895. // description.startPosition = 0;
  8896. this.castItem = {
  8897. itemId: this.curIndex,
  8898. description: {
  8899. assetId: item.filePath,
  8900. title: item.name,
  8901. artist: '',
  8902. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  8903. // mediaUri: item.filePath,
  8904. fdSrc: {
  8905. fd: file.fd
  8906. },
  8907. // 该字段大写,音频'AUDIO',视频'VIDEO'
  8908. mediaType: 'VIDEO',
  8909. mediaSize: item.videoSize,
  8910. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  8911. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  8912. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  8913. duration: this.duration,
  8914. // albumCoverUri: 'https://www.example.jpeg',
  8915. // albumTitle: '《ExampleAlbum》',
  8916. appName: this.appName,
  8917. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  8918. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  8919. }
  8920. };
  8921. this.prepare();
  8922. this.isCastPlaying = true;
  8923. };
  8924. public playNextCallback = (): void => {
  8925. this.playNext()
  8926. };
  8927. public playPreviousCallback = (): void => {
  8928. this.playPrevious()
  8929. };
  8930. async prepare() {
  8931. await this.castController?.prepare(this.castItem);
  8932. await this.castController?.start(this.castItem);
  8933. }
  8934. public initQueueItem() {
  8935. let item = this.songList[this.curIndex];
  8936. let time = this.currentTime;
  8937. let uri = fileUri.getUriFromPath(item.filePath);
  8938. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  8939. this.castItem = {
  8940. itemId: this.curIndex,
  8941. description: {
  8942. assetId: item.filePath,
  8943. title: item.name,
  8944. artist: '',
  8945. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  8946. fdSrc: {
  8947. fd: file.fd
  8948. },
  8949. // 该字段大写,音频'AUDIO',视频'VIDEO'
  8950. mediaType: 'AUDIO',
  8951. mediaSize: item.videoSize,
  8952. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  8953. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  8954. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  8955. duration: this.duration,
  8956. // albumCoverUri: 'https://www.example.jpeg',
  8957. // albumTitle: '《ExampleAlbum》',
  8958. appName: this.appName,
  8959. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  8960. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  8961. }
  8962. };
  8963. }
  8964. async stopCast() {
  8965. try {
  8966. this.castController?.off('playbackStateChange');
  8967. this.castController?.off('endOfStream');
  8968. this.castController?.off('playNext');
  8969. this.castController?.off('playPrevious');
  8970. this.castController?.off('error');
  8971. } catch (error) {
  8972. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  8973. }
  8974. }
  8975. private sessionPlayCallback = (): void => {
  8976. this.playOrPause()
  8977. };
  8978. private sessionPauseCallback = (): void => {
  8979. this.playOrPause()
  8980. };
  8981. private playOrPause() {
  8982. if (!this.debounce()) {
  8983. return;
  8984. }
  8985. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8986. this.pause();
  8987. } else {
  8988. this.startPlayOrResumePlay();
  8989. this.playChange()
  8990. }
  8991. }
  8992. private sessionPlayNextCallback = (): void => {
  8993. this.playNext()
  8994. };
  8995. private sessionPlayPreviousCallback = (): void => {
  8996. this.playPrevious()
  8997. };
  8998. private sessionStopCallback = (): void => {
  8999. this.stop()
  9000. };
  9001. private sessionFastForwardCallback = (time?: number) => {
  9002. if (!time) {
  9003. return;
  9004. }
  9005. if (this.mIjkMediaPlayer != null) {
  9006. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  9007. let seeTime = curPosition + time * 1000;
  9008. // 限制 seekValue 在合法范围内
  9009. if (seeTime < 0) {
  9010. seeTime = 0;
  9011. } else if (seeTime > this.duration) {
  9012. seeTime = this.duration;
  9013. }
  9014. Logger.info('onecold seeTime= ' + seeTime)
  9015. this.setSeekToActionProgress(seeTime)
  9016. this.seekTo(seeTime + "")
  9017. }
  9018. };
  9019. /**
  9020. * Gesture method onActionUpdate.
  9021. *
  9022. * @param event Gesture event.手势拖动设置快进和后退
  9023. */
  9024. private setSeekToActionProgress(position: number) {
  9025. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  9026. let duration = this.mIjkMediaPlayer.getDuration();
  9027. let pos = 0;
  9028. if (duration > 0) {
  9029. this.slideEnable = true;
  9030. let curPercent = position / duration;
  9031. pos = curPercent * 100;
  9032. if (pos > this.PROGRESS_MAX_VALUE) {
  9033. this.progressValue = this.PROGRESS_MAX_VALUE
  9034. } else {
  9035. this.progressValue = pos;
  9036. }
  9037. }
  9038. // LogUtils.getInstance()
  9039. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  9040. this.totalTime = this.stringForTime(duration);
  9041. if (position > duration) {
  9042. position = duration;
  9043. }
  9044. this.isCurrentTime = true;
  9045. this.currentTime = this.stringForTime(position);
  9046. this.isCurrentTime = false
  9047. }
  9048. private sessionRewindCallback = (time?: number) => {
  9049. if (!time) {
  9050. return;
  9051. }
  9052. if (this.mIjkMediaPlayer != null) {
  9053. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  9054. let seeTime = curPosition - time * 1000;
  9055. // 限制 seekValue 在合法范围内
  9056. if (seeTime < 0) {
  9057. seeTime = 0;
  9058. } else if (seeTime > this.duration) {
  9059. seeTime = this.duration;
  9060. }
  9061. Logger.info('onecold seeTime= ' + seeTime)
  9062. this.setSeekToActionProgress(seeTime)
  9063. this.seekTo(seeTime + "")
  9064. }
  9065. };
  9066. private sessionSeekCallback = (seekTime: number) => {
  9067. if (this.mIjkMediaPlayer != null) {
  9068. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  9069. this.seekTo(seekTime + "")
  9070. }
  9071. };
  9072. private async getFileSize(filePath: string): Promise<number> {
  9073. try {
  9074. const stat = await fs.stat(filePath);
  9075. return stat.size;
  9076. } catch (err) {
  9077. console.error('Failed to get file size: ' + err.message);
  9078. return 0;
  9079. }
  9080. }
  9081. private pause() {
  9082. if (this.mIjkMediaPlayer.isPlaying()) {
  9083. this.savePlaybackPosition();
  9084. this.mIjkMediaPlayer.pause();
  9085. this.setProgress();
  9086. this.mDestroyPage = true;
  9087. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  9088. this.updateSessionPlayState(false)
  9089. this.playChange()
  9090. if (this.pipController) {
  9091. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  9092. PiPWindow.PiPControlStatus.PAUSE);
  9093. }
  9094. }
  9095. }
  9096. private stop() {
  9097. this.savePlaybackPosition();
  9098. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9099. this.mIjkMediaPlayer.stop();
  9100. this.mIjkMediaPlayer.release();
  9101. this.stopProgressTask();
  9102. this.updateSessionPlayState(false)
  9103. this.playChange()
  9104. this.watchStatus();
  9105. }
  9106. //保持记忆播放功能
  9107. private savePlaybackPosition() {
  9108. if (this.mIjkMediaPlayer != null) {
  9109. const position = this.mIjkMediaPlayer.getCurrentPosition();
  9110. // ToastUtil.showToast('保存记忆播放 = ' + position)
  9111. const duration = this.mIjkMediaPlayer.getDuration();
  9112. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  9113. // 如果播放位置接近视频末尾,则保存 position 为 0
  9114. const playbackPosition = (duration - position < threshold) ? 0 : position;
  9115. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  9116. }
  9117. }
  9118. //获取记忆播放功能
  9119. private restorePlaybackPosition() {
  9120. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  9121. // ToastUtil.showToast('position = ' + position)
  9122. if (this.mIjkMediaPlayer != null && position > 0) {
  9123. // ToastUtil.showToast('seekTo = ' + position)
  9124. this.seekTo(position + "");
  9125. }
  9126. }
  9127. private seekTo(value: string) {
  9128. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  9129. ToastUtil.showToast('wma格式不支持拖动快进。')
  9130. return
  9131. }
  9132. this.mIjkMediaPlayer.seekTo(value);
  9133. // this.startPlayOrResumePlay()
  9134. // 在这里恢复计时器状态
  9135. this.setProgress()
  9136. // this.startProgressTask();
  9137. }
  9138. // 添加到下一首播放
  9139. private addToNextPlay(song: VideoItem) {
  9140. if (!this.debounce()) {
  9141. return;
  9142. }
  9143. if (this.currentSong) {
  9144. if (this.currentSong === song) {
  9145. ToastUtil.showToast('当前已经在播放这首歌了!')
  9146. return
  9147. }
  9148. }
  9149. // 如果未开始播放或队列为空
  9150. if (this.curIndex === -1 || this.songList.length === 0) {
  9151. this.songList = [song];
  9152. this.curIndex = 0;
  9153. this.doPlay(song)
  9154. return;
  9155. }
  9156. // 插入到当前索引+1的位置
  9157. const insertPos = this.curIndex + 1;
  9158. this.songList.splice(insertPos, 0, song);
  9159. this.songList = [...this.songList]; // 触发状态更新
  9160. this.sonDataSource.pushArrayData(this.songList)
  9161. ToastUtil.showToast('已添加至下一首播放')
  9162. }
  9163. //下一个
  9164. private playNext() {
  9165. if (!this.debounce()) {
  9166. return;
  9167. }
  9168. if (this.playType == 3) { //3:随机播放
  9169. this.randomPlay()
  9170. return;
  9171. }
  9172. if (ArrayUtil.isNotEmpty(this.songList)) {
  9173. if (this.curIndex == this.songList.length - 1) {
  9174. this.curIndex = 0;
  9175. } else {
  9176. this.curIndex++;
  9177. }
  9178. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9179. this.stop();
  9180. this.currentSong = this.songList[this.curIndex]
  9181. this.videoUrl = this.songList[this.curIndex].filePath;
  9182. this.cover = this.songList[this.curIndex].pixelMapPath
  9183. this.artist = this.songList[this.curIndex].artist
  9184. this.name = this.songList[this.curIndex].name
  9185. this.startPlayOrResumePlay()
  9186. }
  9187. }
  9188. // 存储已播放的歌曲索引
  9189. private playedIndices: Set<number> = new Set();
  9190. //随机播放
  9191. private randomPlay() {
  9192. // if (!this.debounce()) {
  9193. // return;
  9194. // }
  9195. if (ArrayUtil.isNotEmpty(this.songList)) {
  9196. if (this.songList.length > 3) {
  9197. // 如果所有歌曲都播放过一次,清空已播放索引集合
  9198. if (this.playedIndices.size === this.songList.length) {
  9199. this.playedIndices.clear();
  9200. }
  9201. // 随机选择一个未播放的歌曲索引
  9202. let newIndex: number;
  9203. // 添加超时机制防止无限循环
  9204. let attempt = 0;
  9205. const maxAttempts = 100; // 根据需求调整
  9206. do {
  9207. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  9208. attempt++;
  9209. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  9210. if (attempt >= maxAttempts) {
  9211. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  9212. newIndex = Math.floor(Math.random() * this.songList.length);
  9213. }
  9214. this.curIndex = newIndex;
  9215. this.playedIndices.add(newIndex);
  9216. } else {
  9217. // 当歌曲数量小于或等于3时,直接播放下一首
  9218. if (this.curIndex == this.songList.length - 1) {
  9219. this.curIndex = 0;
  9220. } else {
  9221. this.curIndex++;
  9222. }
  9223. }
  9224. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9225. this.stop();
  9226. this.currentSong = this.songList[this.curIndex];
  9227. this.videoUrl = this.songList[this.curIndex].filePath;
  9228. this.name = this.songList[this.curIndex].name;
  9229. this.cover = this.songList[this.curIndex].pixelMapPath
  9230. this.artist = this.songList[this.curIndex].artist
  9231. this.startPlayOrResumePlay();
  9232. }
  9233. }
  9234. private playIndex(index: number) {
  9235. if (!this.debounce()) {
  9236. return;
  9237. }
  9238. if (ArrayUtil.isNotEmpty(this.songList)) {
  9239. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9240. this.stop();
  9241. this.currentSong = this.songList[this.curIndex]
  9242. this.videoUrl = this.songList[index].filePath;
  9243. this.name = this.songList[index].name
  9244. this.cover = this.songList[this.curIndex].pixelMapPath
  9245. this.artist = this.songList[this.curIndex].artist
  9246. this.curIndex = index;
  9247. this.startPlayOrResumePlay()
  9248. }
  9249. }
  9250. //上一个
  9251. private playPrevious() {
  9252. if (!this.debounce()) {
  9253. return;
  9254. }
  9255. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  9256. this.randomModePlayFromHistory()
  9257. return;
  9258. }
  9259. if (this.curIndex == 0) {
  9260. this.curIndex = this.songList.length - 1;
  9261. } else {
  9262. this.curIndex--;
  9263. }
  9264. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9265. this.stop();
  9266. this.currentSong = this.songList[this.curIndex]
  9267. this.videoUrl = this.songList[this.curIndex].filePath;
  9268. this.name = this.songList[this.curIndex].name
  9269. this.cover = this.songList[this.curIndex].pixelMapPath
  9270. this.artist = this.songList[this.curIndex].artist
  9271. this.startPlayOrResumePlay()
  9272. }
  9273. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  9274. private randomModePlayFromHistory() {
  9275. if (this.historyList.length >= 2) {
  9276. // 播放历史记录的第二首
  9277. const prevSong = this.historyList[1];
  9278. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  9279. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9280. this.stop();
  9281. this.currentSong = prevSong;
  9282. this.videoUrl = prevSong.filePath;
  9283. this.cover = prevSong.pixelMapPath
  9284. this.artist = prevSong.artist
  9285. this.name = prevSong.name;
  9286. this.startPlayOrResumePlay();
  9287. } else {
  9288. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  9289. if (this.curIndex === 0) {
  9290. this.curIndex = this.songList.length - 1;
  9291. } else {
  9292. this.curIndex--;
  9293. }
  9294. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9295. this.stop();
  9296. this.currentSong = this.songList[this.curIndex];
  9297. this.videoUrl = this.songList[this.curIndex].filePath;
  9298. this.cover = this.songList[this.curIndex].pixelMapPath
  9299. this.artist = this.songList[this.curIndex].artist
  9300. this.name = this.songList[this.curIndex].name;
  9301. this.startPlayOrResumePlay();
  9302. }
  9303. }
  9304. debounce() {
  9305. const delay = 600;
  9306. let cur = new Date().getTime();
  9307. if (cur - this.last > delay) {
  9308. this.last = cur;
  9309. return true;
  9310. }
  9311. return false;
  9312. }
  9313. /**
  9314. * Sets whether the screen is a constant based on the playback status.
  9315. */
  9316. watchStatus() {
  9317. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  9318. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  9319. this.windowClass.setWindowKeepScreenOn(true);
  9320. } else {
  9321. this.windowClass.setWindowKeepScreenOn(false);
  9322. }
  9323. }
  9324. /**
  9325. * Volume gesture method onActionStart.
  9326. *
  9327. * @param event Gesture event.
  9328. */
  9329. private customDialogComponentIdMM: number = 0
  9330. @Builder
  9331. customDialogComponentMM() {
  9332. Column() {
  9333. Row() {
  9334. Blank()
  9335. Text('验证密码')
  9336. .fontSize(22)
  9337. .fontColor($r('app.color.pri_bg'))
  9338. .margin({ top: 18 })
  9339. Blank()
  9340. Image($r('app.media.close'))
  9341. .fillColor(Color.White)
  9342. .margin({ top: 18, right: 18 })
  9343. .width(20)
  9344. .onClick(() => {
  9345. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  9346. })
  9347. }
  9348. .width('100%') // 使Row占据整个宽度
  9349. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  9350. Verify({
  9351. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  9352. });
  9353. }.height('60%')
  9354. .backgroundColor($r('app.color.index_background'))
  9355. .justifyContent(FlexAlign.SpaceBetween)
  9356. }
  9357. private handleVerifyCompleted(isSuccess: boolean) {
  9358. if (isSuccess) {
  9359. console.log('验证成功');
  9360. // 在这里处理验证成功后的逻辑
  9361. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  9362. this.currentPath = this.lockPath
  9363. this.getSortedFiles(this.currentPath)
  9364. } else {
  9365. // console.log('验证失败');
  9366. ToastUtil.showToast('验证失败')
  9367. }
  9368. }
  9369. private showVerifyDialog() {
  9370. promptAction.openCustomDialog({
  9371. transition: TransitionEffect.asymmetric(
  9372. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  9373. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  9374. ,
  9375. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  9376. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  9377. ),
  9378. builder: () => {
  9379. this.customDialogComponentMM()
  9380. },
  9381. isModal: true,
  9382. autoCancel: true,
  9383. maskColor: Color.Transparent,
  9384. alignment: DialogAlignment.Bottom,
  9385. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  9386. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  9387. console.log("dialog onWillDismiss")
  9388. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  9389. dismissDialogAction.dismiss()
  9390. }
  9391. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  9392. dismissDialogAction.dismiss()
  9393. }
  9394. }
  9395. }).then((dialogId: number) => {
  9396. this.customDialogComponentIdMM = dialogId
  9397. })
  9398. }
  9399. //左滑操作 移动文件 重命名 删除等操作
  9400. @Builder
  9401. DeleteButton(item: VideoItem, index: number, filePath: string) {
  9402. Row() {
  9403. //加入收藏
  9404. Button() {
  9405. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  9406. .fillColor(Color.White)
  9407. .width(20)
  9408. }
  9409. .width(40)
  9410. .height(40)
  9411. .type(ButtonType.Circle)
  9412. .backgroundColor(this.themeColor)
  9413. .margin(5)
  9414. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  9415. .onClick(() => {
  9416. if (item) {
  9417. this.doFav(item)
  9418. }
  9419. })
  9420. //加入下一首播放
  9421. Button() {
  9422. Image($r('app.media.next_to_play'))
  9423. .fillColor(Color.White)
  9424. .width(20)
  9425. }
  9426. .width(40)
  9427. .height(40)
  9428. .type(ButtonType.Circle)
  9429. .backgroundColor(this.themeColor)
  9430. .margin(5)
  9431. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  9432. .onClick(() => {
  9433. this.addToNextPlay(item);
  9434. })
  9435. //复制文件
  9436. Button() {
  9437. Image($r('app.media.copy'))
  9438. .fillColor(Color.White)
  9439. .width(20)
  9440. }
  9441. .width(40)
  9442. .height(40)
  9443. .type(ButtonType.Circle)
  9444. .backgroundColor(this.themeColor)
  9445. .margin(5)
  9446. .id(filePath + 'copy')
  9447. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  9448. .onClick(() => {
  9449. this.showCopyDialog(false, item, index, filePath + 'copy');
  9450. })
  9451. //移动文件
  9452. Button() {
  9453. Image($r('app.media.cut'))
  9454. .fillColor(Color.White)
  9455. .width(20)
  9456. }
  9457. .width(40)
  9458. .height(40)
  9459. .type(ButtonType.Circle)
  9460. .backgroundColor(this.themeColor)
  9461. .margin(5)
  9462. .id(filePath)
  9463. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  9464. .onClick(() => {
  9465. this.showCutDialog(false, item, index, filePath);
  9466. })
  9467. Button() {
  9468. Image($r('app.media.cut_current'))
  9469. .fillColor(Color.White)
  9470. .width(20)
  9471. }
  9472. .width(40)
  9473. .height(40)
  9474. .type(ButtonType.Circle)
  9475. .backgroundColor(this.themeColor)
  9476. .margin(5)
  9477. .id(filePath + 'current')
  9478. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  9479. (this.isHasDir ? Visibility.Visible : Visibility.None))
  9480. .onClick(() => {
  9481. this.showCutDialog(true, item, index, filePath + 'current');
  9482. })
  9483. //重命名
  9484. Button() {
  9485. Image($r('app.media.rename2'))
  9486. .fillColor(Color.White)
  9487. .width(20)
  9488. }
  9489. .width(40)
  9490. .height(40)
  9491. .type(ButtonType.Circle)
  9492. .backgroundColor(this.themeColor)
  9493. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  9494. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  9495. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  9496. .margin(5)
  9497. .onClick(() => {
  9498. this.showReNameDialog(item, index + '', filePath)
  9499. })
  9500. Button() {
  9501. Image($r('app.media.delete2'))
  9502. .fillColor(Color.White)
  9503. .width(20)
  9504. }
  9505. .width(40)
  9506. .height(40)
  9507. .type(ButtonType.Circle)
  9508. .backgroundColor(this.themeColor)
  9509. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  9510. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  9511. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  9512. .margin(5)
  9513. .onClick(() => {
  9514. this.showWarnIsDeleteFile(item, index + '', filePath)
  9515. })
  9516. Button() {
  9517. Image($r('app.media.share2'))
  9518. .fillColor(Color.White)
  9519. .width(20)
  9520. }
  9521. .width(40)
  9522. .height(40)
  9523. .type(ButtonType.Circle)
  9524. .backgroundColor(this.themeColor)
  9525. .margin(5)
  9526. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  9527. .onClick(() => {
  9528. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  9529. })
  9530. }
  9531. }
  9532. /**
  9533. * 穿山甲banner广告
  9534. */
  9535. // private declare bannerAd: CSJNativeExpressAd;
  9536. // @State private status: string = "未加载"
  9537. // @State private isShowAd: boolean = false
  9538. // private declare mAdSlot: AdSlot;
  9539. // private mBiddingAdm = '' //服务端bidding才需要设置
  9540. // private expressLoadAdListener: NativeExpressAdListener = {
  9541. // /**
  9542. // * 加载失败的回调
  9543. // *
  9544. // * @param code
  9545. // * @param message
  9546. // */
  9547. // onError: (code: number, message: string) => {
  9548. // console.error("加载广告失败,code=" + code + ",message=" + message);
  9549. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  9550. // },
  9551. //
  9552. // /**
  9553. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  9554. // *
  9555. // * @param ads 返回的广告列表
  9556. // */
  9557. //
  9558. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  9559. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  9560. // if (ads && ads.length > 0) {
  9561. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  9562. // ad.setExpressInteractionListener({
  9563. // /**
  9564. // *广告的点击回调
  9565. // * @param type 广告的交互类型
  9566. // */
  9567. // onAdClicked: (type: number) => {
  9568. // console.log("BannerExpressAdPage==onAdClicked......");
  9569. // },
  9570. //
  9571. // /**
  9572. // * 广告的展示回调 每个广告仅回调一次
  9573. // * @param type 广告的交互类型
  9574. // */
  9575. // onAdShow: (type: number) => {
  9576. // console.log("BannerExpressAdPage==onAdShow......");
  9577. // },
  9578. //
  9579. // /**
  9580. // * 模板渲染失败
  9581. // */
  9582. // onRenderFail: (code: number, msg: string) => {
  9583. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  9584. // },
  9585. //
  9586. // /**
  9587. // * 模板渲染成功
  9588. // * @param width 返回view的宽 单位 vp
  9589. // * @param height 返回view的高 单位 vp
  9590. // */
  9591. // onRenderSuccess: (width: number, height: number) => {
  9592. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  9593. // this.bannerAd = ad;
  9594. // this.status = "广告加载完成待展示";
  9595. //
  9596. // this.showBannerAd()
  9597. // }
  9598. // })
  9599. // //渲染广告
  9600. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  9601. // this.setDislikeCallback(ad); //设置dislike
  9602. // ad.render(this.getUIContext())
  9603. // this.status = "广告加载中...";
  9604. // });
  9605. // }
  9606. // }
  9607. // }
  9608. //
  9609. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  9610. // ad.setDislikeCallback({
  9611. // /**
  9612. // * dislike show
  9613. // */
  9614. // onShow: () => {
  9615. // console.log("BannerExpressAdPage==dislike......show");
  9616. // },
  9617. //
  9618. // /**
  9619. // * @param position 选择的位置
  9620. // * @param value 选择的内容
  9621. // * @param enforceRemove 是否强制关闭广告
  9622. // */
  9623. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  9624. // this.isShowAd = false;
  9625. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  9626. // ",enforce=" + enforceRemove);
  9627. // },
  9628. //
  9629. // /**
  9630. // * 点击取消
  9631. // */
  9632. // onCancel: () => {
  9633. // console.log("BannerExpressAdPage==dislike......onCancel");
  9634. // }
  9635. //
  9636. // })
  9637. // }
  9638. /**
  9639. * 加载Banner广告
  9640. */
  9641. loadBannerAd(rit: string) {
  9642. // if (Utility.isNoble()) {
  9643. // return
  9644. // }
  9645. // if (!Utility.isPassInstallTime(2)) {
  9646. // return
  9647. // }
  9648. // this.isShowAd = false;
  9649. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  9650. // this.mAdSlot = new AdSlotBuilder()
  9651. // .setCodeId(rit)
  9652. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  9653. // .setAdCount(1)
  9654. // .setBidAdm(this.mBiddingAdm)
  9655. // .build()
  9656. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  9657. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  9658. // this.status = "广告加载中..."
  9659. }
  9660. /**
  9661. * 展示Banner广告
  9662. */
  9663. // showBannerAd() {
  9664. // if (!this.bannerAd) {
  9665. // return
  9666. // }
  9667. // this.isShowAd = true
  9668. // this.status = "已展示"
  9669. // }
  9670. /**
  9671. * 穿山甲广告代码结束
  9672. */
  9673. }
  9674. //视频气泡窗口的布局
  9675. @Builder
  9676. function customPopupBuilder(dataBu: BubbleBean) {
  9677. List() {
  9678. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  9679. ListItem() {
  9680. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9681. Row() {
  9682. Column() {
  9683. Image(dataBu.imageRes[index])
  9684. .height(28)
  9685. .fillColor(dataBu.color)
  9686. .alignSelf(ItemAlign.Center)
  9687. }
  9688. .width(32)
  9689. Text(item)
  9690. .padding({
  9691. top: 10,
  9692. bottom: 10,
  9693. right: 10,
  9694. left: 10
  9695. })
  9696. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  9697. .textAlign(TextAlign.Start)
  9698. .width("100%")
  9699. }
  9700. }
  9701. .backgroundColor($r('app.color.settings_background_main'))
  9702. .margin({ top: 6, bottom: 6 })
  9703. }
  9704. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  9705. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  9706. TransitionEffect.scale({ x: 0, y: 0 })))
  9707. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  9708. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  9709. .onClick(() => {
  9710. dataBu.onItemClick?.(index)
  9711. })
  9712. })
  9713. }
  9714. .width(120)
  9715. .divider({
  9716. strokeWidth: 1,
  9717. color: "#22FFFFFF"
  9718. })
  9719. }
  9720. // Function to calculate a hash for the file list
  9721. function simpleHash(fileList: string[]): string {
  9722. let hash = 0;
  9723. const str = fileList.join(',');
  9724. for (let i = 0; i < str.length; i++) {
  9725. const char = str.charCodeAt(i);
  9726. hash = (hash << 5) - hash + char;
  9727. hash |= 0; // Convert to 32bit integer
  9728. }
  9729. return hash.toString();
  9730. }
  9731. interface MoreItem {
  9732. id: number;
  9733. image: Resource;
  9734. title: string;
  9735. }
  9736. //视频气泡窗口的布局
  9737. @Builder
  9738. function cutPopupBuilder(dataBu: BubbleBean) {
  9739. Column() {
  9740. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  9741. .padding({
  9742. top: 10,
  9743. bottom: 10,
  9744. right: 10,
  9745. left: 10
  9746. })
  9747. .textAlign(TextAlign.Start)
  9748. .width(160)
  9749. .fontWeight(666)
  9750. .fontSize(16)
  9751. List() {
  9752. ForEach(dataBu.data, (item: string, index: number) => {
  9753. ListItem() {
  9754. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9755. Row() {
  9756. Column() {
  9757. Image($r('app.media.music_group'))
  9758. .height(28)
  9759. .fillColor(dataBu.color)
  9760. .alignSelf(ItemAlign.Center)
  9761. }
  9762. .width(32)
  9763. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  9764. .padding({
  9765. top: 10,
  9766. bottom: 10,
  9767. right: 10,
  9768. left: 10
  9769. })
  9770. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  9771. .fontSize(15)
  9772. }
  9773. }
  9774. .backgroundColor(Color.Transparent)
  9775. .margin({ top: 7, bottom: 7 })
  9776. }
  9777. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  9778. .animation({ duration: 500 }),
  9779. TransitionEffect.scale({ x: 0, y: 0 })))
  9780. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  9781. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  9782. .onClick(() => {
  9783. dataBu.onItemClick?.(index)
  9784. })
  9785. })
  9786. }
  9787. .width(150)
  9788. .divider({
  9789. strokeWidth: 1,
  9790. color: "#22FFFFFF"
  9791. })
  9792. }
  9793. .height(300)
  9794. .padding({
  9795. bottom: 30
  9796. })
  9797. }