LocalMusic.ets 258 KB

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