LocalMusic.ets 308 KB

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