| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024 |
- import TitleBar from './TitleBar'
- import { Animator, curves, display, PromptAction, promptAction, router, window } from '@kit.ArkUI';
- import { VideoItem } from '../viewmodel/VideoItem';
- import {
- AppUtil,
- ArrayUtil,
- Base64Util,
- DateUtil,
- DeviceUtil,
- DisplayUtil,
- FileUtil,
- ImageUtil,
- LogUtil,
- MD5,
- PickerUtil,
- PreferencesUtil,
- RandomUtil,
- StrUtil,
- ToastUtil
- } from '@pura/harmony-utils';
- import { CommonConstants } from '../common/constants/CommonConstants';
- import Logger from '../common/util/Logger';
- import { photoAccessHelper } from '@kit.MediaLibraryKit';
- import { Utility } from '../common/util/Utility';
- import { BusinessError, emitter } from '@kit.BasicServicesKit';
- import { dataSharePredicates, uniformTypeDescriptor } from '@kit.ArkData';
- import { BubbleBean } from '../viewmodel/BubbleBean';
- import { PopupPosition, XPopup } from '@chinalike/popup';
- import { common, ConfigurationConstant } from '@kit.AbilityKit';
- import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
- import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
- import { CSJUtil } from '../common/util/CSJUtil';
- import {
- AdSlot,
- AdSlotBuilder,
- CSJAdCreator,
- CSJAdSdk,
- CSJNativeExpressAd,
- NativeExpressAdListener
- } from '@csj/openadsdk';
- import { PrintBiddingTokenUtils } from '../common/util/PrintBiddintTokenUtils';
- import { ArrayList, MessageEvents, util, worker } from '@kit.ArkTS';
- import { Verify } from './Verify';
- import { DrawerOptions } from '../dialog/DrawerOptions';
- import { RotatingCover } from './RotatingCover';
- import { PlayConstants } from '../common/constants/PlayConstants';
- import { displaySync, effectKit } from '@kit.ArkGraphics2D';
- import { ColorConversion } from '../common/util/ColorConversion';
- import { LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
- import { AvSessionController } from '../controller/AvSessionController';
- import {
- IjkMediaPlayer,
- InterruptEvent,
- InterruptHintType,
- LogUtils,
- OnBufferingUpdateListener,
- OnCompletionListener,
- OnErrorListener,
- OnInfoListener,
- OnPreparedListener,
- OnSeekCompleteListener,
- OnTimedTextListener,
- OnVideoSizeChangedListener
- } from '@ohos/ijkplayer';
- import { PlayStatus } from '../common/PlayStatus';
- import fs from '@ohos.file.fs';
- import { image } from '@kit.ImageKit';
- import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
- import * as chardet from '@changwei/chardet';
- import { SettingPage } from '../pages/SettingPage';
- import { secondToTime } from '../common/util/CommUtils';
- import { CommonConstants2 } from '../common/util/CommonConstants2';
- import { hilog } from '@kit.PerformanceAnalysisKit';
- import { LazyDataSource } from '../common/util/LazyDataSource';
- import MediaTable from '../common/util/MediaTable';
- import { ImageKnifeComponent } from '@ohos/imageknife';
- import NetAxiosUtil from '../common/util/NetAxiosUtil';
- import ImageUtils from '../common/util/ImageUtils';
- import { ringtone } from '@kit.RingtoneKit';
- import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
- import { resourceManager } from '@kit.LocalizationKit';
- import File from '@system.file';
- import { deviceInfo } from '@kit.BasicServicesKit';
- import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
- import { DEBUG } from 'BuildProfile';
- import { LrcParser } from '@sgaolei/lrc_parser';
- const TAG = 'LocalMusic';
- //排序类型
- function getTypeOrder(type: number) {
- switch (type) {
- case CommonConstants.TYPE_IS_DIR:
- return 1; // First
- case CommonConstants.TYPE_IS_CSJAD:
- return 2; // Middle
- case CommonConstants.TYPE_LOCAL:
- return 3; // Last
- default:
- return 4; // Unknown types, if any, go last
- }
- }
- const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
- interface GeneratedObjectLiteralInterface_1 {
- assetId: string;
- title: string;
- artist: string;
- // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
- mediaUri: string;
- // 该字段大写,音频'AUDIO',视频'VIDEO'
- mediaType: string;
- mediaSize: number;
- //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
- startPosition: number;
- // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
- duration: number;
- albumCoverUri: string;
- albumTitle: string;
- appName: string;
- // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
- drmScheme: string;
- }
- //功能强大的音乐播放器
- @Preview
- @Component
- export struct LocalMusic {
- @State titleName: string = '首页'
- @State textStr: string = ''
- // static readonly STR_MUSIC_VIDEO: string = 'Audios';
- // private download_path: string = '';
- @Consume rootPath: string //音频根目录
- @Consume currentPath: string
- static readonly STR_LOCK_VIDEO: string = '.私密音频';
- static readonly STR_FAC_VIDEO: string = '.我的收藏';
- @State lockPath: string = ''
- @State favPath: string = ''
- static readonly STR_HISTORY_MUSIC: string = '.最近播放';
- @State historyPath: string = ''
- @State historyList: Array<VideoItem> = []
- @Consume isHistory: boolean
- static readonly HISTORY_MUSIC: string = 'music_historyList';
- private table: MediaTable = new MediaTable(getContext(this))
- @State isZero: boolean = false
- @State fileList: Array<string> = []
- @State dirList: Array<VideoItem> = []
- @Consume videoLocalList: Array<VideoItem>
- @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
- @State mediaKuList: Array<VideoItem> = []; //媒体库文件
- @State artistList: Array<VideoItem> = []; //艺术家文件
- @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
- @State albumList: Array<VideoItem> = []; //专辑文件
- @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
- @State imageOpacities: number[] = [];
- @Consume isCanBack: boolean
- @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
- @State showSingleLyric: boolean = false
- @State sortType: number = 4 //默认排序方式
- @State isShowSimi:boolean = false //是否显示私密音频
- @State isShowFAV:boolean = true //是否显示我的收藏
- @State isShowHistory:boolean = true //是否显示最近播放
- @State isCustomizeBg: boolean = false //自定义背景界面
- @State customizeBgPath: string | undefined = '';
- @State isDarkMode: boolean = AppStorage.get<number>('currentColorMode')===ConfigurationConstant.ColorMode.COLOR_MODE_DARK
- @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
- ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT;
- onColorModeChange() {
- this.isDarkMode=AppStorage.get<number>('currentColorMode')===ConfigurationConstant.ColorMode.COLOR_MODE_DARK
- }
- onModeChange() {
- this.isFavMusic = false
- if (this.modeType === 2 || this.modeType === 3) {
- this.titleBarModel.setRightIcon(null)
- } else {
- this.titleBarModel.setRightIcon(($r('app.media.add')))
- }
- LogUtil.info('onecold onModeChange = ' + this.modeType)
- switch (this.modeType) {
- case 0:
- this.getSortedFiles(this.currentPath)
- break
- case 1:
- this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
- this.updateListData(this.mediaKuList)
- this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
- break
- case 2:
- this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
- this.updateListData(this.artistList)
- this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
- break
- case 3:
- this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
- this.updateListData(this.albumList)
- this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
- break
- }
- }
- @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
- // @StorageLink('isPlay') isPlay: boolean = false;
- @StorageLink('isShowPlay') isShowPlay: boolean = false;
- @StorageProp('windowHeight') windowHeight: number = 0;
- @StorageLink('songList') songList: Array<VideoItem> = [];
- @State translateY: number = 0;
- @State isShowSheet: boolean = false;
- @State isShowSheetView: boolean = false;
- @State isShowTimeCloseView: boolean = false;
- private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
- @StorageLink('currIndex') curIndex: number = 0;
- @Consume isShowDrawer: boolean;
- @Consume offsetX: number;
- @State isFac: boolean = false;
- @State facList: Array<String> = []
- @State favList: Array<VideoItem>= []
- @Consume isFavMusic:boolean
- @State isClickedPLayAll: boolean = false;
- private scrollerForlist: ListScroller = new ListScroller();
- imagesF: ImageFrameInfo[] = [
- { src: $r("app.media.app_loading0") },
- { src: $r("app.media.app_loading1") },
- { src: $r("app.media.app_loading2") },
- { src: $r("app.media.app_loading3") },
- ]
- @State animationState: AnimationStatus = AnimationStatus.Initial
- // 缓存机制
- private cache: Map<string, Array<VideoItem>> = new Map();
- private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
- // 持久化缓存
- private async saveCacheToStorage() {
- const cacheArray = Array.from(this.cache.entries());
- const stringCacheArray = Array.from(this.stringCache.entries());
- await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
- await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray)); // 保存字符串缓存
- }
- // 载入缓存
- private async loadCacheFromStorage() {
- const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
- const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
- if (cacheString) {
- const cacheArray: [string, Array<VideoItem>][] = JSON.parse(cacheString);
- this.cache = new Map(cacheArray);
- }
- if (stringCacheString) {
- const stringCacheArray: [string, string][] = JSON.parse(stringCacheString);
- this.stringCache = new Map(stringCacheArray);
- }
- }
- // 查找缓存
- private findCache(key: string): Array<VideoItem> | undefined {
- return this.cache.get(key);
- }
- // 查找字符串缓存
- private findStringCache(key: string): string | undefined {
- return this.stringCache.get(key);
- }
- // 添加缓存
- private addCache(key: string, value: Array<VideoItem>) {
- this.cache.set(key, value);
- }
- // 添加字符串缓存
- private addStringCache(key: string, value: string) {
- this.stringCache.set(key, value);
- }
- // 删除缓存
- private deleteCache(key: string) {
- this.cache.delete(key);
- this.saveCacheToStorage()
- }
- // 删除字符串缓存
- private deleteStringCache(key: string) {
- this.stringCache.delete(key);
- }
- // 多选机制
- @State selectedFiles: Array<VideoItem> = [];
- @State isMultiSelect: boolean = false;
- @State isAllSelected: boolean = false;
- @State appName: string = ''
- @State isHasDir: boolean = false
- @State packName: string = ''
- context = getContext(this);
- @State titleBarModel: TitleBar.Model = new TitleBar.Model()
- .setTitleTextStyle(FontStyle.Normal)
- .setTitleBarStyle(TitleBar.BarStyle.TRANSPARENT)
- .setLeftIcon($r('app.media.menu'))
- .setLeftIconWidth(25)
- .setLeftIconHeight(25)
- .setTitleName('首页')
- .setTitleFontSize(18)
- .setTitleFontColor(Color.White)
- .setTitleBarBackground($r('app.color.title_bar_bg'))
- .setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
- .setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
- .setRightIcon($r('app.media.add'))
- .setOnRightClickListener(() => {
- this.showSheelDialog()
- })
- .setOnTitleClickListener(() => {
- this.showPupDialog()
- })
- .setOnLeftClickListener(() => {
- this.doSwipBack()
- })
- doSwipBack() {
- if (this.modeType !== 0 && this.isCanBack) {
- this.onModeChange()
- this.isCanBack = false
- this.titleBarModel.setLeftIconMain($r('app.media.menu'))
- return
- }
- if (this.isHistory||this.isFavMusic) {
- this.isHistory = false
- this.getSortedFiles(this.currentPath)
- return
- }
- if (this.currentPath === this.rootPath || this.modeType !== 0) {
- animateTo({ duration: 555 }, () => {
- // 动画闭包内控制Image组件的出现和消失
- this.isShowDrawer = true
- this.offsetX = 0
- })
- return
- }
- this.currentPath = Utility.getParentDirectory(this.currentPath)
- Logger.info('this.currentPath2 = ' + this.currentPath)
- this.getSortedFiles(this.currentPath)
- }
- // 组件生命周期
- aboutToAppear() {
- this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
- this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
- this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
- if(this.isCustomizeBg){
- this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
- this.titleBarModel.setTitleBarBackground(Color.Transparent)
- this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
- this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
- }else{
- this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
- this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
- // this.titleBarModel .setRightTitleBackground($r('app.color.title_bar_bg'))
- }
- Utility.getAppName(getContext(this)).then((appName: string) => {
- this.appName = appName
- })
- this.packName = AppUtil.getBundleName()
- this.loadCacheFromStorage(); // 加载缓存
- this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
- if (this.isSavePlayMode) {
- this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
- }
- this.historyList = PreferencesUtil.getSync(LocalMusic.HISTORY_MUSIC, this.historyList) as Array<VideoItem>
- this.mkDownLoadDir()
- let eventMusic: emitter.InnerEvent = { eventId: 2 }
- // 监听广播事件(打开其他应用处理)
- emitter.on(eventMusic, (eventData: emitter.EventData) => {
- this.saveVideoDatas([eventData.data?.message], true)
- });
- //侧滑广播接收时间
- let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: 888 }
- // 监听广播事件(打开其他应用处理)
- emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
- this.doSwipBack()
- });
- //ScanFilePage广播接收时间
- let eventScanUpdate: emitter.InnerEvent = { eventId: 101 }
- // 监听ScanFilePage广播事件(更新数据库)
- emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
- this.doUpdateData()
- });
- let eventSetting: emitter.InnerEvent = { eventId: 333 }
- // 监听广播事件(打开其他应用处理)
- emitter.on(eventSetting, (eventData: emitter.EventData) => {
- this.doChangeSetting()
- });
- let event: Callback<InterruptEvent> = (event) => {
- LogUtils.getInstance().LOGI(`event: ${JSON.stringify(event)}`);
- if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
- this.pause();
- } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
- this.startPlayOrResumePlay();
- } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
- this.stop();
- }
- }
- this.mIjkMediaPlayer.on('audioInterrupt', event);
- this.makeWorker()
- this.windowClass.on('windowSizeChange', (size) => {
- this.doChangeBarHeight()
- });
- //折叠屏的屏幕显示模式变化
- display.on('foldDisplayModeChange', (data) => {
- this.doChangeBarHeight()
- });
- display.on('foldStatusChange', (data) => {
- Logger.info('onecold foldStatusChange ')
- });
- this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, false)
- }
- doChangeSetting(){
- this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
- this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
- this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
- if(this.isCustomizeBg){
- this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
- this.titleBarModel.setTitleBarBackground(Color.Transparent)
- this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
- this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
- }else{
- this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
- this.titleBarModel .setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
- this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
- this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
- }
- this.doUpdateData()
- }
- doChangeBarHeight() {
- if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
- (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
- this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
- this.hideDone = false;
- this.getUIContext().animateTo({
- duration: 300
- }, () => {
- this.bottomBarHeight = 55 + 0;
- this.topBarHeight = 50 + 0;
- this.barOpacity = 1;
- this.currentYOffset = 0;
- this.isHiding = false;
- });
- }
- }
- onPageShow() {
- Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
- }
- //开启线程查看各个数据库
- makeWorker() {
- setTimeout(() => {
- if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
- //发送worker通知扫描文件入库
- workerInstance.postMessage({
- code: 1,
- data1: this.context,
- data2: this.rootPath,
- data3: this.lockPath,
- data4: PreferencesUtil.getStringSync('COVER_API', ''),
- });
- PreferencesUtil.putSync('isFirstApp', false)
- } else {
- workerInstance.postMessage({ code: 2, data: this.context });
- workerInstance.postMessage({ code: 3, data: this.context });
- workerInstance.postMessage({ code: 4, data: this.context });
- }
- }, 1000)
- workerInstance.onmessage = (e: MessageEvents): void => {
- switch (e.data.code) {
- case 101: //第一次扫描文件夹入库
- ToastUtil.showToast('刷新同步数据库成功!')
- Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
- this.doUpdateData()
- break;
- case 102: //查询媒体库列表
- this.mediaKuList = e.data.data
- Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
- Utility.doSortListAscending(this.mediaKuList)
- if (this.modeType === 1) {
- this.updateListData(this.mediaKuList)
- }
- break;
- case 103: //收到查询艺术家列表
- this.artistMap = e.data.data1;
- this.artistList = e.data.data2;
- break;
- case 104: //收到查询专辑列表
- this.albumMap = e.data.data1;
- this.albumList = e.data.data2
- break;
- }
- };
- // 在调用terminate后,执行onexit
- workerInstance.onexit = (code) => {
- console.log("main thread terminate");
- }
- }
- //获取download_path
- async mkDownLoadDir() {
- const documentViewPicker = new picker.DocumentViewPicker()
- let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
- this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
- // this.rootPath = this.download_path
- this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
- this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
- this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
- Logger.info('onecold rootPath = ' + this.rootPath)
- Logger.info('onecold lockPath = ' + this.lockPath)
- if (!FileUtil.accessSync(this.lockPath)) {
- FileUtil.mkdirSync(this.lockPath)
- }
- if (!FileUtil.accessSync(this.favPath)) {
- FileUtil.mkdirSync(this.favPath)
- }
- if (!FileUtil.accessSync(this.historyPath)) {
- FileUtil.mkdirSync(this.historyPath)
- }
- this.getSortedFiles(this.rootPath).then(() => {
- this.isFavMusic = false
- //穿山甲
- this.loadBannerAd(CSJUtil.getBannerID())
- // this.songList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
- this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
- this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
- if (ArrayUtil.isEmpty(this.songList)) {
- this.songList = this.getCurFileList()
- } else {
- this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
- }
- if (ArrayUtil.isNotEmpty(this.songList)) {
- this.sonDataSource.pushArrayData(this.songList)
- if (this.currentSong === undefined) {
- this.currentSong = this.songList[0]
- }
- this.videoUrl = this.currentSong.filePath
- this.name = this.currentSong.name
- this.cover = this.currentSong.pixelMapPath
- } else {
- this.name = '空空如也'
- }
- })
- // if (FileUtil.accessSync(this.favPath)) {
- // this.facList = FileUtil.listFileSync(this.favPath)
- // }
- this.getFavList(false)
- }
- getFavList(isFavRefresh:boolean){
- this.table.queryByisFav(1, async (result: VideoItem[]) => {
- this.favList = result
- if(isFavRefresh||this.isFavMusic){//如果是我的收藏,更新我的收藏数据
- this.videoLocalList = this.favList
- this.updateListData(this.videoLocalList)
- }
- })
- }
- // 组件消失生命周期
- aboutToDisappear() {
- console.info('LifeCycleComponent aboutToDisappear');
- emitter.off(2);
- this.mDestroyPage = true;
- this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
- if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
- this.stop();
- }
- this.mIjkMediaPlayer.off('audioInterrupt');
- if (workerInstance) {
- workerInstance.terminate();
- }
- }
- async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean) {
- this.isFavMusic = false
- if (isWorkerPost) {
- workerInstance.postMessage({ code: 2, data: this.context }); //刷新媒体库列表
- }
- if (this.modeType !== 0) {
- return
- }
- this.isCanBack = false
- this.currentPath = curPath
- this.titleBarModel.setTitleName(Utility.getFileDirName(this.currentPath, this.rootPath))
- if (curPath === this.rootPath) {
- this.titleBarModel.setLeftIconMain($r('app.media.menu'))
- } else {
- if (this.rootPath === Utility.getParentDirectory(curPath)) {
- this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
- }
- }
- // Get the current file list and calculate its hash
- this.fileList = FileUtil.listFileSync(curPath);
- const currentHash = simpleHash(this.fileList);
- // Check cache
- const cachedValue = this.findCache(curPath);
- Logger.info('onecold cachedValue = ' + cachedValue)
- const cachedHash = this.findStringCache(curPath + '_hash');
- const cachedDirList = this.findCache(curPath + "_dirList");
- if (cachedValue !== undefined) {
- // this.videoLocalList = cachedValue;
- Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
- this.updateListData(cachedValue)
- }
- if (cachedDirList !== undefined) {
- this.dirList = cachedDirList
- }
- //通过当前hash值和缓存hash判断list有没有变化
- if (cachedValue && cachedHash === currentHash) {
- return;
- }
- this.fileList = FileUtil.listFileSync(curPath)
- let directories: Array<VideoItem> = [];
- let files: Array<VideoItem> = [];
- for (let i = 0; i < this.fileList.length; i++) {
- console.info(`The name of file: ${this.fileList[i]}`);
- let path = curPath + '/' + this.fileList[i]
- if (FileUtil.isDirectory(path)) {
- let item: VideoItem =
- new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
- '')
- directories.push(item);
- directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
- Utility.doSortListAscending(directories)
- } else {
- if (this.currentPath === this.lockPath) {
- let item: VideoItem =
- await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
- if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
- files.push(item);
- // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
- // this.doSortListAscending(files)
- }
- }
- }
- }
- this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
- if (this.currentPath !== this.lockPath) {
- files = result;
- }
- files.sort((a, b) => a.cTime.localeCompare(b.cTime));
- Utility.doSortListAscending(files)
- if (this.currentPath === this.rootPath) {
- this.dirList = directories
- this.addCache(curPath + "_dirList", this.dirList);
- }
- if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
- let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
- directories.push(adItem)
- }
- // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
- this.videoLocalList = directories.concat(files);
- this.updateListData(this.videoLocalList)
- if (ArrayUtil.isNotEmpty(files)) {
- // 缓存结果
- this.addCache(curPath, this.videoLocalList);
- await this.saveCacheToStorage(); // 保存缓存至本地存储
- this.addStringCache(curPath + '_hash', currentHash);
- }
- console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
- // for (let i = 0; i < this.videoLocalList.length; i++) {
- //
- // console.info(`onecold gengxin 1: ${this.videoLocalList[i].pixelMapPath}`);
- //
- // }
- // this.setButtonStatus()
- if (isOpen) {
- if (destPath === undefined) {
- // 处理 destPath 为 undefined 的情况
- return
- }
- if (destPath.endsWith('.lrc')) {
- ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
- if (StrUtil.isNotEmpty(this.videoUrl)) {
- let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
- this.initLyric(lyricPath);
- }
- return
- }
- let item2 = new VideoItem(Utility.getMediaNameByUri(destPath), destPath, destPath, 0, 0, '')
- this.doPlay(item2)
- }
- });
- }
- //扫描文件夹入库
- async scanDirectory(curPath: string): Promise<VideoItem[]> {
- const files = FileUtil.listFileSync(curPath);
- let mediaItems: VideoItem[] = [];
- Logger.info('onecold scanDirectory start ')
- for (const file of files) {
- const fPath = `${curPath}/${file}`;
- if (fPath === this.lockPath) {
- Logger.info(`Skipping locked path: ${fPath}`);
- continue;
- }
- if (FileUtil.isDirectory(fPath)) {
- // Recursively scan subdirectories
- const subDirItems = await this.scanDirectory(fPath);
- mediaItems = mediaItems.concat(subDirItems);
- } else {
- Logger.info('onecold scanDirectory filePath = ' + fPath)
- // Process media files
- if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
- let mediaItem: VideoItem =
- await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, true);
- mediaItems.push(mediaItem);
- this.table.insert(mediaItem, (id: number) => {
- });
- }
- }
- }
- return mediaItems;
- }
- updateListData(mList: Array<VideoItem>, noSort?: boolean) {
- animateTo({ duration: 888 }, () => {
- this.opacityItem = 0;
- });
- setTimeout(() => {
- this.videoLocalList = mList;
- if (!noSort) {
- if (this.modeType === 0 || this.modeType === 1) {
- this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
- this.doSortType(this.sortType)
- }
- }
- this.dataSource.pushArrayData(this.videoLocalList)
- animateTo({ duration: 888 }, () => {
- this.opacityItem = 1;
- });
- this.setButtonStatus()
- }, 200);
- }
- //获取视频缩略图头像
- async updatePixelMaps(curPath: string) {
- console.info('updatePixelMaps: ', curPath);
- const updatedList = [...this.videoLocalList]; // 创建一个新的列表
- for (const videoItem of updatedList) {
- if (videoItem.type === CommonConstants.TYPE_LOCAL) {
- let pixelMap: image.PixelMap | undefined = undefined;
- const uri = videoItem.filePath;
- // 获取缩略图
- // if (Utility.isVideoByExtension(uri)) {
- // pixelMap = await Utility.getFetchFrameByTime(uri);
- // } else {
- // pixelMap = await Utility.getFetchMetadataFromFdSrcByPromise(uri);
- // }
- let name = await MD5.digestSync(uri)
- let imagePath = this.context.filesDir + FileUtil.separator + name
- console.info('onecold release success. name= ' + name);
- imagePath = fileUri.getUriFromPath(imagePath)
- videoItem.pixelMapPath = imagePath
- // videoItem.pixelMap = pixelMap;
- // videoItem.pixelMapToString = pixelMap ? await ImageUtil.pixelMapToBase64StrBig(pixelMap) : undefined;
- }
- }
- // console.info('updatePixelMaps完毕: ', updatedList.length);
- this.updateListData(updatedList)
- // this.videoLocalList = updatedList; // 重新赋值以触发更新
- // 缓存结果
- this.addCache(curPath, updatedList);
- await this.saveCacheToStorage(); // 保存缓存至本地存储
- }
- //排序模式和多选模式
- showPupDialog() {
- if (this.modeType === 2 || this.modeType === 3) {
- this.titleBarModel.setRightIcon(null)
- } else {
- this.titleBarModel.setRightIcon(($r('app.media.add')))
- }
- let dataBean = new BubbleBean()
- dataBean.data = ["首页", "媒体库", "艺术家", "专辑", "同步数据"]
- dataBean.imageRes =
- [$r('app.media.home_press'), $r('app.media.kp_music'), $r('app.media.music_menu'), $r('app.media.llq'),
- $r('app.media.refresh')]
- let pup: XPopup;
- if (this.isDarkMode) {
- pup = XPopup.Builder()
- .setPopupPosition(PopupPosition.BOTTOM)
- .atView('pup_positon_music')
- .setBackgroundColor(Color.Black)
- .asBubble(wrapBuilder(customPopupBuilder), dataBean)
- .show()
- }else {
- pup = XPopup.Builder()
- .setPopupPosition(PopupPosition.BOTTOM)
- .atView('pup_positon_music')
- .setBackgroundColor(Color.White)
- .asBubble(wrapBuilder(customPopupBuilder), dataBean)
- .show()
- }
- dataBean.onItemClick = (i) => {
- XPopup.dismissTop()
- switch (i) {
- case 0: //首页
- this.modeType = 0
- this.getSortedFiles(this.currentPath)
- break
- case 1:
- this.titleBarModel.setLeftIconMain($r('app.media.menu'))
- this.modeType = 1
- this.updateListData(this.mediaKuList)
- this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
- break
- case 2:
- this.modeType = 2
- this.titleBarModel.setLeftIconMain($r('app.media.menu'))
- this.updateListData(this.artistList)
- this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
- break
- case 3:
- this.modeType = 3
- this.titleBarModel.setLeftIconMain($r('app.media.menu'))
- this.updateListData(this.albumList)
- this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
- break
- case 4: //同步数据
- workerInstance.postMessage({
- code: 1,
- data1: this.context,
- data2: this.rootPath,
- data3: this.lockPath,
- data4: PreferencesUtil.getStringSync('COVER_API', ''),
- });
- break
- }
- }
- }
- getCurFileList(): Array<VideoItem> {
- let files: Array<VideoItem> = [];
- if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
- for (let i = 0; i < this.videoLocalList.length; i++) {
- if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
- files.push(this.videoLocalList[i]);
- }
- }
- }
- return files
- }
- setButtonStatus() {
- if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
- this.isZero = false
- } else {
- this.isZero = true
- }
- if (this.currentPath !== this.rootPath &&
- ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
- this.isHasDir = true //不为空,说明有子文件夹
- } else {
- this.isHasDir = false
- }
- }
- showRankDialog() {
- if (this.modeType === 2 || this.modeType === 3) {
- //动作面板
- DialogHelper.showBottomSheetDialog({
- title: "请选择排序模式",
- maskColor: Color.Transparent,
- // sheets: ["按名称升序", "按名称降序"],
- sheets:[
- {value:'按名称升序',fontColor: $r('app.color.text_color') },
- {value:'按名称降序',fontColor: $r('app.color.text_color') },
- ],
- backgroundColor:$r('app.color.bg_card'),
- height: '30%',
- transition: AnimationHelper.transitionInDown(555),
- onAction: (index) => {
- switch (index) {
- case 0:
- Utility.doSortListAscending(this.videoLocalList)
- break;
- case 1:
- Utility.doSortListDescending(this.videoLocalList)
- break;
- }
- this.updateListData(this.videoLocalList)
- }
- })
- return
- }
- //动作面板
- DialogHelper.showBottomSheetDialog({
- title: "请选择排序模式",
- maskColor: Color.Transparent,
- height: '75%',
- // sheets: ["按艺术家升序", "按艺术家降序", "按专辑升序", "按专辑降序", "按名称升序", "按名称降序", "按添加时间升序","按添加时间降序"],
- sheets:[
- { value: "按艺术家升序", fontColor: $r('app.color.text_color') },
- { value: "按艺术家降序", fontColor: $r('app.color.text_color') },
- { value: "按专辑升序", fontColor: $r('app.color.text_color') },
- { value: "按专辑降序", fontColor: $r('app.color.text_color') },
- { value: "按名称升序", fontColor: $r('app.color.text_color') },
- { value: "按名称降序", fontColor: $r('app.color.text_color') },
- { value: "按添加时间升序", fontColor: $r('app.color.text_color') },
- { value: "按添加时间降序", fontColor: $r('app.color.text_color') },
- ],
- backgroundColor: $r('app.color.bg_card'),
- transition: AnimationHelper.transitionInDown(555),
- onAction: (index) => {
- this.doSortType(index)
- this.updateListData(this.videoLocalList, true)
- }
- })
- }
- doSortType(index: number) {
- switch (index) {
- case 0:
- this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
- // 类型排序优先级
- const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
- if (typeOrder !== 0) {
- return typeOrder;
- }
- // 处理艺术家可能为undefined的字符串比较
- const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
- const artistB = b.artist?.trim() || '';
- return artistA.localeCompare(artistB);
- });
- break;
- case 1:
- this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
- // 类型排序优先级
- const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
- if (typeOrder !== 0) {
- return typeOrder;
- }
- // 处理艺术家可能为undefined的字符串比较
- const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
- const artistB = b.artist?.trim() || '';
- return artistB.localeCompare(artistA);
- });
- break;
- case 2:
- this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
- // 类型排序优先级
- const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
- if (typeOrder !== 0) {
- return typeOrder;
- }
- // 处理专辑可能为undefined的字符串比较
- const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
- const albumB = b.album?.trim() || '';
- return albumA.localeCompare(albumB);
- });
- break;
- case 3:
- this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
- // 类型排序优先级
- const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
- if (typeOrder !== 0) {
- return typeOrder;
- }
- // 处理专辑可能为undefined的字符串比较
- const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
- const albumB = b.album?.trim() || '';
- return albumB.localeCompare(albumA);
- });
- break;
- case 4:
- Utility.doSortListAscending(this.videoLocalList)
- break;
- case 5:
- Utility.doSortListDescending(this.videoLocalList)
- break;
- case 6:
- this.videoLocalList.sort((a, b) => {
- // First, sort by type
- const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
- if (typeOrder !== 0) {
- return typeOrder;
- }
- // If types are the same, sort by cTime in ascending order
- return a.cTime.localeCompare(b.cTime);
- });
- break;
- case 7:
- this.videoLocalList.sort((a, b) => {
- // First, sort by type
- const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
- if (typeOrder !== 0) {
- return typeOrder;
- }
- // If types are the same, sort by cTime in descending order
- return b.cTime.localeCompare(a.cTime);
- });
- break;
- }
- }
- showSheelDialog() {
- // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
- // this.showTips()
- // return
- // }
- this.showAddDialog()
- }
- showAddDialog() {
- if (this.modeType === 2 || this.modeType === 3) {
- return
- }
- DialogHelper.showActionSheetDialog({
- title: "请选择添加方式(建议歌词文件一起导入)",
- // sheets: ["新建歌单", "手动导入", "自动导入"],
- sheets:[
- { value: "新建歌单", fontColor: $r('app.color.text_color') },
- { value: "手动导入", fontColor: $r('app.color.text_color') },
- { value: "自动导入", fontColor: $r('app.color.text_color') },
- ],
- maskColor: Color.Transparent,
- backgroundColor: $r('app.color.bg_card'),
- transition: AnimationHelper.transitionInDown(555),
- onAction: (index) => {
- switch (index) {
- case 0:
- if (this.modeType === 0) {
- this.showMkDialog()
- } else {
- ToastUtil.showToast('请切换到首页才能新建歌单!')
- }
- break;
- case 1:
- this.callFilePickerSelectFile()
- break;
- case 2:
- this.showTips()
- break;
- }
- }
- })
- }
- async showTips() {
- DialogHelper.showTipsDialog({
- title: '使用提示:自动导入教程',
- content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
- + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
- '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
- '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
- onAction: (action) => {
- if (action == DialogAction.TWO) {
- PreferencesUtil.putSync('isFirstMusic', false)
- router.pushUrl({
- url: 'pages/ScanFilePage'
- });
- }
- }
- })
- }
- showMkDialog() {
- DialogHelper.showTextInputDialog({
- title: '新建歌单',
- maskColor: Color.Transparent,
- text: '',
- transition: AnimationHelper.transitionInDown(666),
- onChange: (text) => {
- console.error("onChange: " + text);
- },
- onAction: (action, dialogId, content) => {
- // ToastUtil.showToast('content = ' +content)
- if (action == DialogAction.TWO) {
- const newName = content
- const newPath = this.currentPath + '/' + newName
- FileUtil.mkdir(newPath, true).then(() => {
- this.cache.delete(this.currentPath); // 删除目标路径缓存
- this.getSortedFiles(this.currentPath)
- }).catch((error: BusinessError) => {
- console.error(error.message);
- });
- }
- }
- })
- }
- @State progress: number = 0;
- async saveVideoDatas(uris: string[], isOpen?: boolean) {
- if (ArrayUtil.isEmpty(uris)) {
- return;
- }
- let newUris: string[] = [];
- this.progress = 0
- DialogHelper.showLoadingProgress({
- progress: this.progress,
- backCancel: false,
- autoCancel: false,
- loadColor: $r('app.color.title_bar_bg'),
- fontColor: $r('app.color.title_bar_bg')
- });
- // 计算所有文件的总大小
- let totalSize = 0;
- for (let uri of uris) {
- const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
- totalSize += (await fileIo.stat(sourceFile.fd)).size;
- await fileIo.close(sourceFile.fd);
- }
- let totalRead = 0;
- let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
- Logger.info(TAG, 'destPath uri: ' + destPath);
- for (let i = 0; i < uris.length; i++) {
- let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
- Logger.info(TAG, 'filePath uri: ' + filePath);
- newUris.push(filePath);
- try {
- const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
- const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
- const buffSize = 1024 * 1024; // 1MB 缓冲区大小
- const buffer = new ArrayBuffer(buffSize);
- let len = await fileIo.read(sourceFile.fd, buffer);
- while (len > 0) {
- await fileIo.write(destFile.fd, buffer.slice(0, len));
- totalRead += len;
- // 计算总进度
- this.progress = Math.floor((totalRead / totalSize) * 100);
- DialogHelper.updateLoading('正在导入', this.progress);
- len = await fileIo.read(sourceFile.fd, buffer);
- }
- await fileIo.close(sourceFile.fd);
- await fileIo.close(destFile.fd);
- if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
- if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
- let mediaItem: VideoItem =
- await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, true);
- this.table.insert(mediaItem, (id: number) => {
- // 删除目标路径缓存
- this.cache.delete(this.currentPath);
- this.getSortedFiles(this.currentPath, true, destPath, isOpen)
- });
- }
- }
- } catch (error) {
- Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
- }
- }
- DialogHelper.closeLoading()
- this.isZero = false
- // setTimeout(() => {
- // // 删除目标路径缓存
- // this.cache.delete(this.currentPath);
- // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
- // }, 500);
- Logger.info(TAG, 'scan select video result:' + newUris)
- }
- //拉起音频
- // goSelectMusic(){
- //
- // try {
- // let audioSelectOptions = new picker.AudioSelectOptions();
- // let audioPicker = new picker.AudioViewPicker(this.context);
- // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
- // if (audioSelectResult !== null && audioSelectResult !== undefined) {
- // this.saveVideoDatas(audioSelectResult)
- // }
- // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
- // }).catch((err: BusinessError) => {
- //
- // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
- // });
- // } catch (error) {
- // let err: BusinessError = error as BusinessError;
- // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
- // }
- //
- //
- //
- // }
- goSelectImage() {
- if (!this.currentSong) {
- return
- }
- let selectUris: Array<string> = [];
- let photoPicker = new photoAccessHelper.PhotoViewPicker();
- let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
- photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; // 过滤选择媒体文件类型为IMAGE
- photoSelectOptions.maxSelectNumber = 1; // 选择媒体文件的最大数目
- photoPicker.select(photoSelectOptions).then(async (photoSelectResult: photoAccessHelper.PhotoSelectResult) => {
- //用一个全局变量存储返回的uri
- selectUris = photoSelectResult.photoUris;
- console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
- //使用fs.openSync接口,通过uri打开这个文件得到fd
- let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
- console.info('file fd: ' + file.fd);
- let name = await MD5.digestSync(this.videoUrl)
- let imagePath = this.context.filesDir + FileUtil.separator + name
- imagePath = fileUri.getUriFromPath(imagePath)
- let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
- fileIo.copyFileSync(file.fd, file2.fd)
- fileIo.closeSync(file);
- fileIo.closeSync(file2);
- this.cover = imagePath
- if (this.currentSong) {
- this.currentSong.pixelMapPath = imagePath
- }
- this.table.updatePixelMapPath(this.videoUrl, this.cover, (success: boolean, error?: string) => {
- if (success) {
- this.doUpdateData()
- console.log(" onecold 更新音乐封面成功,数据库已同步");
- } else {
- console.error(" onecold 更新音乐封面数据库失败原因: " + error);
- }
- });
- LogUtil.debug("onecold this.cover =" + this.cover)
- }).catch((err: BusinessError) => {
- console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
- })
- }
- // 拉起picker选择文件管理器
- async callFilePickerSelectFile(): Promise<void> {
- try {
- let DocumentSelectOptions = new picker.DocumentSelectOptions();
- // DocumentSelectOptions.multiAuthMode = true
- DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
- let documentPicker = new picker.DocumentViewPicker();
- documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
- Logger.info(TAG,
- 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
- if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
- this.saveVideoDatas(DocumentSelectResult)
- }
- }).catch((err: BusinessError) => {
- Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
- });
- } catch (err) {
- Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
- }
- }
- showWarnIsDeleteFile(item: VideoItem, index: string, filePath: string) {
- //操作确认类弹出框
- DialogHelper.showAlertDialog({
- maskColor: Color.Transparent,
- content: "确定要删除这个文件吗?",
- backgroundColor: Color.Grey,
- transition: AnimationHelper.transitionInUp(555),
- onAction: (action) => {
- if (action == DialogAction.ONE) {
- // ToastUtil.showToast(`您点击了取消按钮`);
- } else if (action == DialogAction.TWO) {
- // ToastUtil.showToast(`您点击了确认按钮`);
- this.doDelete(item, index + '', filePath)
- }
- }
- })
- }
- //删除单个索引index的视频
- doDelete(item: VideoItem, index: string, filePath: string) {
- if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
- Logger.info(TAG, 'delete filePath = ' + filePath);
- if (item.type === CommonConstants.TYPE_IS_DIR) {
- //旧文件删除
- this.table.deleteDataForParentPath(item.filePath, () => {
- FileUtil.rmdir(filePath).then(() => {
- this.videoLocalList.splice(Number(index), 1)
- this.deleteCache(this.currentPath)
- this.getSortedFiles(this.currentPath, true)
- }).catch((error: BusinessError) => {
- console.error(error.message);
- });
- });
- } else {
- this.table.deleteData(item, () => {
- FileUtil.unlink(filePath).then(() => {
- this.videoLocalList.splice(Number(index), 1)
- this.deleteCache(this.currentPath)
- this.getSortedFiles(this.currentPath, true)
- }).catch((error: BusinessError) => {
- console.error(error.message);
- });
- });
- }
- }
- }
- //重命名的对话框
- showReNameDialog(item: VideoItem, index: string, filePath: string) {
- DialogHelper.showTextInputDialog({
- title: '重命名',
- text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
- maskColor: Color.Transparent,
- backgroundColor: Color.Grey,
- transition: AnimationHelper.transitionInDown(666),
- onChange: (text) => {
- console.error("onChange: " + text);
- },
- onAction: (action, dialogId, content) => {
- // ToastUtil.showToast('content = ' +content)
- if (action == DialogAction.TWO) {
- const newName = content
- const newPath = this.currentPath + '/' + newName
- console.log("onecold item = " + item.type);
- this.doReName(index, newName, filePath, newPath, item)
- }
- }
- })
- }
- //剪切 移动到另个文件夹的对话框
- showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
- Logger.info('onecold showCutDialog')
- let mList: Array<string> = []
- let rPath = this.rootPath
- if (isCurrent) {
- mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
- rPath = this.currentPath
- } else {
- mList = Utility.getNameList(this.dirList);
- rPath = this.rootPath
- }
- let dataBean = new BubbleBean()
- dataBean.data = mList
- dataBean.onItemClick = (i) => {
- const newPath = rPath + '/' + mList[i] + '/' + item.fileName
- Logger.info('newPath = ' + newPath)
- FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
- ToastUtil.showToast('移动成功')
- this.table.deleteData(item, () => {
- });
- // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
- // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
- let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
- CommonConstants.TYPE_LOCAL, true);
- if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
- this.table.insert(newItem, (id: number) => {
- //加入数据库
- });
- }
- this.cache.delete(this.currentPath); // 删除原路径缓存
- this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
- this.getSortedFiles(this.currentPath, true)
- }).catch((error: BusinessError) => {
- console.error(error.message);
- });
- XPopup.dismissTop()
- }
- let popupPosition: PopupPosition = PopupPosition.BOTTOM
- if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
- popupPosition = PopupPosition.TOP
- }
- if (index <= 3) {
- popupPosition = PopupPosition.BOTTOM
- }
- let pup:XPopup
- if(this.isDarkMode){
- pup = XPopup.Builder()
- .setPopupPosition(popupPosition)
- .atView(id)
- .setBackgroundColor(Color.Black)
- .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
- .show()
- }else {
- pup = XPopup.Builder()
- .setPopupPosition(popupPosition)
- .atView(id)
- .setBackgroundColor(Color.White)
- .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
- .show()
- }
- }
- //复制 到另个文件夹的对话框
- showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
- Logger.info('onecoldv showCopyDialog')
- let mList: Array<string> = []
- let rPath = this.rootPath
- if (isCurrent) {
- mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
- rPath = this.currentPath
- } else {
- mList = Utility.getNameList(this.dirList);
- rPath = this.rootPath
- }
- let dataBean = new BubbleBean()
- dataBean.data = mList
- dataBean.isCopy = true
- dataBean.onItemClick = (i) => {
- const newPath = rPath + '/' + mList[i] + '/' + item.fileName
- Logger.info('newPath = ' + newPath)
- FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
- ToastUtil.showToast('复制成功')
- this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
- this.getSortedFiles(this.currentPath)
- // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
- // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
- let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
- CommonConstants.TYPE_LOCAL, true);
- if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
- this.table.insert(newItem, (id: number) => {
- //加入数据库
- });
- }
- }).catch((error: BusinessError) => {
- console.error(error.message);
- });
- XPopup.dismissTop()
- }
- let popupPosition: PopupPosition = PopupPosition.BOTTOM
- if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
- popupPosition = PopupPosition.TOP
- }
- if (index <= 3) {
- popupPosition = PopupPosition.BOTTOM
- }
- // let pup = XPopup.Builder()
- // .setPopupPosition(popupPosition)
- // .atView(id)
- // .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
- // .show()
- let pup:XPopup
- if (this.isDarkMode) {
- pup = XPopup.Builder()
- .setPopupPosition(popupPosition)
- .atView(id)
- .setBackgroundColor(Color.Black)
- .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
- .show();
- }else {
- pup = XPopup.Builder()
- .setPopupPosition(popupPosition)
- .atView(id)
- .setBackgroundColor(Color.White)
- .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
- .show();
- }
- }
- //重命名索引index的视频
- doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
- FileUtil.rename(oldPath, newPath).then(async () => {
- if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
- if (info.type === CommonConstants.TYPE_IS_DIR) {
- //如果是文件夹先删除源数据,再添加新数据
- this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
- if (success) {
- console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
- } else {
- console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
- }
- });
- this.scanDirectory(newPath)
- } else if (info.type === CommonConstants.TYPE_LOCAL) {
- this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
- if (success) {
- console.log(" onecold 重命名成功,数据库已同步");
- } else {
- console.error(" onecold 重命名数据库失败原因: " + error);
- }
- });
- }
- let mediaItem: VideoItem =
- await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, true);
- this.videoLocalList[index] = mediaItem;
- }
- this.cache.delete(this.currentPath)
- this.getSortedFiles(this.currentPath, true)
- }).catch((error: BusinessError) => {
- console.error(error.message);
- });
- }
- build() {
- Scroll() {
- Column() {
- Column(){
- Line().width('100%').height('100%')
- }
- .height(this.currentBreakpoint !== BreakpointTypeEnum.SM?0:CommonConstants.TOP_HEIGHT)
- .backgroundColor(this.isCustomizeBg?Color.Transparent:$r('app.color.title_bar_bg'))
- .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
- TitleBar({ model: $titleBarModel })
- .id('pup_positon_music')
- Stack() {
- Column() {
- XComponent({
- id: 'xcomponentId',
- type: 'surface',
- libraryname: 'ijkplayer_napi',
- controller: this.xcomponentController
- })
- .onLoad((event?: object) => {
- if (!!event) {
- this.initDelayPlay(event);
- }
- })
- .onDestroy(() => {
- })
- .width('100%')// .width(this.videoWidth)
- .aspectRatio(this.videoAspectRatio)
- }
- .aspectRatio(this.videoAspectRatio)
- .justifyContent(FlexAlign.Center)
- .backgroundColor(Color.Transparent)
- .visibility(Visibility.Hidden)
- .height(CommonConstants.FULL_PERCENT)
- .width(CommonConstants.FULL_PERCENT)
- Column() {
- this.tabTitle()
- this.listViewTitle()
- this.getListView()
- }
- .layoutWeight(1)
- .height('100%')
- Row() {
- Button(this.isAllSelected ? '全不选' : '全选', { type: ButtonType.Circle, stateEffect: true })
- .width('35%')
- .height(60)
- .margin({ top: 10, bottom: 10, right: 6 })
- .backgroundColor($r('app.color.tab_item_bg'))
- .onClick(() => {
- if (this.isAllSelected) {
- // 全不选
- this.selectedFiles = [];
- } else {
- // 全选
- this.selectedFiles = [...this.getCurFileList()];
- }
- this.isAllSelected = !this.isAllSelected;
- })
- Button('剪切', { type: ButtonType.Circle, stateEffect: true })
- .width('35%')
- .height(60)
- .id('music_cut')
- .margin({ top: 10, bottom: 10, right: 6 })
- .backgroundColor($r('app.color.tab_item_bg'))
- .onClick(() => {
- this.showCutDialogForMultipleFiles(false, 'music_cut')
- })
- Button('移动', { type: ButtonType.Circle, stateEffect: true })
- .width('35%')
- .height(60)
- .id('music_cut_current')
- .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
- .margin({ top: 10, bottom: 10, right: 6 })
- .backgroundColor($r('app.color.tab_item_bg'))
- .onClick(() => {
- this.showCutDialogForMultipleFiles(true, 'music_cut_current')
- })
- Button('复制', { type: ButtonType.Circle, stateEffect: true })
- .width('35%')
- .height(60)
- .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
- .margin({ top: 10, bottom: 10, right: 6 })
- .backgroundColor($r('app.color.tab_item_bg'))
- .onClick(() => {
- this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
- })
- Button('删除', { type: ButtonType.Circle, stateEffect: true })
- .width('35%')
- .height(60)
- .margin({ top: 10, bottom: 10, right: 6 })
- .visibility(this.isFavMusic?Visibility.None:Visibility.Visible)
- .backgroundColor($r('app.color.tab_item_bg'))
- .onClick(() => {
- this.showWarnIsDelete()
- })
- Button('取消', { type: ButtonType.Circle, stateEffect: true })
- .width('35%')
- .height(60)
- .margin({ top: 10, bottom: 10, right: 6 })
- .backgroundColor($r('app.color.tab_item_bg'))
- .onClick(() => {
- this.selectedFiles = [];
- this.isAllSelected = false
- this.isMultiSelect = false
- })
- }
- .width('100%')
- .justifyContent(FlexAlign.Center)
- .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
- .opacity(this.isMultiSelect ? 1 : 0)
- .animation({
- duration: 666,
- curve: 'ease-in-out' // 可选动画曲线
- })
- .position({ bottom: 108 }) // 将 Row 固定在底部
- Column() {
- Button('导入音乐', { type: ButtonType.Capsule, stateEffect: true })
- .width('50%')
- .height(55)
- .margin({ top: 50, bottom: 40 })
- .backgroundColor($r('app.color.title_bar_bg'))
- .onClick(() => {
- this.showSheelDialog()
- })
- }
- .height('100%')
- .justifyContent(FlexAlign.Center)
- .opacity(this.isZero ? 1 : 0)
- .visibility(this.isZero && this.modeType === 0 ? Visibility.None : Visibility.None)
- .animation({
- duration: 666,
- curve: 'ease-in-out' // 可选动画曲线
- })
- .width('100%')
- }
- .width('100%')
- .height('100%')
- .alignContent(Alignment.Top)
- Column() {
- this.PlayController()
- }
- .hitTestBehavior(HitTestMode.Transparent)
- .position({ bottom: 0 }) // 将 Row 固定在底部
- .opacity(this.barOpacity)
- }
- .width('100%')
- .height('100%')
- .backgroundImage(this.isCustomizeBg?this.customizeBgPath:$r('app.color.bottom_control_background'))
- .backgroundImageSize({ height: '100%'})
- .backgroundImagePosition(Alignment.Center)
- // .backgroundColor($r('app.color.bottom_control_background'))
- .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
- }
- }
- // 处理文件选择的函数
- handleFileSelection(item: VideoItem, checked: boolean) {
- if (checked) {
- this.selectedFiles.push(item);
- } else {
- const index = this.selectedFiles.indexOf(item);
- if (index > -1) {
- this.selectedFiles.splice(index, 1);
- }
- }
- }
- showWarnIsDelete() {
- //操作确认类弹出框
- DialogHelper.showAlertDialog({
- content: "确定要删除这些文件吗?",
- transition: AnimationHelper.transitionInUp(666),
- maskColor: Color.Transparent,
- backgroundColor: Color.Grey,
- onAction: (action) => {
- if (action == DialogAction.ONE) {
- // ToastUtil.showToast(`您点击了取消按钮`);
- } else if (action == DialogAction.TWO) {
- // ToastUtil.showToast(`您点击了确认按钮`);
- this.deleteMultipleFiles()
- }
- }
- })
- }
- //多选删除文件
- deleteMultipleFiles() {
- if (ArrayUtil.isNotEmpty(this.selectedFiles)) {
- this.selectedFiles.forEach((item) => {
- Logger.info(TAG, 'delete filePath = ' + item.filePath);
- if (item.type === CommonConstants.TYPE_IS_DIR) {
- this.table.deleteDataForParentPath(item.filePath, () => {
- FileUtil.rmdir(item.filePath).then(() => {
- this.videoLocalList = this.videoLocalList.filter(v => v !== item);
- this.selectedFiles = [];
- this.isMultiSelect = false
- this.isAllSelected = false
- this.cache.delete(this.currentPath);
- this.getSortedFiles(this.currentPath, true);
- }).catch((error: Error) => {
- console.error(error.message);
- });
- });
- } else {
- this.table.deleteData(item, () => {
- FileUtil.unlink(item.filePath).then(() => {
- this.videoLocalList = this.videoLocalList.filter(v => v !== item);
- this.selectedFiles = [];
- this.isMultiSelect = false
- this.isAllSelected = false
- this.cache.delete(this.currentPath);
- this.getSortedFiles(this.currentPath, true);
- }).catch((error: Error) => {
- console.error(error.message);
- });
- });
- }
- });
- }
- }
- //多选移动文件
- showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
- Logger.info('onecold showCutDialogForMultipleFiles')
- let mList: Array<string> = []
- let rPath = this.rootPath
- if (isCurrent) {
- mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
- rPath = this.currentPath
- } else {
- mList = Utility.getNameList(this.dirList);
- rPath = this.rootPath
- }
- let dataBean = new BubbleBean();
- dataBean.data = mList;
- dataBean.onItemClick = (i) => {
- const newDirPath = rPath + '/' + mList[i];
- // Logger.info('newDirPath = ' + newDirPath)
- this.selectedFiles.forEach((item) => {
- const newPath = newDirPath + '/' + item.fileName;
- FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
- ToastUtil.showToast('移动成功');
- this.table.deleteData(item, () => {
- this.cache.delete(this.currentPath); // 删除原路径缓存
- this.cache.delete(newDirPath); // 删除目标路径缓存
- this.getSortedFiles(this.currentPath, true);
- });
- // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
- // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
- let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
- CommonConstants.TYPE_LOCAL, true);
- if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
- this.table.insert(newItem, (id: number) => {
- //加入数据库
- });
- }
- }).catch((error: Error) => {
- console.error(error.message);
- });
- });
- this.isMultiSelect = false
- this.selectedFiles = [];
- this.isAllSelected = false
- XPopup.dismissTop();
- };
- // let pup = XPopup.Builder()
- // .setPopupPosition(PopupPosition.TOP)
- // .atView(viewId)
- // .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
- // .show();
- let pup:XPopup
- if (this.isDarkMode) {
- pup = XPopup.Builder()
- .setPopupPosition(PopupPosition.TOP)
- .atView(viewId)
- .setBackgroundColor(Color.Black)
- .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
- .show();
- }else {
- pup = XPopup.Builder()
- .setPopupPosition(PopupPosition.TOP)
- .atView(viewId)
- .setBackgroundColor(Color.White)
- .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
- .show();
- }
- }
- doFav(item:VideoItem){
- LogUtil.info('onecold doFav isFav=' +item.isFav)
- let isFav = 0
- if(Utility.getIsFav(this.favList,item)){
- isFav = 0
- }else{
- isFav = 1
- }
- this.table.updateIsFavByFilePath(item.filePath,isFav, async (result: boolean) => {
- if(result){
- if(isFav===1){
- ToastUtil.showToast('收藏成功');
- }else{
- ToastUtil.showToast('取消收藏成功');
- }
- this.deleteCache(this.currentPath)
- this.getFavList(false)
- if(this.modeType===0&&!this.isFavMusic){
- LogUtil.info('onecold doFav currentPath ='+ this.currentPath)
- this.getSortedFiles(this.currentPath)
- }
- workerInstance.postMessage({ code: 2, data: this.context });
- workerInstance.postMessage({ code: 3, data: this.context });
- workerInstance.postMessage({ code: 4, data: this.context });
- }
- })
- }
- //多选复制文件
- showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
- console.log('onecold showCopyDialogForMultipleFiles');
- let mList: Array<string> = []
- let rPath = this.rootPath
- if (isCurrent) {
- mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
- rPath = this.currentPath
- } else {
- mList = Utility.getNameList(this.dirList);
- rPath = this.rootPath
- }
- let dataBean = new BubbleBean();
- dataBean.data = mList;
- dataBean.isCopy = true
- dataBean.onItemClick = (i) => {
- const newDirPath = rPath + '/' + mList[i];
- // Logger.info('newDirPath = ' + newDirPath)
- this.selectedFiles.forEach((item) => {
- const newPath = newDirPath + '/' + item.fileName;
- FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
- ToastUtil.showToast('复制成功');
- this.cache.delete(newDirPath); // 删除目标路径缓存
- this.getSortedFiles(this.currentPath);
- // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
- // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
- let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
- CommonConstants.TYPE_LOCAL, true);
- if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
- this.table.insert(newItem, (id: number) => {
- //加入数据库
- });
- }
- }).catch((error: Error) => {
- console.error(error.message);
- });
- });
- this.isMultiSelect = false
- this.selectedFiles = [];
- this.isAllSelected = false
- XPopup.dismissTop();
- };
- let pup:XPopup
- if (this.isDarkMode) {
- pup = XPopup.Builder()
- .setPopupPosition(PopupPosition.TOP)
- .atView(viewId)
- .setBackgroundColor(Color.Black)
- .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
- .show();
- }else {
- pup = XPopup.Builder()
- .setPopupPosition(PopupPosition.TOP)
- .atView(viewId)
- .setBackgroundColor(Color.White)
- .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
- .show();
- }
- }
- @Builder
- private DirItem(item: VideoItem, index?: number) {
- Row() {
- Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
- $r('app.media.music_group'))
- .height(33)
- .width(33)
- .alt($r('app.media.music_group'))
- .borderRadius('100%')
- .clip(true)
- .margin({ left: 20, top: 8, bottom: 8 })
- Column() {
- Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
- .fontSize(16)
- .maxLines(1)// .width('88%')
- .animation({
- duration: 555,
- curve: 'ease-in-out',
- })
- .transition({
- type: TransitionType.Insert,
- opacity: 0,
- translate: { x: 160 }
- })
- .margin({ left: 10, right: 20 })
- .fontColor($r('app.color.text_color'))
- Row() {
- Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
- .fontSize(11)
- .padding({ top: 8 })
- .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 10 })
- Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
- .fontSize(11)
- .padding({ top: 8 })
- .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 10 })
- Blank()
- }
- }
- .height('100%')
- .layoutWeight(1)
- .justifyContent(FlexAlign.Center)
- .alignItems(HorizontalAlign.Start)
- Blank()
- Image($r('app.media.arrow_right'))
- .height(25)
- .margin({ right: 10 })
- .alignSelf(ItemAlign.Center)
- .id(item.filePath)
- }
- .height(58)
- .width('100%')
- .visibility(this.isShowDir(item.name)?Visibility.Visible:Visibility.None)
- .opacity(this.opacityItem) // 绑定透明度
- .stateStyles({
- pressed: { opacity: 0.6 } // 按压反馈
- })
- }
- isShowDir(dirName:string){
- this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
- this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
- this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
- if(dirName ===undefined)
- return true
- if(dirName === LocalMusic.STR_LOCK_VIDEO){
- return this.isShowSimi
- }
- if(dirName === LocalMusic.STR_FAC_VIDEO){
- return this.isShowFAV
- }
- if(dirName === LocalMusic.STR_HISTORY_MUSIC){
- return this.isShowHistory
- }
- return true
- }
- @State opacityItem: number = 1; // 控制透明度的状态变量
- @Builder
- private MusicItem(item: VideoItem, index?: number) {
- Row() {
- Stack() {
- Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
- .height(33)
- .width(33)
- .alt($r('app.media.music_red'))
- .borderRadius('100%')
- .clip(true)
- .opacity(this.opacityItem)// 绑定透明度
- .margin({ left: 20 })
- }
- .width('15%')
- Column() {
- Column() {
- Text(item.name)
- .fontSize(14)
- .maxLines(1)
- .animation({
- duration: 555,
- curve: 'Linear',
- })
- .fontColor(this.currentSong?.filePath === item.filePath ? $r('app.color.title_bar_bg_text') :
- $r('app.color.text_color'))
- .margin({ left: 10 })
- Row() {
- Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
- .fontSize(11)
- .padding({ top: 8 })
- .fontColor(this.currentSong?.filePath === item.filePath ? $r('app.color.title_bar_bg_text') :
- $r('app.color.text_color'))
- .margin({ left: 10 })
- Blank()
- Text(item.size)
- .fontSize(11)
- .padding({ top: 8 })
- .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
- .fontColor(this.currentSong?.filePath === item.filePath ? $r('app.color.title_bar_bg_text') :
- $r('app.color.text_color'))
- .margin({ left: 10 })
- }
- }
- .height('100%')
- .width('100%')
- .justifyContent(FlexAlign.Center)
- .alignItems(HorizontalAlign.Start)
- }
- .height('100%')
- .width('65%')
- Column() {
- Checkbox({ name: 'checkbox' + index })
- .select(this.selectedFiles.some(x => x.filePath === item.filePath))
- .selectedColor(0x39a2db)
- .shape(CheckBoxShape.CIRCLE)
- .opacity(this.isMultiSelect ? 1 : 0)
- .animation({
- duration: 666,
- curve: 'Smooth' // 可选动画曲线
- })
- .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
- .onChange((checked: boolean) => this.handleFileSelection(item, checked))
- .margin({ left: 20, top: 8, bottom: 8 })
- .width(22)
- .height(22)
- ImageAnimator()
- .images(this.imagesF)// 动画数组
- .duration(1000)// 持续
- .state(this.animationState)// 动画状态
- .fillMode(FillMode.Forwards)
- .width(18)
- .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
- Visibility.None)
- .height(18)
- .iterations(-1) // 播放次数
- }
- .width('18%')
- }
- .width('100%')
- .height(58)
- .justifyContent(FlexAlign.SpaceBetween)
- .stateStyles({
- pressed: { opacity: 0.6 } // 按压反馈
- })
- }
- private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
- @Builder
- tabTitle() {
- Column() {
- // 使用 Stack 布局来实现绝对定位效果
- Stack() {
- // 背景动画容器
- Row() {
- ForEach(this.tabs, (i: string, index) => {
- Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
- Flex()
- .backgroundColor($r('app.color.tab_item_bg'))
- .borderRadius(20)
- .padding(10)
- .margin(6)
- .width('100%')
- .height('100%')
- .visibility(this.modeType === index ? Visibility.Visible : Visibility.None)
- .opacity(this.modeType === index ? 1 : 0)
- .animation({
- duration: 666,
- playMode: PlayMode.Normal,
- curve: 'ease-in-out'
- });
- }
- .layoutWeight(1)
- .margin({ left: 5, right: 5, bottom: 1 });
- });
- }
- .width('100%')
- .height(50);
- // 导航栏容器
- Row() {
- ForEach(this.tabs, (item: string, index) => {
- Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
- Text(item)
- .fontSize(16)
- .fontColor(this.modeType === index ? Color.White : $r('app.color.text_color'))
- .padding(15)
- .onClick(() => {
- this.modeType = index;
- this.onModeChange();
- });
- }
- .layoutWeight(1)
- .stateStyles({
- pressed: { opacity: 0.6 } // 按压反馈
- });
- });
- }
- .width('100%')
- .height(this.topBarHeight)
- .opacity(this.barOpacity)
- .backgroundColor(Color.Transparent);
- }
- .width('100%')
- .height(this.topBarHeight)
- .opacity(this.barOpacity)
- Line().width('100%').height(1).backgroundColor($r('app.color.index_background'))
- .opacity(this.barOpacity)
- .visibility(this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
- }
- }
- @Builder
- listViewTitle() {
- Column() {
- Row({ space: 8 }) {
- Row({ space: 8 }) {
- Image($r("app.media.hm_playlist"))
- .width(25)
- .margin({ left: 8 })
- .fillColor('#ff5186')
- Text(`共找到${this.artistList.length}位艺术家`)
- .fontColor($r('app.color.text_color'))
- .fontSize(14)
- .opacity(this.opacityItem)
- .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
- Text(`共找到${this.albumList.length}张专辑`)
- .fontColor($r('app.color.text_color'))
- .opacity(this.opacityItem)
- .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
- .fontSize(14)
- }
- .layoutWeight(1)
- .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
- Row() {
- TextInput({
- placeholder: this.modeType === 2 ? '输入艺术家名称...' : '输入专辑名称...',
- text: this.searchText
- })
- .height(35)
- .onChange((value: string) => {
- this.onSearchInput(value);
- })
- .layoutWeight(1)
- Text(`取消`)
- .margin({ left: 10, right: 10 })
- .fontColor($r('app.color.text_color'))
- .fontSize(16)
- .onClick(() => {
- this.isSearchMode = false
- this.searchText = ''
- if (this.modeType === 2) {
- this.updateListData(this.artistList)
- } else {
- this.updateListData(this.albumList)
- }
- })
- }
- .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
- .animation({
- duration: 666,
- curve: 'ease-in-out' // 可选动画曲线
- })
- Blank()
- Image($r("app.media.search"))
- .width(25)
- .visibility(this.modeType === 2 || this.modeType === 3 ? Visibility.Visible : Visibility.None)
- .animation({
- duration: 666,
- curve: 'ease-in-out' // 可选动画曲线
- })// .opacity(this.opacityItem)
- .clickEffect({ level: ClickEffectLevel.MIDDLE })
- .onClick(() => {
- this.isSearchMode = true
- })
- Image($r("app.media.top_rank"))
- .width(25)// .opacity(this.opacityItem)
- .animation({
- duration: 666,
- curve: 'ease-in-out' // 可选动画曲线
- })
- .clickEffect({ level: ClickEffectLevel.MIDDLE })
- .onClick(() => {
- this.showRankDialog()
- })
- }
- .visibility(((this.modeType === 2 || this.modeType === 3) && !this.isCanBack) ? Visibility.Visible :
- Visibility.None)
- .width('100%')
- .padding(10)
- .height(50)
- .border({
- width: { bottom: 1 },
- color: this.isCustomizeBg?Color.Transparent:'#12ec5c87'
- })
- Row({ space: 8 }) {
- Row({ space: 8 }) {
- Image($r("app.media.hm_play"))
- .width(25)
- .margin({ left: 8 })
- .fillColor('#ff5186')
- Text(`播放全部`)
- .fontColor($r('app.color.text_color'))
- .fontSize(14)
- .animation({
- duration: 666,
- curve: 'ease-in-out' // 可选动画曲线
- })
- Text(`(${Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length}首)`)
- .fontColor($r('app.color.text_color'))
- .fontSize(14)
- .opacity(this.opacityItem)
- .animation({
- duration: 666,
- curve: 'ease-in-out' // 可选动画曲线
- })
- }
- .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
- .animation({
- duration: 666,
- curve: 'ease-in-out' // 可选动画曲线
- })
- .backgroundColor(this.isClickedPLayAll ? $r('app.color.button_click') : Color.Transparent)
- .onTouch((event: TouchEvent) => {
- if (event.type === TouchType.Down) {
- this.isClickedPLayAll = true;
- } else if (event.type === TouchType.Up || event.type === TouchType.Cancel) {
- this.isClickedPLayAll = false;
- }
- })
- .onClick(() => {
- if (this.modeType === 0) {
- if (ArrayUtil.isNotEmpty(this.getCurFileList())) {
- this.doPlay(this.getCurFileList()[0])
- }
- } else {
- if (ArrayUtil.isNotEmpty(this.mediaKuList)) {
- this.doPlay(this.mediaKuList[0])
- }
- }
- })
- Row() {
- TextInput({ placeholder: '输入名称...', text: this.searchText })
- .height(35)
- .onChange((value: string) => {
- this.onSearchInput(value);
- })
- .layoutWeight(1)
- Text(`取消`)
- .margin({ left: 10, right: 10 })
- .fontColor($r('app.color.text_color'))
- .fontSize(16)
- .onClick(() => {
- this.isSearchMode = false
- this.searchText = ''
- this.updateListData(this.mediaKuList)
- })
- }
- .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
- .animation({
- duration: 666,
- curve: 'ease-in-out' // 可选动画曲线
- })
- Blank()
- Image($r("app.media.search"))
- .width(25)// .visibility(this.modeType===1?Visibility.Visible:Visibility.None)
- .animation({
- duration: 666,
- curve: 'ease-in-out' // 可选动画曲线
- })// .opacity(this.opacityItem)
- .clickEffect({ level: ClickEffectLevel.MIDDLE })
- .onClick(() => {
- this.isSearchMode = true
- })
- Image($r("app.media.refresh"))
- .width(25)
- .visibility(this.isHistory || this.isCanBack || this.isSearchMode ? Visibility.None : Visibility.Visible)
- .animation({
- duration: 666,
- curve: 'ease-in-out' // 可选动画曲线
- })// .opacity(this.opacityItem)
- .clickEffect({ level: ClickEffectLevel.MIDDLE })
- .onClick(() => {
- if(this.isFavMusic){
- this.getFavList(true)
- }else{
- this.deleteCache(this.currentPath)
- this.getSortedFiles(this.currentPath)
- }
- })
- Image($r("app.media.top_rank"))
- .width(25)
- .visibility(this.isHistory || this.isSearchMode ? Visibility.None :
- Visibility.Visible)// .opacity(this.opacityItem)
- .animation({
- duration: 666,
- curve: 'ease-in-out' // 可选动画曲线
- })
- .clickEffect({ level: ClickEffectLevel.MIDDLE })
- .onClick(() => {
- this.showRankDialog()
- })
- Image(this.isMultiSelect ? $r("app.media.cancel_multi") : $r("app.media.top_flower"))
- .width(24)
- .margin({ right: 10 })
- .fillColor('#ff5186')// .opacity(this.opacityItem)
- .visibility(this.isHistory || this.isSearchMode ? Visibility.None : Visibility.Visible)
- .animation({
- duration: 666,
- curve: 'ease-in-out' // 可选动画曲线
- })
- .clickEffect({ level: ClickEffectLevel.MIDDLE })
- .onClick(() => {
- this.isMultiSelect = !this.isMultiSelect
- })
- Image($r("app.media.uninstall_green"))
- .width(24)
- .margin({ right: 10 })
- .fillColor('#ff5186')
- .visibility(this.isHistory ? Visibility.Visible : Visibility.None)
- .animation({
- duration: 666,
- curve: 'ease-in-out' // 可选动画曲线
- })
- .clickEffect({ level: ClickEffectLevel.MIDDLE })
- .onClick(() => {
- this.clearVideoHistory() //清空播放记录
- })
- }
- .width('100%')
- .padding(10)
- .height(50)
- .visibility(this.modeType === 0 || this.modeType === 1 || this.isCanBack ? Visibility.Visible : Visibility.None)
- .border({
- width: { bottom: 1 },
- color: this.isCustomizeBg?Color.Transparent:'#12ec5c87'
- })
- }
- .height(this.topBarHeight)
- .opacity(this.barOpacity)
- }
- //搜索功能的实现
- @State searchText: string = ''; // 用户输入内容
- @State filteredList: Array<VideoItem> = []; // 过滤后的结果
- @State isSearchMode: boolean = false
- // 实时搜索逻辑(带防抖)
- private onSearchInput(value: string) {
- this.searchText = value.trim();
- let mSearchList: Array<VideoItem> = []
- switch (this.modeType) {
- case 0:
- mSearchList = this.videoLocalList
- break;
- case 1:
- mSearchList = this.mediaKuList
- break;
- case 2:
- mSearchList = this.artistList
- break;
- case 3:
- mSearchList = this.albumList
- break;
- }
- // 新增条件判断:空输入时显示所有数据
- if (this.searchText === '') {
- this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
- } else {
- this.filteredList = mSearchList.filter((item: VideoItem) => {
- return item.name.toLowerCase().includes(this.searchText.toLowerCase());
- });
- }
- this.updateListData(this.filteredList);
- // this.isSearchMode = false; // 根据业务需求决定是否启用
- }
- @State dragItem: number = -1
- @State scaleItem: number = -1
- @State neighborItem: number = -1
- @State neighborScale: number = -1
- @State offsetY: number = 0
- private dragRefOffset: number = 0
- private ITEM_INTV: number = 78
- scaleSelect(item: number): number {
- if (this.scaleItem === item) {
- return 1.05
- } else if (this.neighborItem === item) {
- return this.neighborScale
- } else {
- return 1
- }
- }
- itemMove(index: number, newIndex: number): void {
- if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
- return;
- }
- let tmp = this.videoLocalList.splice(index, 1);
- this.videoLocalList.splice(newIndex, 0, tmp[0]);
- this.dataSource.pushArrayData(this.videoLocalList)
- }
- @Builder
- getListView() {
- List() {
- LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
- ListItem() {
- Column() {
- if (item.type === CommonConstants.TYPE_IS_DIR
- || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
- this.DirItem(item, index)
- } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
- //穿山甲
- if (this.isShowAd) {
- Row() {
- NodeContainer(this.bannerAd.getAdComponent())
- .width('92%')
- .height(this.mAdSlot.getAcceptHeight())
- .alignSelf(ItemAlign.Center)
- .align(Alignment.Center)
- // .margin({left:10})
- Image($r('app.media.close'))
- .height(15)
- .aspectRatio(1)
- .visibility(Visibility.None)
- .margin({ right: 15 })// .position({ x:20 })
- .onClick(() => {
- this.isShowAd = false
- })
- Blank()
- }
- .opacity(this.opacityItem) // 绑定透明度
- }
- } else {
- this.MusicItem(item, index)
- }
- }
- .shadow(this.scaleItem === index ? {
- radius: 70,
- color: '#15000000',
- offsetX: 0,
- offsetY: 0
- } :
- {
- radius: 0,
- color: '#15000000',
- offsetX: 0,
- offsetY: 0
- })
- .animation({ curve: Curve.Sharp, duration: 300 })
- }
- .swipeAction((this.modeType !== 3 && this.modeType !== 2 && item.type !== CommonConstants.TYPE_IS_CSJAD &&
- !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath) } : {}) //左滑
- .onClick(() => {
- this.doPlay(item, index)
- })
- //拖动List关键代码开始
- .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
- .zIndex(this.dragItem === index ? 1 : 0)
- .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
- .gesture(
- GestureGroup(GestureMode.Sequence,
- LongPressGesture({ repeat: true })
- .onAction((event?: GestureEvent) => {
- animateTo({ curve: Curve.Friction, duration: 300 }, () => {
- this.scaleItem = index
- })
- })
- .onActionEnd(() => {
- animateTo({ curve: Curve.Friction, duration: 300 }, () => {
- this.scaleItem = -1
- })
- }),
- PanGesture({ fingers: 1, direction: null, distance: 0 })
- .onActionStart(() => {
- this.dragItem = index // 记录当前拖动项索引
- this.dragRefOffset = 0 // 重置偏移基准
- })
- .onActionUpdate((event: GestureEvent) => {
- this.offsetY = event.offsetY - this.dragRefOffset;
- this.neighborItem = -1;
- let indexA = this.videoLocalList.indexOf(item);
- // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
- let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
- let value: number = 0;
- if (this.offsetY < 0) {
- value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
- this.neighborItem = indexA - 1;
- this.neighborScale = 1 - value / 20;
- } else if (this.offsetY > 0) {
- value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
- this.neighborItem = indexA + 1;
- this.neighborScale = 1 - value / 20;
- }
- if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
- animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
- this.offsetY -= this.ITEM_INTV;
- this.dragRefOffset += this.ITEM_INTV;
- this.itemMove(indexA, indexA + 1);
- });
- } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
- animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
- this.offsetY += this.ITEM_INTV;
- this.dragRefOffset -= this.ITEM_INTV;
- this.itemMove(indexA, indexA - 1);
- });
- }
- })
- .onActionEnd((event: GestureEvent) => {
- animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
- this.dragItem = -1
- this.neighborItem = -1
- })
- animateTo({
- curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
- }, () => {
- this.scaleItem = -1
- })
- })
- )
- .onCancel(() => {
- animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
- this.dragItem = -1
- this.neighborItem = -1
- })
- animateTo({
- curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
- }, () => {
- this.scaleItem = -1
- })
- })
- ) //拖动List关键代码结束
- }, (item: VideoItem) => item.filePath)
- }
- // .divider({ strokeWidth: 1, color: this.isDarkMode? '#333333':'#ffe9f0f0' })
- .margin({ bottom: this.isPuraWP() ? 100 : 158 })
- .cachedCount(30)
- .borderRadius(20)
- .layoutWeight(1)
- .lanes(
- new BreakpointType<number>({
- sm: 1,
- md: 2,
- lg: 3,
- xl: 4,
- xxl: 4
- }).getValue(this.currentBreakpoint),
- new BreakpointType<number>({
- sm: 0,
- md: 12,
- lg: 16,
- xl: 18,
- xxl: 20
- }).getValue(this.currentBreakpoint)
- )
- .onScrollFrameBegin((offset: number) => {
- if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
- (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
- this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
- this.hideDone = false;
- this.getUIContext().animateTo({
- duration: 300
- }, () => {
- this.bottomBarHeight = 55 + 0;
- this.topBarHeight = 50 + 0;
- this.barOpacity = 1;
- this.currentYOffset = 0;
- this.isHiding = false;
- });
- return { offsetRemain: offset };
- }
- if (offset > 0 && !this.hideDone) {
- this.currentYOffset += offset;
- if (this.currentYOffset <= 100) {
- this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
- this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
- this.barOpacity = 1 - this.currentYOffset / 100;
- } else {
- this.topBarHeight = 0;
- this.bottomBarHeight = 0;
- this.barOpacity = 0;
- this.hideDone = true;
- }
- this.isHiding = true;
- }
- if (offset < 0 && this.isHiding) {
- this.hideDone = false;
- this.getUIContext().animateTo({
- duration: 300
- }, () => {
- this.bottomBarHeight = 55 + 0;
- this.topBarHeight = 50 + 0;
- this.barOpacity = 1;
- this.currentYOffset = 0;
- this.isHiding = false;
- });
- }
- return { offsetRemain: offset };
- })
- }
- private doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean) {
- switch (item.type) {
- case CommonConstants.TYPE_IS_DIR:
- if (item.name === LocalMusic.STR_LOCK_VIDEO) {
- this.showVerifyDialog()
- } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
- this.titleBarModel.setTitleName('最近播放')
- //加载动画效果
- this.updateListData(this.historyList)
- // this.videoLocalList = this.historyList
- if (ArrayUtil.isEmpty(this.historyList)) {
- ToastUtil.showToast('最近播放记录空空如也')
- }
- this.isHistory = true
- this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
- } else if(item.name === LocalMusic.STR_FAC_VIDEO){
- this.titleBarModel.setTitleName('我的收藏')
- //加载动画效果
- this.updateListData(this.favList)
- if(ArrayUtil.isEmpty(this.favList)){
- ToastUtil.showToast('无音乐收藏记录')
- }
- this.isFavMusic = true
- this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
- }else {
- this.currentPath = item.filePath
- this.getSortedFiles(this.currentPath)
- }
- break;
- case CommonConstants.TYPE_IS_ARTIST:
- let mList = this.artistMap.get(item.name)
- if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
- Utility.doSortListAscending(mList)
- this.isCanBack = true
- this.titleBarModel.setTitleName(item.name)
- this.updateListData(mList)
- this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
- }
- break;
- case CommonConstants.TYPE_IS_ALBUM:
- let albumList = this.albumMap.get(item.name)
- if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
- Utility.doSortListAscending(albumList)
- this.isCanBack = true
- this.titleBarModel.setTitleName(item.name)
- this.updateListData(albumList)
- this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
- }
- break;
- case CommonConstants.TYPE_IS_CSJAD:
- return
- break;
- case CommonConstants.TYPE_LOCAL:
- if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
- this.stop();
- }
- if (isFromSonPlayList) { //点击来自右下角的播放列表
- this.currentSong = item
- if (index !== undefined) {
- this.curIndex = index
- }
- } else {
- let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
- this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
- this.songList = globalVideoList
- this.sonDataSource.pushArrayData(this.songList)
- this.currentSong = globalVideoList[this.curIndex]
- }
- if (FileUtil.accessSync(this.favPath)) {
- this.facList = FileUtil.listFileSync(this.favPath)
- this.isFac = Utility.getIsFac(this.facList, item)
- }
- this.videoUrl = this.currentSong.filePath
- this.name = this.currentSong.name
- this.cover = this.currentSong.pixelMapPath
- this.startPlayOrResumePlay()
- break;
- }
- }
- @Builder
- PlayController() {
- Column() {
- Line().width('100%').height(1).backgroundColor($r('app.color.index_background'))
- .visibility(this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
- Row() {
- Row() {
- RotatingCover({ songLabel: this.currentSong?.pixelMapPath })
- Column() {
- Text(this.currentSong?.name)
- .fontSize(13)
- .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
- .maxLines(1)
- .fontColor($r('app.color.text_color'))
- .fontWeight(500)
- Row() {
- Text(this.currentSong?.artist)
- .margin({ top: 2 })
- .fontSize(11)
- .fontColor($r('app.color.text_color'))
- }
- }
- .alignItems(HorizontalAlign.Start)
- .margin({ right: 22 })
- }
- .layoutWeight(1)
- .onClick(() => {
- if (ArrayUtil.isNotEmpty(this.songList)) {
- this.isShowPlay = true;
- let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
- this.initLyric(lyricPath);
- if (FileUtil.accessSync(this.favPath)) {
- this.facList = FileUtil.listFileSync(this.favPath)
- this.isFac = this.currentPath === this.favPath ? true : Utility.getIsFac(this.facList, this.currentSong)
- }
- } else {
- ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
- }
- })
- Row() {
- Image($r('app.media.hm_previous'))
- .height(24)
- .width(24)
- .margin({ left: 8, right: 16 })
- .displayPriority(2)
- .onClick(() => {
- if (ArrayUtil.isNotEmpty(this.songList)) {
- this.playPrevious()
- } else {
- ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
- }
- })
- //播放进度条
- Stack() {
- Progress({
- value: Math.floor(this.progressValue),
- type: ProgressType.Ring,
- })
- .color($r('app.color.title_bar_bg'))// 进度条前景色为灰色
- .backgroundColor(Color.Pink)
- .height(36)
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ? $r('app.media.hm_pause') : $r('app.media.hm_play2'))
- .height(32)
- .width(32)
- .displayPriority(3)
- .onClick(() => {
- if (ArrayUtil.isNotEmpty(this.songList)) {
- this.playOrPause()
- } else {
- ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
- }
- })
- }
- Image($r('app.media.hm_next'))
- .height(24)
- .width(24)
- .margin({
- right: 16,
- left: 16
- })
- .displayPriority(2)
- .onClick(() => {
- if (ArrayUtil.isNotEmpty(this.songList)) {
- this.playNext()
- } else {
- ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
- }
- })
- Image($r('app.media.hm_playlist'))
- .height(24)
- .width(24)
- .displayPriority(1)
- .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
- height: '95%',
- dragBar: true,
- showClose: true,
- blurStyle: BlurStyle.Thin,
- preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
- backgroundColor: Color.Transparent,
- title: {
- title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
- + `(${this.songList.length}首)`
- }
- })
- .onClick(() => {
- if (ArrayUtil.isNotEmpty(this.songList)) {
- this.isShowSheet = !this.isShowSheet;
- this.isFrontWhite = false
- } else {
- ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
- }
- })
- }
- }
- .width('100%')
- .height(this.bottomBarHeight)
- .justifyContent(FlexAlign.Center)
- .hitTestBehavior(HitTestMode.Transparent)
- .backgroundColor(this.isCustomizeBg?Color.Transparent:$r('app.color.bottom_control_background'))
- .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
- // modalTransition: ModalTransition.DEFAULT,
- transition: AnimationHelper.transitionInDown(666),
- backgroundColor: 'rgba(0, 0, 0, 0.9)',
- })
- .padding({
- left: 16,
- right: 16
- })
- Line().width('100%').height(25).backgroundColor($r('app.color.bottom_control_background'))
- .visibility(this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
- }
- }
- @State isFrontWhite: boolean = false
- //播放列表布局
- @Builder
- PlayListSheet() {
- Column() {
- this.PlayList()
- }
- .width('100%')
- .height('100%')
- }
- @State titleStr: string = ''
- @State ablumStr: string = ''
- @State artistStr: string = ''
- @State lyricConStr: string = ''
- @State currentEditItem: string = ''
- doUpdateData() {
- setTimeout(() => {
- if (this.modeType === 0) {
- this.deleteCache(this.currentPath)
- this.getSortedFiles(this.currentPath)
- }
- workerInstance.postMessage({ code: 2, data: this.context });
- workerInstance.postMessage({ code: 3, data: this.context });
- workerInstance.postMessage({ code: 4, data: this.context });
- }, 999)
- }
- //编辑信息
- doEdit() {
- if (!this.currentSong) {
- return
- }
- if (StrUtil.isEmpty(this.titleStr)) {
- ToastUtil.showToast('标题不能为空')
- return
- }
- this.table.updateMediaInfo(this.videoUrl, this.titleStr, this.artistStr, this.ablumStr,
- (success: boolean, error?: string) => {
- this.isShowEdit = false
- if (success) {
- console.log(" onecold 编辑信息成功,数据库已同步");
- ToastUtil.showToast('保存成功')
- this.isShowMoreView = false
- this.name = this.titleStr
- if (this.currentSong) {
- this.currentSong.name = this.titleStr
- this.currentSong.artist = this.artistStr
- this.currentSong.album = this.ablumStr
- }
- this.doUpdateData()
- } else {
- ToastUtil.showToast('保存失败' + error?.toString())
- console.error(" onecold 编辑信息数据库失败原因: " + error);
- }
- });
- if (this.lyricConStr !== this.lyricContent) {
- let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
- let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
- let isJiaMi = false;
- let realLyricPath = lyricPath
- if (FileUtil.accessSync(jiaMilyricPath)) {
- isJiaMi = true
- realLyricPath = jiaMilyricPath
- console.info("onecold doEdit找到加密本地歌词 ");
- } else {
- isJiaMi = false
- realLyricPath = lyricPath
- console.info("onecold doEdit本地歌词 ");
- }
- this.saveDataToFile(this.lyricConStr, realLyricPath, isJiaMi)
- }
- }
- @Builder
- editSheet() {
- Scroll() {
- Column() {
- this.editDetail()
- }
- }
- .width('100%')
- .height('100%')
- }
- @Builder
- editDetail() {
- Column() {
- if (this.currentSong) {
- Row() {
- Stack() {
- Image(StrUtil.isEmpty(this.currentSong.pixelMapPath) ? $r('app.media.music_red') :
- this.currentSong.pixelMapPath)
- .height(33)
- .width(33)
- .borderRadius('100%')
- .clip(true)
- .opacity(this.opacityItem)// 绑定透明度
- .margin({ left: 20 })
- }
- .width('15%')
- Row() {
- Column() {
- Text(this.currentSong.name)
- .fontSize(14)
- .maxLines(1)
- .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
- .animation({
- duration: 555,
- curve: 'Linear',
- })
- .fontColor($r('app.color.title_bar_bg'))
- .margin({ left: 10 })
- Row() {
- Text(this.currentSong.artist)
- .fontSize(11)
- .maxLines(1)
- .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
- .padding({ top: 8 })
- .fontColor($r('app.color.title_bar_bg'))
- .margin({ left: 10 })
- }
- }
- .height('100%')
- .width(100)
- .visibility(this.isDarkMode?Visibility.None:Visibility.Visible)
- .justifyContent(FlexAlign.Center)
- .alignItems(HorizontalAlign.Start)
- Button('本地封面')
- .fontColor(Color.White)
- .fontSize(12)
- .height(38)
- .width(88)
- .backgroundColor($r('app.color.title_bar_bg'))
- .stateEffect(true)
- .margin({ right: 5, left: 12 })
- .onClick(async () => {
- this.goSelectImage()
- })
- Button('获取封面')
- .fontColor(Color.White)
- .fontSize(12)
- .height(38)
- .width(88)
- .backgroundColor($r('app.color.title_bar_bg'))
- .stateEffect(true)
- .margin({ right: 12, left: 5 })
- .onClick(async () => {
- if (this.currentSong !== undefined) {
- let artist = this.currentSong?.artist
- if (StrUtil.isEmpty(artist) || artist === undefined) {
- artist = ''
- }
- this.searchCover(this.name, artist)
- }
- })
- }
- .height('100%')
- .justifyContent(FlexAlign.Start)
- .layoutWeight(1)
- }
- .width('100%')
- .height(58)
- Row() {
- Text('标题:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- TextInput({ text: this.currentSong?.name ? this.currentSong.name : '' })
- .height(40)
- .maxLines(1)
- .fontSize(14)
- .layoutWeight(1)
- .fontColor($r('app.color.text_color'))
- .margin({ right: 20, left: 10 })
- .onChange((val: string) => {
- this.titleStr = val
- })
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('艺术家:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- TextInput({ text: this.currentSong?.artist ? this.currentSong.artist : '' })
- .height(40)
- .maxLines(1)
- .fontSize(14)
- .layoutWeight(1)
- .fontColor($r('app.color.text_color'))
- .margin({ right: 20, left: 10 })
- .onChange((val: string) => {
- this.artistStr = val
- })
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('专辑名:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- TextInput({ text: this.currentSong?.album ? this.currentSong.album : '' })
- .height(40)
- .maxLines(1)
- .fontSize(14)
- .layoutWeight(1)
- .fontColor($r('app.color.text_color'))
- .margin({ right: 20, left: 10 })
- .onChange((val: string) => {
- this.ablumStr = val
- })
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('歌词:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- TextArea({ text: this.lyricContent ? this.lyricContent : '' })
- .type(TextAreaType.NORMAL)
- .height(275)
- .fontSize(14)
- .layoutWeight(1)
- .fontColor($r('app.color.text_color'))
- .margin({ right: 20, left: 10 })
- .onChange((val: string) => {
- this.lyricConStr = val
- })
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Button('保存')
- .fontColor(Color.White)
- .layoutWeight(1)
- .height(50)
- .width(100)
- .backgroundColor($r('app.color.title_bar_bg'))
- .stateEffect(true)
- .margin({ right: 20, bottom: 20 })
- .onClick(async () => {
- this.doEdit()
- })
- Button('取消')
- .fontColor(Color.White)
- .layoutWeight(1)
- .height(50)
- .width(100)
- .backgroundColor($r('app.color.title_bar_bg'))
- .stateEffect(true)
- .margin({ left: 20, bottom: 20 })
- .onClick(async () => {
- this.isShowEdit = false
- })
- }
- .margin({
- left: 38,
- right: 38,
- top: 10,
- bottom: 10
- })
- .width(250)
- .height(60)
- }
- }
- .margin({ bottom: 20 })
- }
- @Builder
- detailSheet() {
- Scroll() {
- Column() {
- this.songDetail()
- }
- }
- .width('100%')
- .height('100%')
- }
- @Builder
- songDetail() {
- Column() {
- if (this.currentSong) {
- Row() {
- Stack() {
- Image(StrUtil.isEmpty(this.currentSong.pixelMapPath) ? $r('app.media.music_red') :
- this.currentSong.pixelMapPath)
- .height(33)
- .width(33)
- .borderRadius('100%')
- .clip(true)
- .opacity(this.opacityItem)// 绑定透明度
- .margin({ left: 20 })
- }
- .width('15%')
- Column() {
- Column() {
- Text(this.currentSong.name)
- .fontSize(14)
- .maxLines(1)
- .animation({
- duration: 555,
- curve: 'Linear',
- })
- .fontColor($r('app.color.text_color'))
- .margin({ left: 10 })
- Row() {
- Text(StrUtil.isEmpty(this.currentSong.artist) ? this.currentSong.cTime :
- this.currentSong.artist + ' ' + this.currentSong?.album)
- .fontSize(11)
- .padding({ top: 8 })
- .fontColor($r('app.color.text_color'))
- .margin({ left: 10 })
- }
- }
- .height('100%')
- .width('100%')
- .justifyContent(FlexAlign.Center)
- .alignItems(HorizontalAlign.Start)
- }
- .height('100%')
- }
- .width('100%')
- .height(58)
- .justifyContent(FlexAlign.SpaceBetween)
- Row() {
- Text('歌手名:')
- .fontSize(14)
- .fontColor(Color.White)
- .margin({ left: 22 })
- Text(this.currentSong?.artist ? this.currentSong.artist : '未知歌手')
- .fontSize(14)
- .fontColor(Color.White)
- .margin({ left: 10 })
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('专辑名:')
- .fontSize(14)
- .fontColor(Color.White)
- .margin({ left: 22 })
- Text(this.currentSong?.album ? this.currentSong.album : '未知专辑')
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor(Color.White)
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('文件大小:')
- .fontSize(14)
- .fontColor(Color.White)
- .margin({ left: 22 })
- Text(this.currentSong.size)
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor(Color.White)
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('文件名:')
- .fontSize(14)
- .fontColor(Color.White)
- .margin({ left: 22 })
- Text(this.currentSong.fileName)
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor(Color.White)
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('修改时间:')
- .fontSize(14)
- .fontColor(Color.White)
- .margin({ left: 22 })
- Text(this.currentSong.cTime)
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor(Color.White)
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('存放目录:')
- .fontSize(14)
- .fontColor(Color.White)
- .margin({ left: 22 })
- Text(this.currentSong.filePath)
- .fontSize(12)
- .margin({ left: 10 })
- .fontColor(Color.White)
- .layoutWeight(1)
- }
- .margin({ top: 10, bottom: 10 })
- .width('100%')
- .justifyContent(FlexAlign.Start)
- }
- }
- .margin({ bottom: 20 })
- }
- //定时关闭布局
- @Builder
- TimeCloseSheet() {
- Scroll() {
- Column() {
- this.TimeClose()
- }
- }
- .width('100%')
- .height('100%')
- }
- //倒计时关闭音乐,退出App功能实现。
- @State selectedMinutes: number = 0 // 0表示未开启
- @State remainingSeconds: number = 0
- @State isCustomSuccess: boolean = false //设置自定义成功
- // 预设时间选项
- private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
- private formatTime(seconds: number): string {
- const mins = Math.floor(seconds / 60)
- const secs = seconds % 60
- return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
- }
- // 开始倒计时
- private handleTimeSelect(minutes: number) {
- if (minutes === this.selectedMinutes) {
- this.stopCountdown();
- this.selectedMinutes = 0;
- return;
- }
- this.selectedMinutes = minutes;
- this.remainingSeconds = minutes * 60;
- this.startCountdown(); // 新增调用
- }
- @Builder
- TimeClose() {
- Column() {
- // 倒计时显示区域
- Text(this.selectedMinutes > 0 ?
- `剩余时间:${this.formatTime(this.remainingSeconds)}` :
- "定时关闭未开启")
- .fontSize(17)
- .fontColor($r('app.color.text_color'))
- .margin({ top: 2 });
- Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
- ForEach(this.presetTimes, (minutes: number) => {
- // 单行时间选项容器
- Row() {
- // 文字描述区域
- Text(this.getDisplayText(minutes))
- .fontSize(15)
- .fontColor(minutes === this.selectedMinutes ? $r('app.color.title_bar_bg') :
- $r('app.color.text_color'))// 选中态颜色变化
- .textAlign(TextAlign.Start)
- .layoutWeight(1); // 占据剩余空间
- // 复选框区域
- Checkbox()
- .select(minutes === this.selectedMinutes ? true : minutes === -1 ? this.isCustomSuccess : false)// 绑定选中状态
- .selectedColor($r('app.color.title_bar_bg'))// 主题色
- .shape(CheckBoxShape.CIRCLE)
- .size({ width: 24, height: 24 })
- .margin({ left: 20 })
- }
- .width('100%')
- .padding(10)
- .backgroundColor(minutes === this.selectedMinutes ?$r('app.color.timeColor_bg') :$r('app.color.bottom_control_background')) // 选中背景高亮
- .borderRadius(12)
- .margin({ bottom: 6 })
- .onClick(() => this.handleSelect(minutes)); // 确保点击触发选择
- });
- }
- .width('100%')
- .padding(16)
- }
- // .width('100%')
- // .height('100%')
- }
- // 获取显示文本
- private getDisplayText(minutes: number): string {
- if (minutes === -1) {
- return Utility.resourceToString(getContext(this), $r('app.string.customize'));
- }
- return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
- `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
- }
- // 处理选择事件
- private handleSelect(minutes: number): void {
- if (minutes === -1) { // 自定义
- // 弹出自定义时间对话框
- DialogHelper.showTextInputDialog({
- title: '自定义时间',
- maskColor: Color.Transparent,
- inputType: InputType.Number,
- text: '',
- onChange: (text) => {
- console.error("onChange: " + text);
- },
- onAction: (action, dialogId, content) => {
- if (action == DialogAction.TWO) {
- this.handleTimeSelect(Number(content)); // 改为调用统一方法
- this.isCustomSuccess = true
- ToastUtil.showToast("设置成功," + this.selectedMinutes + "分钟后定时关闭");
- }
- }
- });
- } else {
- this.isCustomSuccess = false
- this.handleTimeSelect(minutes); // 统一调用选择处理方法
- }
- }
- // 添加定时器引用
- private timerId: number = -1;
- // 启动/重置倒计时
- private startCountdown() {
- // 清除旧定时器
- if (this.timerId !== -1) {
- clearInterval(this.timerId);
- }
- // 创建新定时器
- if (this.selectedMinutes > 0) {
- this.timerId = setInterval(() => {
- if (this.remainingSeconds === 15) {
- this.showConfirmationDialog();
- }
- if (this.remainingSeconds > 0) {
- this.remainingSeconds -= 1;
- } else {
- this.stopCountdown();
- this.handleTimeout();
- }
- }, 1000);
- }
- }
- // 15倒计时后再次提示显示确认是否关闭App对话框
- private showConfirmationDialog() {
- DialogHelper.showAlertDialog({
- backgroundColor: $r('app.color.btn_green'),
- title: '确认关闭',
- maskColor: Color.Transparent,
- content: "马上到达定时关闭时间,您是否确定要退出应用?",
- borderStyle: BorderStyle.Dashed,
- primaryButton: '暂不关闭',
- secondaryButton: '确定',
- onAction: (action) => {
- if (action == DialogAction.ONE) { //暂不关闭,取消定时
- this.stopCountdown();
- this.selectedMinutes = 0
- } else if (action == DialogAction.TWO) {
- }
- }
- })
- }
- // 停止倒计时
- private stopCountdown() {
- if (this.timerId !== -1) {
- clearInterval(this.timerId);
- this.timerId = -1;
- }
- }
- // 超时处理
- private handleTimeout() {
- // 执行播放器关闭逻辑
- this.selectedMinutes = 0;
- this.isCustomSuccess = false;
- ToastUtil.showToast(" 定时关闭已完成");
- this.stop(); // 假设存在的播放器实例
- //退出APP
- const mContext = getContext(this) as common.UIAbilityContext
- mContext.terminateSelf();
- AvSessionController.getInstance(true).unregisterSessionListener()
- }
- //倒计时关闭音乐,退出App功能实现结束。
- //播放列表的拖动List 重新排序
- @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
- //左滑操作 移动文件 重命名 删除等操作
- @Builder
- sonButton(item: VideoItem, index: number, filePath: string) {
- Row() {
- //加入下一首播放
- Button() {
- Image($r('app.media.next_to_play'))
- .fillColor(Color.White)
- .width(20)
- }
- .width(40)
- .height(40)
- .type(ButtonType.Circle)
- .backgroundColor($r('app.color.title_bar_bg'))
- .margin(5)
- .onClick(() => {
- this.addToNextPlay(item);
- })
- Button() {
- Image($r('app.media.ic_close'))
- .fillColor(Color.White)
- .width(13)
- }
- .width(40)
- .height(40)
- .type(ButtonType.Circle)
- .backgroundColor($r('app.color.title_bar_bg'))
- .margin(5)
- .onClick(() => {
- this.songList.splice(Number(index), 1)
- this.sonDataSource.pushArrayData(this.songList)
- })
- Button() {
- Image($r('app.media.share2'))
- .fillColor(Color.White)
- .width(20)
- }
- .width(40)
- .height(40)
- .type(ButtonType.Circle)
- .backgroundColor($r('app.color.title_bar_bg'))
- .margin(5)
- .onClick(() => {
- Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
- })
- }
- }
- itemMoveSon(index: number, newIndex: number): void {
- if (newIndex < 0 || newIndex >= this.songList.length) {
- return;
- }
- let tmp = this.songList.splice(index, 1);
- this.songList.splice(newIndex, 0, tmp[0]);
- this.sonDataSource.pushArrayData(this.songList)
- this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
- }
- @Builder
- PlayList() {
- List() {
- LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
- ListItem() {
- this.MusicItemSon(item, index)
- }
- .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
- .animation({
- duration: 666,
- curve: 'ease-in-out' // 可选动画曲线
- })
- //拖动List关键代码开始
- .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
- .zIndex(this.dragItem === index ? 1 : 0)
- .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
- .gesture(
- GestureGroup(GestureMode.Sequence,
- LongPressGesture({ repeat: true })
- .onAction((event?: GestureEvent) => {
- animateTo({ curve: Curve.Friction, duration: 300 }, () => {
- this.scaleItem = index
- })
- })
- .onActionEnd(() => {
- animateTo({ curve: Curve.Friction, duration: 300 }, () => {
- this.scaleItem = -1
- })
- }),
- PanGesture({ fingers: 1, direction: null, distance: 0 })
- .onActionStart(() => {
- this.dragItem = index // 记录当前拖动项索引
- this.dragRefOffset = 0 // 重置偏移基准
- })
- .onActionUpdate((event: GestureEvent) => {
- this.offsetY = event.offsetY - this.dragRefOffset;
- this.neighborItem = -1;
- let indexA = this.songList.indexOf(item);
- // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
- let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
- let value: number = 0;
- if (this.offsetY < 0) {
- value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
- this.neighborItem = indexA - 1;
- this.neighborScale = 1 - value / 20;
- } else if (this.offsetY > 0) {
- value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
- this.neighborItem = indexA + 1;
- this.neighborScale = 1 - value / 20;
- }
- if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
- animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
- this.offsetY -= this.ITEM_INTV;
- this.dragRefOffset += this.ITEM_INTV;
- this.itemMoveSon(indexA, indexA + 1);
- });
- } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
- animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
- this.offsetY += this.ITEM_INTV;
- this.dragRefOffset -= this.ITEM_INTV;
- this.itemMoveSon(indexA, indexA - 1);
- });
- }
- })
- .onActionEnd((event: GestureEvent) => {
- animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
- this.dragItem = -1
- this.neighborItem = -1
- })
- animateTo({
- curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
- }, () => {
- this.scaleItem = -1
- })
- })
- )
- .onCancel(() => {
- animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
- this.dragItem = -1
- this.neighborItem = -1
- })
- animateTo({
- curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
- }, () => {
- this.scaleItem = -1
- })
- })
- ) //拖动List关键代码结束
- .onClick(() => {
- this.doPlay(item, index, true)
- })
- }, (item: VideoItem) => item.filePath)
- }
- .width('100%')
- .height('100%')
- .cachedCount(10)
- .padding({
- bottom: 0
- })
- }
- @Builder
- private MusicItemSon(item: VideoItem, index?: number) {
- Row() {
- Stack() {
- Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
- .height(33)
- .width(33)
- .alt($r('app.media.music_red'))
- .borderRadius('100%')
- .clip(true)
- .margin({ left: 20 })
- }
- .width('15%')
- Column() {
- Column() {
- Text(item.name)
- .fontSize(14)
- .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
- this.isFrontWhite ? Color.White : $r('app.color.text_color'))
- .maxLines(1)
- .margin({ left: 10 })
- Row() {
- Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
- .fontSize(11)
- .padding({ top: 8 })
- .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
- this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
- .margin({ left: 10 })
- Blank()
- Text(item.size)
- .fontSize(11)
- .padding({ top: 8 })
- .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
- .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
- this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
- .margin({ left: 10 })
- }
- }
- .height('100%')
- .width('100%')
- .justifyContent(FlexAlign.Center)
- .alignItems(HorizontalAlign.Start)
- }
- .height('100%')
- .width('65%')
- Column() {
- ImageAnimator()
- .images(this.imagesF)// 动画数组
- .duration(1000)// 持续
- .state(this.animationState)// 动画状态
- .fillMode(FillMode.Forwards)
- .width(18)
- .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
- Visibility.None)
- .height(18)
- .iterations(-1) // 播放次数
- }
- .width('20%')
- }
- .width('100%')
- .height(58)
- .justifyContent(FlexAlign.SpaceBetween)
- .shadow(this.scaleItem === index ? {
- radius: 70,
- color: '#15000000',
- offsetX: 0,
- offsetY: 0
- } :
- {
- radius: 0,
- color: '#15000000',
- offsetX: 0,
- offsetY: 0
- })
- .animation({ curve: Curve.Sharp, duration: 300 })
- }
- @Builder
- MusicPlayBuilder() {
- Column() {
- this.IjkMusicPlayerView()
- }
- .height('100%')
- .width('100%')
- .onDisAppear(() => {
- this.translateY = 0;
- })
- .translate({ y: this.translateY })
- .gesture(
- PanGesture(this.panOption)
- .onActionUpdate((event?: GestureEvent) => {
- if (event) {
- this.translateY = event.offsetY;
- if (this.translateY < 0) {
- this.translateY = 0;
- return;
- }
- }
- })
- .onActionEnd(() => {
- if (this.translateY > this.windowHeight / 2) {
- this.isShowPlay = false;
- } else {
- this.getUIContext().animateTo({
- duration: 300,
- curve: Curve.Smooth
- }, () => {
- this.translateY = 0;
- })
- }
- })
- )
- }
- @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
- @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
- HeightBreakpoint.HEIGHT_LG;
- @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
- @State topBarHeight: number = 50
- @State barOpacity: number = 1
- private hideDone: boolean = false;
- @State currentYOffset: number = 0;
- @State bottomBarHeight: number = 55;
- private isHiding: boolean = false;
- //是否是Pura X外屏,或者小屏幕
- isPuraWP() {
- return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
- && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
- }
- isCoverOpacity() {
- if (this.isPuraWP()) {
- return true
- }
- if (this.isPhoneLan()) {
- return true
- }
- if (deviceInfo.marketName.includes('Pura X')
- && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
- return true
- }
- return false
- }
- //是不是手机横屏
- isPhoneLan() {
- if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
- && this.currentBreakpoint !== BreakpointTypeEnum.SM) {
- if (DisplayUtil.getFoldStatus() === 0 || DisplayUtil.getFoldStatus() === 2) {
- return true
- }
- }
- return false
- }
- @Builder
- IjkMusicPlayerView() {
- Column() {
- // Stack({ alignContent: Alignment.Center }) {
- //
- //
- //
- // Image($r('app.media.icon_load'))
- // .objectFit(ImageFit.Auto)
- // .width('120px')
- // .height('120px')
- // .visibility(this.loadingVisible)
- // .border({ width: 0 })
- // .borderStyle(BorderStyle.Dashed)
- //
- //
- // }
- Column() {
- Column() {
- //播放标题
- Column() {
- this.PlayTitle()
- }
- .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
- .width('100%')
- .margin({ top: 0 })
- .height(PlayConstants.HEIGHT)
- .visibility(Visibility.None)
- // .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM
- // ?Visibility.Visible:Visibility.Visible)
- Swiper() {
- this.CoverInfo()
- this.PlayerLyrics()
- }
- .indicator(false)
- // .indicator(this.currentBreakpoint === BreakpointTypeEnum.SM ?
- // new DotIndicator()
- // .top(this.isCoverOpacity()?0:10)
- //
- // .selectedColor($r('app.color.select_swiper'))
- // .color($r('app.color.slider_track')):false
- // )
- .displayCount(new BreakpointType({
- sm: 1,
- md: 2,
- lg: 2,
- xl: 2,
- xxl: 2
- }).getValue(this.currentBreakpoint))
- .clip(false)
- .loop(false)
- .autoPlay(false)
- // .interval(8000)
- .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
- .height('100%')
- .hitTestBehavior(HitTestMode.Transparent)
- Image($r('app.media.icon_replay'))
- .objectFit(ImageFit.Auto)
- .width('120px')
- .height('120px')
- .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
- .border({ width: 0 })
- .visibility(Visibility.None)
- .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
- .onClick(() => {
- this.startPlayOrResumePlay();
- })
- }
- .width(CommonConstants.FULL_PERCENT)
- .height(CommonConstants.FULL_PERCENT)
- .justifyContent(FlexAlign.End)
- }
- .justifyContent(FlexAlign.End)
- .margin({ bottom: 8 })
- }
- .backgroundImage(this.imageLabelBg)
- .backgroundImageSize({ height: '150%', width: '100%' })
- // .height('100%')
- // .width('100%')
- // .backgroundColor(this.imageColor)
- // .backgroundBlurStyle(BlurStyle.BACKGROUND_REGULAR)
- .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
- .hitTestBehavior(HitTestMode.Transparent)
- .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
- }
- @State progressValue: number = 0;
- @State currentTime: string = "00:00";
- @State totalTime: string = "00:00";
- @State loadingVisible: Visibility = Visibility.None;
- @State replayVisible: Visibility = Visibility.None;
- @State slideEnable: boolean = false;
- @State aspRatio: number = 0.5;
- @State mContext: object | undefined = undefined;
- // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
- @State mFirst: boolean = true;
- @State mDestroyPage: boolean = false;
- @State playSpeed: number = 1;
- @State oldSeconds: number = 0;
- @State isSeekTo: boolean = false;
- @State isCurrentTime: boolean = false;
- @State videoWidth: string = '100%';
- @State videoHeight: string = '100%';
- @State initAspectRatio: number = 1;
- @State videoAspectRatio: number = this.initAspectRatio;
- private videoUrl: string = '';
- private last: number = 0;
- @State videoParentAspectRatio: number = this.initAspectRatio;
- private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
- @State CONTROL_PlayStatus: number = PlayStatus.INIT;
- @State PROGRESS_MAX_VALUE: number = 100;
- @State updateProgressTimer: number = 0;
- @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
- @State name: string = '';
- // @State loop: boolean = false;
- @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
- @State isLandscape: boolean = false;
- @State multiple: string = '1.0X';
- xcomponentController: XComponentController = new XComponentController()
- private panOptionBright: PanGestureOptions =
- new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
- private panOptionVolume: PanGestureOptions =
- new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
- private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
- //手势的音量控制和亮度控制
- private positionX: number = PlayConstants.POSITION_X;
- private positionY: number = PlayConstants.POSITION_Y;
- private windowClass: window.Window = globalThis.windowClass
- @State volume: number = 0.5;
- @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
- @State bright: number = PlayConstants.BRIGHT;
- @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
- @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
- // @State screenHeight:number = 0
- @State screenWidth: number = 0
- @State screenHeight: number = 0
- @State statusBarHeight: number = 0
- @State isYesFull: boolean = false
- private seekValue: number = 0
- @State isVideoLock: boolean = false; // Whether the video playback is locked
- eventHub = getContext().eventHub;
- //投播组件
- private avSessionController: AvSessionController = AvSessionController.getInstance(false);
- private castController: avSession.AVCastController | undefined = undefined;
- @State isCastPlaying: boolean = false;
- @State currentTime2: number = 0;
- @State currentStringTime: string = '00:00';
- @State duration: number = 0;
- @State isReady: boolean = false;
- @State durationTime: number = 0;
- @State durationStringTime: string = '00:00';
- @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
- // @State isPlaying: boolean = false;
- private castSeek: boolean = false;
- private castItem: avSession.AVQueueItem | undefined = undefined;
- // @State isBgPlayOpen:boolean = true //是否启用后台播放
- @State imageLabel: PixelMap | Resource = CommonConstants.musicBgList[0];
- @State imageLabelBg: PixelMap | Resource = CommonConstants.musicBgList[0];
- @State rotateAngle2: number = 0
- @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
- @State cover: string | undefined = '';
- @State artist: string | undefined = ''
- // 1.初始化controller
- private lyricController: LyricController = new LyricController()
- private parser = new LyricParser()
- @State randomColor: string = 'rgb(0,0,0)'
- @State randomShakenX: number = 0
- @State randomShakenY: number = 0
- @State lyricTextSize: number = 24
- @State lyricContent: string = ''
- @State isDebug: boolean = DEBUG
- /**
- * 初始化歌词加载与展示逻辑
- * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
- * @param isToast 是否弹出Toast提示(可选)获取在线歌词为true
- * @param isApi2 是否使用API2获取歌词(可选)
- *
- * 主要流程:
- * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
- * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
- * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
- * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
- * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
- * 6. 解析失败或读取失败时,清空歌词显示。
- *
- * 注意事项:
- * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
- * - 支持加密歌词文件(.lrcc),自动检测并解密。
- * - 歌词内容解析后通过lyricController驱动UI渲染。
- */
- async initLyric(lyricPath: string, isToast?: boolean, isApi2?: boolean) {
- if (StrUtil.isEmpty(lyricPath)) {
- return
- }
- this.lyricContent = ''
- this.lyricController
- .setTextSize(this.currentLyricSize)
- .setCacheSize(4)
- .setTextColor("#DDDDDD")
- .setHighlightColor("#FFFFFF")// .setLineSpace(18)
- .setEmptyHint("")
- .setAnimationDuration(1000)
- this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
- this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 2)
- this.setBlurDegree(this.blurDegree)
- this.setLyricAlignMode(this.currentLyricAlignMode)
- this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18))
- this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23))
- this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 52))
- this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'))
- this.showSingleLyric = false
- this.timeOffset = 0
- this.lyricController.setLyric(null)
- let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
- LogUtil.debug("onecold lyricPath =" + lyricPath)
- const neiqianLrc = LrcParser.getLyrics(this.videoUrl); //获取内嵌歌词
- if (StrUtil.isNotEmpty(neiqianLrc) && !isToast) {
- LogUtil.debug("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
- //赋值给this.lyricContent,播控中心才可以显示歌词
- this.lyricContent = neiqianLrc
- // 将文件内容按行分割成字符串数组
- let lines = neiqianLrc.split('\n').map(line => line.trim());
- // 3.解析歌词
- let lyric = this.parser.parse(lines);
- // 4.设置歌词
- this.lyricController.setLyric(lyric);
- return
- }
- if (isToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
- && !Utility.isVideoByExtension(this.videoUrl))) {
- if (this.currentSong !== undefined) {
- // ToastUtil.showShort('正在为你搜索在线歌词!')
- //判断是不是赞助会员,是会员的话才开启歌词功能
- // if (!this.isDebug) {
- // if (!Utility.isNoble()) {
- // LogUtil.debug("onecold 不是赞助会员")
- // return
- // }
- // if(!Utility.isPassInstallTime(33)){
- // LogUtil.debug("onecold not pass time")
- // // LogUtil.debug("onecold 用户安装app没超过12天" )
- // return
- // }
- // }
- let artist = this.currentSong?.artist
- if (artist === undefined) {
- artist = ''
- }
- if (isApi2 === undefined) {
- isApi2 = false
- }
- NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
- // LogUtil.debug("onecold res =" + res)
- if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
- if (StrUtil.isNotEmpty(res)) {
- this.lyricContent = res
- let lines = res.split('\n').map(line => line.trim());
- // 3.解析歌词
- let lyric = this.parser.parse(lines);
- // 4.设置歌词
- this.lyricController.setLyric(lyric);
- this.showSingleLyric = true
- // 4.保存歌词文件lyric到本地
- this.saveDataToFile(res, jiaMilyricPath, true)
- } else {
- this.lyricController.setLyric(null)
- if (isToast) {
- ToastUtil.showShort('未获取到歌词!')
- }
- }
- } else {
- this.lyricController.setLyric(null)
- if (isToast) {
- ToastUtil.showShort('未获取到歌词!')
- }
- }
- })
- } else {
- this.lyricController.setLyric(null)
- if (isToast) {
- ToastUtil.showShort('未获取到歌词!')
- }
- }
- return
- }
- try {
- let isJiaMi = false;
- let realLyricPath = lyricPath
- if (FileUtil.accessSync(jiaMilyricPath)) {
- isJiaMi = true
- realLyricPath = jiaMilyricPath
- console.info("onecold 找到加密本地歌词 ");
- } else {
- isJiaMi = false
- realLyricPath = lyricPath
- console.info("onecold 找到本地歌词 ");
- }
- // 3.读取文件内容并指定编码为 UTF-8
- let file = fs.openSync(realLyricPath, fs.OpenMode.READ_WRITE);
- let arrayBuffer = new ArrayBuffer(4096);
- fs.read(file.fd, arrayBuffer)
- .then((readLen: number) => {
- console.info("read file data succeed");
- // let buf = buffer.from(arrayBuffer, 0, readLen);
- let buf = new Uint8Array(arrayBuffer, 0, readLen);
- // 检查 buf 是否为空
- if (buf.length === 0) {
- throw new Error("Buffer is empty after reading the file");
- }
- try {
- // 检测文件编码
- let detectedEncoding = chardet.detect(buf);
- console.info("Detected encoding: " + detectedEncoding);
- // 使用检测到的编码解码,解决中文乱码问题
- let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
- let fileContent = textDecoder.decode(buf);
- console.info(`onecold The content of file1: ${fileContent}`);
- //解密
- if (isJiaMi) {
- fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
- }
- console.info(`onecold The content of file2: ${fileContent}`);
- this.lyricContent = fileContent
- // 将文件内容按行分割成字符串数组
- let lines = fileContent.split('\n').map(line => line.trim());
- console.info(`onecold The content of file: ${fileContent}`);
- // 3.解析歌词
- let lyric = this.parser.parse(lines);
- // 4.设置歌词
- this.lyricController.setLyric(lyric);
- this.showSingleLyric = true
- console.info(`The content of file: ${fileContent}`);
- } catch (chardetError) {
- console.error("chardet.detect failed with error: " + chardetError.message);
- this.lyricController.setLyric(null);
- }
- })
- .catch((err: BusinessError) => {
- this.lyricController.setLyric(null)
- console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
- })
- .catch((err: Error) => {
- this.lyricController.setLyric(null)
- console.error("read file 2 data failed with error message: " + err.message);
- })
- .finally(() => {
- fs.closeSync(file);
- });
- } catch (error) {
- this.lyricController.setLyric(null)
- Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
- }
- }
- async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
- if (StrUtil.isEmpty(filePath)) {
- return
- }
- try {
- //将content进行加密
- // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
- let lyricContent = ''
- if (isJiaMi) {
- lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
- } else {
- lyricContent = content
- }
- const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
- // 清空文件内容
- await fileIo.truncate(file.fd, 0);
- await fileIo.write(file.fd, lyricContent);
- await fileIo.close(file);
- console.log('onecold lyric file Data saved successfully.');
- } catch (error) {
- console.error('onecold lyric file Failed to save data:', error);
- }
- }
- /**
- * Get largest proportion color of an image.
- */
- getImageColor() {
- if (!this.context) {
- return;
- }
- let bg = Utility.getMusisBg()
- this.imageLabel = bg
- ColorConversion.setSysBarLightBackground(true);
- this.context.resourceManager.getMediaContent(bg)
- .then((value: Uint8Array) => {
- let buffer = value.buffer as ArrayBuffer;
- image.createImageSource(buffer).createPixelMap().then((pixelMap) => {
- effectKit.createColorPicker(pixelMap, (error, colorPicker) => {
- if (error) {
- Logger.error('Failed to create color picker.');
- } else {
- let color = colorPicker.getLargestProportionColor();
- let colorArr = ColorConversion.dealColor(color.red, color.green, color.blue);
- this.imageColor = `rgba(${colorArr[0]}, ${colorArr[1]}, ${colorArr[2]}, 1)`;
- }
- })
- let headFilter = effectKit.createEffect(pixelMap);
- if (headFilter !== null) {
- headFilter.blur(15);
- headFilter.getEffectPixelMap().then((value) => {
- this.imageLabelBg = value;
- })
- }
- })
- .catch((error: BusinessError) => {
- Logger.error(`${error.code} + ${error.message}`)
- })
- })
- .catch((error: BusinessError) => {
- Logger.error(`${error.code} + ${error.message}`)
- })
- }
- setImageColor(cover: string) {
- if (!this.context) {
- return;
- }
- if (cover === undefined) {
- return;
- }
- ImageUtil.imagePathToPixelMap(cover).then((value) => {
- let headFilter = effectKit.createEffect(value);
- if (headFilter !== null) {
- headFilter.blur(15);
- headFilter.getEffectPixelMap().then((value) => {
- this.imageLabelBg = value;
- })
- }
- }).catch((error: BusinessError) => {
- Logger.error(`${error.code} + ${error.message}`)
- })
- }
- setImageColor2(cover: string) {
- if (!this.context) {
- return;
- }
- if (cover === undefined) {
- return;
- }
- LogUtils.getInstance().LOGI("setImageColor2--> cover ==" + cover);
- ImageUtils.getImageDealData(getContext(this), cover, this.videoUrl).then((data) => {
- this.imageColor = data.imageColor;
- if (data.blurPixelMap) {
- this.imageLabelBg = data.blurPixelMap;
- }
- })
- }
- // 定义开始旋转的方法
- // 定时器用于一百毫秒执行一次旋转角度
- @State timer: number = 0
- @State rotateAngle: number = 0
- //封面旋转动画
- animationRoFun() {
- if (this.isPlaying && !this.isCoverRectangle) {
- this.timer = setInterval(() => {
- this.rotateAngle += 1
- }, 100)
- this.startRotation()
- } else {
- clearInterval(this.timer)
- this.stopRotation()
- }
- }
- // 定义开始旋转的方法
- startRotation() {
- if (this.isPlaying) {
- animateTo({
- duration: 777,
- iterations: 1,
- curve: Curve.Linear
- }, () => {
- this.rotateAngle2 = 0
- })
- }
- }
- // 回调,暂停和播放按钮回调,下一首和上一首
- playChange() {
- // if(this.isCoverRectangle){
- // return
- // }
- if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
- this.setIsPlaying(true)
- this.animationState = AnimationStatus.Running
- } else {
- this.setIsPlaying(false)
- this.animationState = AnimationStatus.Paused
- }
- }
- // 定义停止旋转的方法
- stopRotation() {
- if (this.isCoverRectangle) {
- this.rotateAngle = 0
- } else {
- //唱针以左上角为点选择逆时针40度
- animateTo({
- duration: 1000,
- curve: Curve.Linear,
- iterations: 1,
- }, () => {
- this.rotateAngle2 = -40;
- });
- }
- }
- @Builder
- private LyricsTopItem() {
- Row() {
- Stack() {
- Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
- .height(39)
- .width(39)
- .alt(this.imageLabel)
- .borderRadius(8)
- .margin({ left: this.currentLyricAlignMode === 0 ? 25 : -15 })
- }
- .width('15%')
- Column() {
- Column() {
- Text(this.name)
- .fontSize(14)
- .maxLines(1)
- .fontWeight(FontWeight.Bolder)
- .fontColor(this.currentLyricColor)
- .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
- Row() {
- Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
- .fontSize(10)
- .fontWeight(FontWeight.Bold)
- .padding({ top: 8 })
- .fontColor(this.currentLyricColor)
- .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
- Blank()
- }
- }
- .height('100%')
- .width('100%')
- .justifyContent(FlexAlign.Center)
- .alignItems(HorizontalAlign.Start)
- }
- .height('100%')
- .width('65%')
- Column() {
- Image($r('app.media.lyric'))
- .width(25)
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- .margin({ right: 30 })
- .onClick(() => {
- this.isLyricSetting = !this.isLyricSetting;
- })
- .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(), {
- height: this.isCoverOpacity() ? '95%' : '78%',
- dragBar: true,
- showClose: true,
- blurStyle: BlurStyle.Thin,
- backgroundColor: Color.Transparent,
- // title: { title: $r('app.string.lyric_setting') }
- })
- }
- .width('18%')
- }
- .width(this.isLandscape ? '50%' : '82%')
- .height(58)
- .justifyContent(FlexAlign.SpaceBetween)
- }
- //歌词显示
- @Builder
- PlayerLyrics() {
- Column() {
- Column() {
- this.LyricsTopItem()
- }
- .height(this.isPuraWP() ? 15 : 58)
- .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
- Visibility.None : Visibility.Visible)
- .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
- .width("100%")
- Column() {
- LyricView2({
- controller: this.lyricController,
- enableSeek: true,
- seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
- seekLineColor: "#80ffffff", // 滑动定位线颜色
- seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
- onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
- this.isSeekTo = true;
- this.mDestroyPage = false;
- this.showLoadIng();
- // LogUtils.getInstance().LOGI("onecold-->seekValue start:" + position);
- this.seekTo(position + "");
- this.isSeekTo = false;
- return true
- }
- })
- .width("100%")
- .layoutWeight(1)
- .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: 10 })
- }
- .position({
- top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
- (this.isPuraWP() ? 58 : 99)
- })
- .justifyContent(FlexAlign.Center)
- .height(this.isCoverOpacity() ? '95%' : '80%')
- }
- }
- //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
- @Builder
- BottomControl() {
- Column() {
- //播放 暂停,下一首,上一首
- Row() {
- Row({ space: 33 }) {
- //更多功能
- Image($r('app.media.menu'))
- .width(24)
- .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
- height: this.isCoverOpacity() ? '95%' : '93%',
- dragBar: true,
- showClose: true,
- blurStyle: BlurStyle.Thin,
- backgroundColor: Color.Transparent,
- })
- .onClick(() => {
- this.isShowMoreView = !this.isShowMoreView;
- })
- Image($r('app.media.ic_previous'))
- .width(33)
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- .onClick(async () => {
- this.playPrevious()
- })
- }
- .margin({ left: 33 })
- Column() {
- Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
- $r('app.media.ic_public_play') : $r('app.media.ic_public_pause'))
- .width(60)
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- .onClick(async () => {
- this.playOrPause()
- })
- }
- .layoutWeight(1)
- .margin({ left: 20, right: 20 })
- Row({ space: 33 }) {
- Image($r('app.media.ic_next'))
- .width(33)
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- .onClick(() => {
- this.playNext();
- })
- //添加或取消收藏
- Image(Utility.getIsFav(this.favList,this.currentSong)?$r('app.media.add_fac_light'):$r('app.media.add_fac'))
- .width(24)
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- .onClick(async () => {
- if(this.currentSong){
- this.doFav(this.currentSong)
- }
- })
- }
- .margin({ right: 33 })
- }
- .width('100%')
- .margin(10)
- //播放进度条
- Row() {
- Column() {
- if (this.playType === 0) {
- Image($r('app.media.loop'))
- .width($r('app.float.control_image_width'))
- .margin(10)
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- } else if (this.playType === 1) {
- Image($r('app.media.single'))
- .width($r('app.float.control_image_width'))
- .margin(10)
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- } else if (this.playType === 2) {
- Image($r('app.media.normal_play'))
- .width($r('app.float.control_image_width'))
- .margin(10)
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- } else if (this.playType === 3) {
- Image($r('app.media.random'))
- .width($r('app.float.control_image_width'))
- .margin(10)
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- }
- }
- .onClick(async () => {
- this.setLoopMode()
- })
- Text(this.currentTime)
- .fontSize($r('app.float.slider_font_size'))
- .fontColor(Color.White)
- .margin(3)
- Slider({
- value: this.progressValue,
- min: 0,
- max: this.PROGRESS_MAX_VALUE,
- step: 1,
- style: SliderStyle.OutSet
- })
- .width('600px')
- .blockColor(Color.White)
- .trackColor($r('app.color.track_color'))
- .selectedColor(Color.White)
- .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
- .layoutWeight(1)
- .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
- .showSteps(true)
- .showTips(true)
- .enabled(this.slideEnable)
- .onChange((value: number, mode: SliderChangeMode) => {
- // if (mode == 2) {
- this.isSeekTo = true;
- this.mDestroyPage = false;
- this.showLoadIng();
- LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
- let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
- this.seekTo(seekValue + "");
- // this.setProgress()
- LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
- this.isSeekTo = false;
- // }
- })
- Text(this.totalTime)
- .fontSize($r('app.float.slider_font_size'))
- .fontColor(Color.White)
- .margin(3)
- .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
- //播放列表
- Image($r('app.media.playlist'))
- .width($r('app.float.control_image_width'))
- .margin({ right: 10, left: 20 })
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
- height: '95%',
- dragBar: true,
- showClose: true,
- preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
- blurStyle: BlurStyle.Thin,
- backgroundColor: Color.Transparent,
- title: {
- title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
- + `(${this.songList.length}首)`
- }
- })
- .onClick(() => {
- this.isShowSheetView = !this.isShowSheetView;
- this.isFrontWhite = true
- })
- }
- .width(PlayConstants.PROGRESS_ROW_WIDTH)
- // .visibility(this.isHide?Visibility.Hidden:Visibility.Visible)
- }
- .position({ bottom:this.isCoverOpacity()?55: 80 }) // 将 固定在底部
- }
- @State isCoverRectangle: boolean = false
- @Builder
- CoverInfo() {
- Column() {
- // 第一个
- Column({ space: 8 }) {
- Text(this.name)
- .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22)
- .fontWeight(FontWeight.Bold)
- .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
- .maxLines(1)
- .fontColor(Color.White)
- Text(this.artist + ' ' + this.currentSong?.album)
- .fontSize(this.isCoverOpacity() ? 12 : 15)
- .fontColor(Color.White)
- }
- .margin({ top: this.isCoverOpacity() ? 20 : 66 })
- .justifyContent(FlexAlign.Center)
- .zIndex(1)
- .visibility(this.isCoverOpacity() ? Visibility.None : Visibility.Visible)
- Stack() {
- // 唱片旋转效果
- Image($r('app.media.ic_music_disc'))
- .width(250)
- .height(250)
- .margin({ right: 30, left: 30, top: this.isCoverOpacity() || this.isCoverRectangle ? 0 : 10 })
- .aspectRatio(1)
- .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
- .borderRadius('100%')
- .align(Alignment.Center)
- .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
- .rotate({
- angle: this.rotateAngle,
- centerX: "50%",
- centerY: "50%",
- })
- .animation({
- duration: 100,
- curve: Curve.Linear
- })
- .shadow({
- radius: 30,
- color: this.randomColor
- })
- Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
- .height(this.isCoverOpacity() ? 152 : this.isCoverRectangle ? 300 : 162)
- .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
- .alt(this.imageLabel)
- .margin({ right: 30, left: 30, top: this.isCoverOpacity() || this.isCoverRectangle ? 0 : 10 })
- .aspectRatio(1)
- .borderRadius(this.isCoverRectangle ? 20 : '100%')
- .align(Alignment.Center)// .opacity(this.isCoverOpacity()||this.isCoverRectangle?0:1)
- .clip(true)
- .rotate({
- x: 0,
- y: 0,
- z: 1,
- angle: this.rotateAngle
- })
- .onClick(() => {
- this.getImageColor()
- })
- // 唱针以左上角为点选择逆时针40度
- Image($r('app.media.ic_music_cover_hand'))
- .height(130)
- .margin({ bottom: 220, top: 0 })
- .align(Alignment.Top)
- .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
- .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
- Column({ space: 8 }) {
- Text(this.name)
- .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22)
- .fontWeight(FontWeight.Bold)
- .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
- .maxLines(1)
- .fontColor(Color.White)
- Text(this.artist)
- .fontSize(this.isCoverOpacity() ? 12 : 15)
- .fontColor(Color.White)
- }
- .justifyContent(FlexAlign.Start)
- .zIndex(1)
- // .margin({bottom:180})
- .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
- }
- .margin({
- bottom: this.isCoverOpacity() || this.isCoverRectangle ? 160 : 0,
- top: this.isCoverOpacity() ? 0 : this.isCoverRectangle ? 40 : 30
- })
- this.BottomControl()
- }
- .width(CommonConstants.FULL_PERCENT)
- .clip(true)
- }
- @Builder
- private PlayTitle() {
- Row() {
- Row() {
- Image($r('app.media.ic_back_down'))
- .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
- .hitTestBehavior(HitTestMode.Transparent)
- // .visibility(this.isLandscape?Visibility.None:Visibility.Visible)
- Text(this.name + ' ' + this.artist)
- .fontColor(Color.White)
- .fontSize($r('app.float.title_font_size'))
- .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
- .maxLines(1)
- .visibility(Visibility.None)
- .margin({ left: 2, right: 30 })
- }
- .layoutWeight(1)
- .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
- .onClick(() => {
- this.isShowPlay = false;
- })
- // Text(this.multiple)
- // .fontSize(16)
- // .fontColor(Color.White)
- // .margin({ right:15 })
- // .visibility(this.isHide?Visibility.None:Visibility.Visible)
- // .id('xid')
- // .onClick(()=>{
- // this.showMultipleDialog('xid')
- // })
- Column() {
- AVCastPicker({
- normalColor: Color.White,
- onStateChange: this.onStateVastChange
- })
- .width(24)
- .height(24)
- }
- .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
- //更多功能
- // Image( $r('app.media.two_point') )
- // .width(24)
- // .visibility(this.isHide?Visibility.None:Visibility.Visible)
- // .margin({left:13})
- // .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
- // height:this.isCoverOpacity()?'95%':'85%',
- // dragBar: true,
- // showClose: true,
- // blurStyle:BlurStyle.Thin,
- // backgroundColor:Color.Transparent,
- // })
- // .onClick(() => {
- // this.isShowMoreView = !this.isShowMoreView;
- // })
- }
- .width(PlayConstants.ROW_WIDTH)
- }
- @Builder
- lyricSettingSheet() {
- Scroll() {
- this.lyricSetting()
- }
- .width('100%')
- .height('100%')
- }
- @Builder
- lyricSetting() {
- Column() {
- // 时间调节模块
- this.BuildTimeControls()
- // 字号控制模块
- this.BuildFontControls()
- }
- }
- // 歌词时间偏移状态
- @State timeOffset: number = 0.0
- @State currentLyricColor: string = '#FFFFFF'
- // 歌词字号状态
- @State currentLyricSize: number = 20
- // 高亮歌词放大倍数
- @State currentHightLyricSize: number = 1.2
- @State currentLyricLineSpace: number = 52 //{
- @State currentLyricAlignMode: number = 1
- @State blurDegree: number = 2
- // 构建字号控制器
- @Builder
- BuildFontControls() {
- Column() {
- Row() {
- Text(`歌词居中:`)
- .fontSize(14)
- .fontColor(Color.White)
- .margin({ right: 8 })
- Row() {
- ForEach(['居中', '居左'], (size: string, index: number) => {
- Button(size)
- .width(60)
- .height(28)
- .fontSize(12)
- .fontColor(this.currentLyricAlignMode === index ? '#FFFFFF' : '#007DFF')
- .backgroundColor(this.currentLyricAlignMode === index ? '#007DFF' : '#FFFFFF')
- .border({
- color: this.currentLyricAlignMode === index ? '#007DFF' : '#DDDDDD',
- width: 1
- })
- .onClick(() => {
- this.setLyricAlignMode(index)
- })
- .margin({ left: 8, right: 8 })
- })
- }
- .layoutWeight(1)
- Blank()
- }
- .justifyContent(FlexAlign.Start)
- .margin({ top:10,bottom:10,right:20,left:35})
- Row() {
- Text(`歌词颜色:`)
- .fontSize(14)
- .fontColor(Color.White)
- Row({space: 10}) {
- HSBColorPicker({
- color: '#FFFFFF',
- radius: 8,
- layout: HSBColorPickerLayout.COLUMN,
- onChange:(value: string) =>this.changeLyricColor(value)
- })
- .height(88)
- .layoutWeight(1)
- .padding({left:15,right:35})
- }
- }
- .width('76%')
- .margin({ top:10,bottom:10,right:45,left:20})
- Row() {
- Text(`歌词字号:`)
- .fontSize(14)
- .fontColor(Color.White)
- Slider({
- value: this.currentLyricSize,
- min: 12,
- max: 30,
- step: 0.1,
- style: SliderStyle.OutSet
- })
- .blockColor(Color.Red)
- .trackColor($r('app.color.speed_text_color'))
- .selectedColor(Color.White)
- .trackThickness(6)
- .onChange((value: number) => {
- ;
- this.setLyricTextSize(value)
- })
- .width('76%')
- }
- .margin({
- left: 20,
- right: 15,
- top: 5,
- bottom: 5
- })
- Row() {
- Text(`高亮倍数:`)
- .fontSize(14)
- .fontColor(Color.White)
- Slider({
- value: this.currentHightLyricSize,
- min: 1,
- max: 2,
- step: 0.1,
- style: SliderStyle.OutSet
- })
- .blockColor(Color.Red)
- .trackColor($r('app.color.speed_text_color'))
- .selectedColor(Color.White)
- .trackThickness(6)
- .onChange((value: number) => {
- ;
- this.setHighLyricTextSize(value)
- })
- .width('76%')
- }
- .margin({
- left: 20,
- right: 15,
- top: 5,
- bottom: 5
- })
- Row() {
- Text(`歌词间隙:`)
- .fontSize(14)
- .fontColor(Color.White)
- Slider({
- value: this.currentLyricLineSpace,
- min: 15,
- max: 120,
- step: 0.1,
- style: SliderStyle.OutSet
- })
- .blockColor(Color.Red)
- .trackColor($r('app.color.speed_text_color'))
- .selectedColor(Color.White)
- .trackThickness(6)
- .onChange((value: number) => {
- ;
- this.setLyricLineSpace(value)
- })
- .width('76%')
- }
- .margin({
- left: 20,
- right: 15,
- top: 5,
- bottom: 5
- })
- Row() {
- Text(`歌词模糊:`)
- .fontSize(14)
- .fontColor(Color.White)
- Slider({
- value: this.blurDegree,
- min: 0,
- max: 10,
- step: 0.1,
- style: SliderStyle.OutSet
- })
- .blockColor(Color.Red)
- .trackColor($r('app.color.speed_text_color'))
- .selectedColor(Color.White)
- .trackThickness(6)
- .onChange((value: number) => {
- ;
- this.setBlurDegree(value)
- })
- .width('76%')
- }
- .margin({
- left: 20,
- right: 15,
- top: 5,
- bottom: 15
- })
- Row() {
- this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
- // this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
- // this.pushLyricButton($r('app.media.white_search'), 2, '获取歌词')
- }
- .justifyContent(FlexAlign.Center)
- .margin({ top: 3, bottom: 10 })
- }
- }
- private setBlurDegree(index: number) {
- this.blurDegree = index
- this.lyricController.setBlurDegree(this.blurDegree)
- PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
- }
- private setLyricAlignMode(index: number) {
- this.currentLyricAlignMode = index
- // LogUtil.info('onecold this.currentLyricSize = '+this.currentLyricAlignMode)
- if (this.currentLyricAlignMode === 1) {
- this.lyricController.setAlignMode("left")
- } else {
- this.lyricController.setAlignMode("center")
- }
- PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
- }
- private setLyricTextSize(index: number) {
- this.currentLyricSize = index
- this.lyricController.setTextSize(this.currentLyricSize)
- PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
- }
- private setHighLyricTextSize(scale: number) {
- this.currentHightLyricSize = scale
- // LogUtil.info('onecold this.currentHightLyricSize = '+this.currentHightLyricSize)
- this.lyricController
- .setHighlightScale(this.currentHightLyricSize)
- PreferencesUtil.putSync('HighLyricTextSize', scale)
- }
- private setLyricLineSpace(index: number) {
- this.currentLyricLineSpace = index
- this.lyricController.setLineSpace(this.currentLyricLineSpace)
- PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
- }
- private changeLyricColor(color: string) {
- this.currentLyricColor = color
- this.lyricController
- .setTextColor(this.currentLyricColor)
- .setHighlightColor(this.currentLyricColor)
- PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
- }
- // 构建时间控制器
- @Builder
- BuildTimeControls() {
- Column() {
- // 时间显示
- Text(this.getTimeText())
- .fontSize(18)
- .fontColor(Color.White)
- .margin({ bottom: 10 })
- Row() {
- this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
- this.PrecisionTimeButton($r('app.media.loop'), 0, 'RESET')
- this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
- }
- .justifyContent(FlexAlign.Center)
- }
- .margin({ top: 12, bottom: 8 })
- }
- // 精度按钮组件
- @Builder
- PrecisionTimeButton(icon: Resource, step: number, label: string) {
- Column() {
- Image(icon)
- .width(28)
- .margin({ bottom: 5 })
- .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
- Text(label)
- .fontSize(12)
- .fontColor('#FFFFFF')
- }
- .enabled(!this.isButtonDisabled(step))
- .onClick(() => this.handlePrecisionAdjust(step))
- .padding(5)
- .width(60)
- .height(60)
- .margin({ left: 18, right: 18 })
- .border({
- color: '#FFFFFF',
- radius: 20,
- width: 1.8
- })
- }
- private handlePrecisionAdjust(step: number) {
- if (step === 0) {
- this.timeOffset = 0
- return
- }
- // 精度处理:保留1位小数
- const newOffset = Number((this.timeOffset + step).toFixed(5))
- // 边界保护(±15.0秒)
- if (newOffset < -30.0 || newOffset > 30.0) {
- // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
- return
- }
- // 状态更新
- this.timeOffset = newOffset
- }
- // 按钮禁用逻辑
- private isButtonDisabled(step: number): boolean {
- const futureOffset = this.timeOffset + step
- return (futureOffset < -30.0) || (futureOffset > 30.0)
- }
- // 时间显示文本升级
- private getTimeText(): string {
- const absValue = Math.abs(this.timeOffset)
- return this.timeOffset === 0
- ? '歌词时间已重置'
- : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
- }
- // 导入 本地歌词 搜索歌词
- @Builder
- pushLyricButton(icon: Resource, step: number, label: string) {
- Row() {
- Image(icon)
- .width(14)
- .margin({ left: 6 })
- Text(label)
- .fontSize(10)
- .margin({ left: 6 })
- .fontColor('#FFFFFF')
- }
- .visibility(step === 1 ? (Utility.isNoble() ? Visibility.Visible : Visibility.None) : Visibility.Visible)
- .onClick(() => {
- switch (step) {
- case 0:
- this.callFilePickerSelectFileForLyric()
- break;
- case 1:
- //判断是不是赞助会员
- // if(Utility.isNoble()){
- if (StrUtil.isNotEmpty(this.videoUrl)) {
- ToastUtil.showToast('正在获取')
- this.isLyricSetting = false
- let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
- this.initLyric(lyricPath, true);
- }
- // }else{
- // this.isLyricSetting = false
- // this.showVipDialog()
- // }
- break;
- case 2:
- //判断是不是赞助会员
- // if(Utility.isNoble()){
- if (StrUtil.isNotEmpty(this.videoUrl)) {
- ToastUtil.showToast('正在获取')
- this.isLyricSetting = false
- let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
- this.initLyric(lyricPath, true, true);
- }
- // }else{
- // this.isLyricSetting = false
- // this.showVipDialog()
- // }
- break;
- }
- })
- .padding(5)
- .width(90)
- .height(40)
- .margin({ left: 6, right: 6 })
- .border({
- color: '#FFFFFF',
- radius: 20,
- width: 1.8
- })
- }
- showVipDialog() {
- DialogHelper.showCustomContentDialog({
- dialogId: 'vip',
- title: "友情提示",
- autoCancel: false, //点击遮障层时,不关闭弹窗
- backCancel: true, //点击返回键,不关闭弹窗
- contentBuilder: () => {
- this.customVipBuilder("该功能需开通赞助功能,非常感谢您的支持!")
- },
- buttons: [],
- })
- }
- //去赞助的自定义内容
- @Builder
- customVipBuilder(content: string) {
- Column() {
- Text(content)
- .fontColor(Color.Gray)
- .fontSize(16)
- .alignSelf(ItemAlign.Start)
- .margin({ bottom: 15 })
- .fontSize(16)
- Row() {
- Button('取消')
- .fontColor(Color.White)
- .backgroundColor($r('app.color.title_bar_bg'))//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
- .height(50)
- .layoutWeight(1)
- .stateEffect(true)
- .margin({ right: 6 })
- .onClick(() => {
- DialogHelper.closeDialog('vip'); //关闭弹框
- })
- Button('开通')
- .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
- .layoutWeight(1)
- .height(50)
- .backgroundColor($r('app.color.title_bar_bg'))
- .stateEffect(true)
- .margin({ left: 6 })
- .onClick(() => {
- DialogHelper.closeDialog('vip'); //关闭弹框
- this.isShowPlay = false
- router.pushUrl({
- url: 'pages/VipPage'
- }, router.RouterMode.Single);
- })
- }
- }
- .width("100%")
- .padding(10)
- }
- @Builder
- PlayMoreSheet() {
- Column() {
- this.MoreList()
- }
- .width('100%')
- .height('100%')
- }
- @Builder
- MoreList() {
- Scroll() {
- Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
- ForEach(this.moreItems, (more: MoreItem) => {
- Row() {
- if (more.id === 3) {
- Image(more.image)
- .width(24)
- .height(24)
- .margin({ left: 10, right: 10 })
- .onClick(() => {
- this.isShowDetailMore = !this.isShowDetailMore;
- })
- Text(more.title)
- .fontSize(16)
- .fontColor(Color.White)
- .onClick(() => {
- this.doMore(more.id)
- })
- .bindSheet($$this.isShowDetailMore, this.detailSheet(), {
- height: this.isCoverOpacity() ? '95%' : '60%',
- dragBar: true,
- showClose: true,
- blurStyle: BlurStyle.Thin,
- backgroundColor: Color.Transparent,
- title: { title: '歌曲信息' }
- })
- .onClick(() => {
- this.isShowDetailMore = !this.isShowDetailMore;
- })
- } else if (more.id === 15) { //编辑信息
- Image(more.image)
- .width(24)
- .height(24)
- .margin({ left: 10, right: 10 })
- .onClick(() => {
- this.isShowEdit = !this.isShowEdit;
- })
- Text(more.title)
- .fontSize(16)
- .fontColor(Color.White)
- .onClick(() => {
- this.doMore(more.id)
- })
- .bindSheet($$this.isShowEdit, this.editSheet(), {
- height: this.isCoverOpacity() ? '95%' : '88%',
- dragBar: true,
- showClose: true,
- // blurStyle:BlurStyle.Thin,
- // backgroundColor:Color.Transparent,
- title: { title: '编辑信息' }
- })
- .onClick(() => {
- this.isShowEdit = !this.isShowEdit;
- })
- } else if (more.id === 5) { //定时关闭
- Image(more.image)
- .width(24)
- .height(24)
- .margin({ left: 10, right: 10 })
- .onClick(() => {
- this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
- })
- Text(more.title)
- .fontSize(16)
- .fontColor(Color.White)
- .onClick(() => {
- this.doMore(more.id)
- })
- .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
- height: this.isCoverOpacity() ? '95%' : '78%',
- dragBar: true,
- showClose: true,
- title: { title: $r('app.string.time_close') }
- })
- .onClick(() => {
- this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
- })
- } else if (more.id === 2) { //歌词设置
- Image(more.image)
- .width(24)
- .height(24)
- .margin({ left: 10, right: 10 })
- .onClick(() => {
- this.isLyricSetting = !this.isLyricSetting;
- this.isShowMoreView = false
- })
- Text(more.title)
- .fontSize(16)
- .fontColor(Color.White)
- .onClick(() => {
- this.isLyricSetting = !this.isLyricSetting;
- this.isShowMoreView = false
- })
- } else if (more.id === 11) { //跳过头尾
- Image(more.image)
- .width(24)
- .height(24)
- .margin({ left: 10, right: 10 })
- .onClick(() => {
- this.isJumpSetting = !this.isJumpSetting;
- })
- Text(more.title)
- .fontSize(16)
- .fontColor(Color.White)
- .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
- height: this.isCoverOpacity() ? '95%' : '60%',
- dragBar: true,
- showClose: true,
- blurStyle: BlurStyle.Thin,
- backgroundColor: Color.Transparent,
- title: { title: '跳过头尾' }
- })
- .onClick(() => {
- this.isJumpSetting = !this.isJumpSetting;
- })
- } else if (more.id === 12) { //投播
- AVCastPicker({
- customPicker: (): void => this.TPImageBuilder(more),
- onStateChange: (state) => {
- if (state == AVCastPickerState.STATE_APPEARING) {
- console.log(' The picker starts showing.');
- } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
- console.log(' The picker finishes presenting.');
- }
- },
- pickerStyle: AVCastPickerStyle.STYLE_PANEL,
- sessionType: 'video'
- })
- .id('AVCastPicker')
- .width(46)
- } else {
- Image(more.image)
- .width(24)
- .height(24)
- .margin({ left: 10, right: 10 })
- .onClick(() => {
- this.doMore(more.id)
- })
- Text(more.title)
- .fontSize(16)
- .fontColor(Color.White)
- .onClick(() => {
- this.doMore(more.id)
- })
- Select([//倍速
- { value: '0.25x' },
- { value: '0.5x' },
- { value: '0.75x' },
- { value: '1x' },
- { value: '1.25x' },
- { value: '1.5x' },
- { value: '1.75x' },
- { value: '2x' },
- { value: '3x' }])
- .font({ size: 16, weight: FontWeight.Medium })
- .fontColor($r('sys.color.white'))
- .margin({ left: 25 })
- .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
- .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
- .value(Utility.optimizedFormat(this.playSpeed))
- .onSelect(async (_index: number, text?: string | undefined) => {
- let speed = parseFloat(text?.replace('x', '') || '1');
- if (!CommonConstants.video_speed_list.includes(speed)) {
- speed = 1;
- }
- this.playSpeed = speed
- this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
- })
- Slider({
- value: this.volume,
- min: 0,
- max: 1,
- step: 0.1,
- style: SliderStyle.OutSet
- })
- .margin({ left: 18, right: 8 })
- .blockColor(Color.Red)
- .trackColor($r('app.color.speed_text_color'))
- .selectedColor(Color.White)
- .trackThickness(9)
- .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
- .onChange((value: number) => {
- this.volume = value;
- this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
- })
- .layoutWeight(1)
- Blank()
- Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
- .selectedColor($r('app.color.title_bar_bg'))
- .switchPointColor(Color.White)
- .margin({ right: 15 })
- .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
- .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
- if (more.id == 6) {
- this.isMusicMemoryPlay = checked;
- PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
- if (this.isMusicMemoryPlay) {
- ToastUtil.showToast('记忆播放已开启')
- } else {
- ToastUtil.showToast('记忆播放已关闭')
- }
- }
- })
- .width(48)
- .height(24);
- Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
- .selectedColor($r('app.color.title_bar_bg'))
- .switchPointColor(Color.White)
- .margin({ right: 15 })
- .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
- .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
- if (more.id == 7) {
- this.isMusicBGCover = checked;
- PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
- if (this.isMusicBGCover) {
- ToastUtil.showToast('播放背景随音乐封面已开启')
- } else {
- ToastUtil.showToast('播放背景随音乐封面已关闭')
- }
- }
- })
- .width(48)
- .height(24);
- Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
- .selectedColor($r('app.color.title_bar_bg'))
- .switchPointColor(Color.White)
- .margin({ right: 15 })
- .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
- .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
- if (more.id == 8) {
- this.isSavePlayMode = checked;
- PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
- if (this.isSavePlayMode) {
- ToastUtil.showToast('保存播放模式已开启')
- } else {
- ToastUtil.showToast('保存播放模式已关闭')
- }
- }
- })
- .width(48)
- .height(24);
- Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
- .selectedColor($r('app.color.title_bar_bg'))
- .switchPointColor(Color.White)
- .margin({ right: 15 })
- .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
- .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
- if (more.id == 13) {
- this.isCoverRectangle = checked;
- PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
- if (this.isCoverRectangle) {
- ToastUtil.showToast('封面方形已开启')
- this.animationRoFun()
- } else {
- ToastUtil.showToast('封面圆形已开启')
- this.animationRoFun()
- }
- }
- })
- .width(48)
- .height(24);
- }
- }
- .width('100%')
- .height(45)
- .padding(15)
- .backgroundColor(Color.Transparent) // 选中背景高亮
- .borderRadius(12)
- .margin({ bottom: 6 })
- });
- }
- .width('100%')
- .padding(16)
- }.margin({ bottom: 18 })
- }
- @Builder
- TPImageBuilder(more: MoreItem): void {
- Row() {
- Image($r('app.media.tuoping'))
- .width(22)
- .height(22)
- .margin({ left: 10, right: 10 })
- Text(more.title)
- .fontSize(16)
- .fontColor(Color.White)
- }
- }
- private moreItems: MoreItem[] = [
- { id: 1, image: $r('app.media.speed'), title: '倍速' },
- { id: 2, image: $r('app.media.lyric'), title: '歌词' },
- { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
- { id: 12, image: $r('app.media.toubo'), title: '投播' },
- { id: 4, image: $r('app.media.share2'), title: '分享' },
- { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
- { id: 15, image: $r('app.media.rename2'), title: '编辑信息' },
- { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
- { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
- { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
- { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
- { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
- { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
- { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
- { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
- ];
- @State isShowMoreView: boolean = false;
- @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
- @State isShowTimeCloseMore: boolean = false
- @State isShowDetailMore: boolean = false
- @State isMusicBGCover: boolean = true
- @State isSavePlayMode: boolean = true
- @State isLyricSetting: boolean = false
- @State isJumpSetting: boolean = false
- @State isShowEdit: boolean = false
- async setRingTone() {
- if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
- return
- }
- // 确定后的逻辑
- let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
- LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
- let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
- ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
- LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
- //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
- await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
- , this.videoUrl, this.name).then(res => {
- LogUtil.info('onecold setFlag :' + res);
- });
- }
- doMore(moreId: number) {
- switch (moreId) {
- case 10: //设为铃声
- this.setRingTone()
- this.isShowMoreView = false
- break;
- case 4: //分享
- if (this.currentSong !== undefined) {
- Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
- }
- this.isShowMoreView = false
- break;
- case 14: //搜索封面
- if (this.currentSong !== undefined) {
- let artist = this.currentSong?.artist
- if (StrUtil.isEmpty(artist) || artist === undefined) {
- artist = ''
- }
- this.searchCover(this.name, artist)
- }
- this.isShowMoreView = false
- break;
- }
- }
- searchCover(title: string, artist: string) {
- NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API','')).then(async (res) => {
- LogUtil.debug("onecold res =" + res)
- if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
- this.cover = res
- if (this.currentSong) {
- this.currentSong.pixelMapPath = res
- }
- this.table.updatePixelMapPath(this.videoUrl, this.cover, (success: boolean, error?: string) => {
- if (success) {
- this.doUpdateData()
- console.log(" onecold 更新音乐封面成功,数据库已同步");
- } else {
- console.error(" onecold 更新音乐封面数据库失败原因: " + error);
- }
- });
- LogUtil.debug("onecold this.cover =" + this.cover)
- }
- })
- }
- @State jumpTopTime: number = 0
- @State jumpEndTime: number = 0
- @State isOpenJump: boolean = false
- @Builder
- JumpTopEndSheet() {
- Scroll() {
- Column() {
- Column() {
- Text('仅对本播放列表有效')
- .fontSize(16)
- .fontColor($r('app.color.text_color'))
- // 跳过头尾
- Column() {
- Row() {
- Text('跳过片头:')
- .fontSize(16)
- .fontColor($r('app.color.text_color'))
- Text(this.jumpTopTime + 's')
- .fontSize(16)
- .fontColor($r('app.color.text_color'))
- }
- .margin({ bottom: 5 })
- Row() {
- Slider({
- value: this.jumpTopTime,
- min: 0,
- max: 120,
- step: 1,
- style: SliderStyle.OutSet
- })
- .blockColor(Color.Red)
- .trackColor($r('app.color.speed_text_color'))
- .selectedColor(Color.White)
- .trackThickness(8)
- .onChange((value: number) => {
- this.jumpTopTime = value;
- })
- .width('85%')
- }
- .alignItems(VerticalAlign.Top)
- }
- .margin({ top: 10, bottom: 10 })
- // 跳过头尾
- Column() {
- Row() {
- Text('跳过片尾:')
- .fontSize(16)
- .fontColor($r('app.color.text_color'))
- Text(this.jumpEndTime + 's')
- .fontSize(16)
- .fontColor($r('app.color.text_color'))
- }
- .margin({ bottom: 5 })
- Row() {
- Slider({
- value: this.jumpEndTime,
- min: 0,
- max: 120,
- step: 1,
- style: SliderStyle.OutSet
- })
- .blockColor(Color.Red)
- .trackColor($r('app.color.speed_text_color'))
- .selectedColor(Color.White)
- .trackThickness(8)
- .onChange((value: number) => {
- this.jumpEndTime = value;
- })
- .width('85%')
- }
- .alignItems(VerticalAlign.Top)
- }
- .margin({ top: 10, bottom: 10 })
- Row() {
- Button('保存设置')
- .fontColor(Color.White)
- .layoutWeight(1)
- .height(40)
- .width(80)
- .backgroundColor($r('app.color.title_bar_bg'))
- .stateEffect(true)
- .margin({ left: 0, bottom: 20 })
- .onClick(async () => {
- if (!Utility.isNoble()) {
- this.isJumpSetting = false
- this.isShowMoreView = false
- this.showVipDialog()
- return
- }
- if (this.currentSong === undefined) {
- return
- }
- if (this.modeType === 0) {
- let parentPath = FileUtil.getParentPath(this.videoUrl)
- PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
- PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
- PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
- } else if (this.modeType === 1) { //媒体库
- PreferencesUtil.putSync(1 + 'isOpenJump', true)
- PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
- PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
- } else if (this.modeType === 2) { //艺术家
- if (this.currentSong?.artist) {
- PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
- PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
- PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
- }
- } else if (this.modeType === 3) { //专辑
- if (this.currentSong?.album) {
- PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
- PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
- PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
- }
- }
- ToastUtil.showShort("保存成功")
- this.isJumpSetting = false
- })
- }
- .margin({
- left: 38,
- right: 38,
- top: 10,
- bottom: 10
- })
- .width(120)
- .height(50)
- }
- }
- }
- .width('100%')
- .height('100%')
- }
- // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
- private onStateVastChange(state: AVCastPickerState) {
- if (state == AVCastPickerState.STATE_APPEARING) {
- console.log('The picker starts showing.');
- } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
- console.log('The picker finishes presenting.');
- }
- }
- private showSelectLyric() {
- DialogHelper.showActionSheetDialog({
- title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
- // sheets: ["本地歌词", "搜索歌词"],
- sheets:[
- { value: "本地歌词", fontColor: $r('app.color.text_color') },
- { value: "搜索歌词", fontColor: $r('app.color.text_color') },
- ],
- maskColor: Color.Transparent,
- backgroundColor: $r('app.color.bg_card'),
- transition: AnimationHelper.transitionInDown(666),
- onAction: (index) => {
- switch (index) {
- case 0:
- this.callFilePickerSelectFileForLyric()
- break;
- case 1:
- if (StrUtil.isNotEmpty(this.videoUrl)) {
- let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
- this.initLyric(lyricPath);
- }
- break;
- }
- }
- })
- }
- // 拉起picker选择文件管理器
- async callFilePickerSelectFileForLyric(): Promise<void> {
- try {
- let DocumentSelectOptions = new picker.DocumentSelectOptions();
- DocumentSelectOptions.maxSelectNumber = 1
- DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
- let documentPicker = new picker.DocumentViewPicker();
- documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
- Logger.info(TAG,
- 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
- if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
- this.saveVideoDatasLyric(DocumentSelectResult)
- }
- }).catch((err: BusinessError) => {
- Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
- });
- } catch (err) {
- Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
- }
- }
- async saveVideoDatasLyric(uris: string[]) {
- if (ArrayUtil.isEmpty(uris)) {
- return
- }
- let newUris: string[] = [];
- for (let i = 0; i < uris.length; i++) {
- let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
- Logger.info(TAG, 'filePath uri: ' + filePath);
- newUris.push(filePath)
- let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
- let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
- fileIo.copyFileSync(file.fd, file2.fd)
- fileIo.closeSync(file);
- fileIo.closeSync(file2);
- this.initLyric(filePath)
- }
- }
- private initDelayPlay(context: object) {
- this.mContext = context;
- }
- private startPlayOrResumePlay() {
- this.mDestroyPage = false;
- this.animationState = AnimationStatus.Running
- LogUtils.getInstance().LOGI("startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
- if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
- this.stopProgressTask();
- this.startProgressTask();
- this.play(this.videoUrl.toString());
- }
- if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
- this.mIjkMediaPlayer.start();
- this.setProgress()
- this.CONTROL_PlayStatus = PlayStatus.PLAY
- }
- this.setIsPlaying(true)
- this.updateSessionPlayState(true)
- this.watchStatus();
- }
- private completionNum(num: number): string | number {
- if (num < 10) {
- return '0' + num;
- } else {
- return num;
- }
- }
- private stringForTime(timeMs: number): string {
- let totalSeconds: number | string = (timeMs / 1000);
- let newSeconds: number | string = totalSeconds % 60;
- let minutes: number | string = (totalSeconds / 60) % 60;
- let hours: number | string = totalSeconds / 3600;
- //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
- hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
- minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
- newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
- if (this.isCurrentTime) {
- if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
- this.oldSeconds = newSeconds
- } else {
- newSeconds = this.oldSeconds
- }
- }
- newSeconds = this.completionNum(newSeconds);
- if (hours > 0) {
- return hours + ":" + minutes + ":" + newSeconds;
- } else {
- return minutes + ":" + newSeconds;
- }
- }
- private setProgress() {
- let position = this.mIjkMediaPlayer.getCurrentPosition();
- let duration = this.mIjkMediaPlayer.getDuration();
- let pos = 0;
- if (duration > 0) {
- this.slideEnable = true;
- let curPercent = position / duration;
- pos = curPercent * 100;
- if (pos > this.PROGRESS_MAX_VALUE) {
- this.progressValue = this.PROGRESS_MAX_VALUE
- } else {
- this.progressValue = pos;
- }
- }
- // LogUtils.getInstance()
- // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
- this.totalTime = this.stringForTime(duration);
- if (position > duration) {
- position = duration;
- }
- this.isCurrentTime = true;
- this.lyricController.updatePosition(position + this.timeOffset * 1000)
- this.currentTime = this.stringForTime(position);
- this.isCurrentTime = false
- if (this.mIjkMediaPlayer.isPlaying()) {
- this.randomColor =
- `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
- // 判断是否播放到结束时间
- if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
- if (position >= duration - this.jumpEndTime * 1000) {
- this.playNext()
- }
- }
- } else {
- this.randomColor = 'rbg(0,0,0)'
- }
- }
- private startProgressTask() {
- let that = this;
- this.updateProgressTimer = setInterval(() => {
- //LogUtils.getInstance().LOGI("startProgressTask");
- if (!that.mDestroyPage) {
- that.setProgress();
- }
- }, 300);
- }
- private stopProgressTask() {
- LogUtils.getInstance().LOGI("stopProgressTask");
- clearInterval(this.updateProgressTimer);
- }
- private showLoadIng() {
- this.loadingVisible = Visibility.Visible;
- this.replayVisible = Visibility.None;
- }
- private hideLoadIng() {
- this.loadingVisible = Visibility.None;
- this.replayVisible = Visibility.None;
- }
- private showRePlay() {
- this.loadingVisible = Visibility.None;
- this.replayVisible = Visibility.Visible;
- }
- private async play(url: string) {
- let that = this;
- that.showLoadIng();
- //设置XComponent回调的context
- if (!!this.mContext) {
- this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
- }
- if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
- this.mIjkMediaPlayer.reset();
- }
- this.CONTROL_PlayStatus = PlayStatus.PLAY;
- //设置debug模式
- this.mIjkMediaPlayer.setDebug(false);
- //初始化配置
- this.mIjkMediaPlayer.native_setup();
- // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0
- this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
- //设置视频源
- this.mIjkMediaPlayer.setDataSource(url);
- //设置视频源http请求头
- let headers = new Map([
- ["user_agent", "Mozilla/5.0 BiliDroid/7.30.0 (bbcallen@gmail.com)"],
- ["referer", "https://www.bilibili.com"]
- ]);
- this.mIjkMediaPlayer.setDataSourceHeader(headers);
- // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
- // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
- // }
- this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
- //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
- const fileSize = await this.getFileSize(this.videoUrl);
- let bufferSize = 1 * 1024 * 1024; // 默认缓冲区大小为2MB
- if (fileSize > 3 * 1024 * 1024 * 1024) { // 文件大于3GB
- bufferSize = 25 * 1024 * 1024; // 设置缓冲区大小为25MB
- }
- //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
- //停止预读的最小帧数
- // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
- // 设置其他缓冲相关选项
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
- //启动预加载
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
- // 设置无缓冲,这是播放器的缓冲区,有数据就播放
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
- //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
- // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
- // 因此需要播放器丢包,才不会累积延时
- // 这个和第三个参数packet-buffering无关。
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
- // 无限制收流
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
- this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
- // 屏幕常亮
- this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
- // 设置超时
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
- // 变速播放
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
- this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
- let Speed = this.mIjkMediaPlayer.getSpeed()
- LogUtils.getInstance().LOGI('getSpeed--' + Speed)
- //是否开启循环播放
- // this.mIjkMediaPlayer.setLoopCount(this.loop);
- let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
- onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
- if (height === 0) {
- return;
- }
- const va = width / height;
- const vpa = that.videoParentAspectRatio;
- if (vpa > va) {
- that.videoWidth = (width / (height * vpa)) * 100 + '%';
- } else {
- that.videoWidth = '100%';
- }
- if (width && height) {
- that.videoAspectRatio = width / height;
- }
- LogUtils.getInstance()
- .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
- that.hideLoadIng();
- }
- }
- this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
- let mOnPreparedListener: OnPreparedListener = {
- onPrepared: async () => {
- LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
- try {
- this.cover = this.songList[this.curIndex].pixelMapPath
- this.artist = this.songList[this.curIndex].artist
- this.videoUrl = this.songList[this.curIndex].filePath
- let isBgCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
- if (isBgCover && this.cover !== undefined && StrUtil.isNotEmpty(this.cover)) {
- this.setImageColor2(this.cover)
- } else {
- this.getImageColor();
- }
- let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
- await this.initLyric(lyricPath);
- setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
- this.avSessionController.initAvSession(false);
- this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
- this.setAvSessionListener();
- this.updateSessionPlayState(true)
- this.setCurrentPlayMode()
- this.addItemToHistory(this.songList[this.curIndex])
- }, 500)
- let timeoutPlay = 0
- if (StrUtil.isNotEmpty(this.videoUrl) &&
- (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
- timeoutPlay = 1000
- }
- //跳过片头片尾关键代码,以下是跳过片头的关键代码
- if (this.modeType === 0) { //文件夹
- let parentPath = FileUtil.getParentPath(this.videoUrl)
- this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
- this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
- this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
- } else if (this.modeType === 1) { //媒体库
- this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
- this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
- this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
- } else if (this.modeType === 2) { //艺术家
- if (this.currentSong?.artist) {
- this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
- this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
- this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
- }
- } else if (this.modeType === 3) { //专辑
- if (this.currentSong?.album) {
- this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
- this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
- this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
- }
- }
- this.duration = this.mIjkMediaPlayer.getDuration()
- if (this.isOpenJump) { //用户是否设置跳过片头片尾
- if (this.mIjkMediaPlayer != null) {
- if (this.jumpTopTime * 1000 <= this.duration) {
- // 调用 seekTo 方法,跳到指定时间
- setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
- if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
- this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
- }
- }, timeoutPlay)
- } else {
- // 提示用户无法跳过
- ToastUtil.showToast('跳过时间超过视频时长');
- }
- }
- } else {
- this.jumpTopTime = 0
- this.jumpEndTime = 0
- //记忆播放
- if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
- setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
- if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
- this.restorePlaybackPosition() //读取播放记忆功能
- }
- }, timeoutPlay)
- }
- }
- this.saveLastPlayList()
- } catch (error) {
- let err: BusinessError = error as BusinessError;
- console.error('onecold failed with err: ' + JSON.stringify(err));
- }
- }
- }
- this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
- let mOnTimedTextListener: OnTimedTextListener = {
- onTimedText: () => {
- }
- }
- this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
- let mOnCompletionListener: OnCompletionListener = {
- onCompletion: () => {
- LogUtils.getInstance().LOGI("OnCompletionListener-->go")
- if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
- this.playNext()
- } else if (this.playType == 1) { //1:单片重复播放
- this.CONTROL_PlayStatus = PlayStatus.INIT
- that.startPlayOrResumePlay();
- } else if (this.playType == 2) { //2:正常播放,单曲播完
- that.showRePlay();
- that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
- that.progressValue = this.PROGRESS_MAX_VALUE;
- that.slideEnable = false;
- that.stop();
- // ToastUtil.showToast('开始重新播放')
- } else if (this.playType == 3) { //3:随机播放
- this.randomPlay()
- }
- }
- }
- this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
- let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
- onBufferingUpdate: (percent: number) => {
- LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
- let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
- LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
- let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
- LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
- let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
- LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
- let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
- LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
- let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
- LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
- let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
- LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
- let Looping = this.mIjkMediaPlayer.isLooping()
- LogUtils.getInstance().LOGI('isLooping---' + Looping);
- }
- }
- this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
- let mOnSeekCompleteListener: OnSeekCompleteListener = {
- onSeekComplete: () => {
- LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
- that.startPlayOrResumePlay();
- }
- }
- this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
- let mOnInfoListener: OnInfoListener = {
- onInfo: (what: number, extra: number) => {
- LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
- that.hideLoadIng();
- }
- }
- this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
- let mOnErrorListener: OnErrorListener = {
- onError: (what: number, extra: number) => {
- this.stopProgressTask();
- LogUtils.getInstance().LOGI("OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
- that.hideLoadIng();
- if (StrUtil.isNotEmpty(this.videoUrl) && !FileUtil.accessSync(this.videoUrl)) {
- ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
- } else {
- ToastUtil.showToast(getContext()
- .resourceManager
- .getStringByNameSync("Honey_the_video_is_playing_errant_The_system_is_wandering"))
- }
- }
- }
- this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
- this.mIjkMediaPlayer.setMessageListener();
- this.mIjkMediaPlayer.prepareAsync();
- this.mIjkMediaPlayer.start();
- }
- //保存最后播放的那首歌和已经对应的播放列表
- saveLastPlayList() {
- PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
- PreferencesUtil.putSync('LastMusicList', this.songList)
- }
- //添加播放历史记录
- async addItemToHistory(vItem: VideoItem) {
- if (vItem.type === CommonConstants.TYPE_LOCK) {
- return
- }
- // 检查是否已存在记录
- const existingIndex = this.historyList.findIndex(item => item.filePath === vItem.filePath);
- if (existingIndex !== -1) {
- // 更新现有记录的播放时间
- this.historyList[existingIndex].lastPlayed = new Date();
- } else {
- // 添加新的播放记录
- let newItem: VideoItem = new VideoItem(vItem.name, '', vItem.filePath, vItem.type,
- vItem.videoSize, vItem.cTime, vItem.pixelMap, vItem.size, vItem.pixelMapPath, vItem.artist, vItem.album
- , vItem.fileName, new Date())
- this.historyList.push(newItem);
- }
- // 保持播放记录不超过50条
- if (this.historyList.length > 50) {
- this.historyList = this.historyList.slice(0, 50);
- }
- // 按播放时间降序排序
- this.historyList.sort((a, b) => {
- let timeA = a.lastPlayed ? a.lastPlayed.getTime() : 0;
- let timeB = b.lastPlayed ? b.lastPlayed.getTime() : 0;
- return timeB - timeA;
- });
- // 缓存结果
- PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
- if (this.isHistory) {
- this.updateListData(this.historyList)
- }
- }
- // 删除播放记录
- removeVideoFromHistory(path: string) {
- this.historyList = this.historyList.filter(item => item.filePath !== path);
- }
- // 清空播放记录
- clearVideoHistory() {
- this.historyList = [];
- this.updateListData(this.historyList)
- PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
- ToastUtil.showToast('清空播放记录成功')
- }
- public async setAvSessionListener() {
- if (!this.avSessionController) {
- return;
- }
- this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
- this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
- this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
- this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
- this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
- this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
- this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
- this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
- this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
- this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
- this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
- }
- setLoopMode() {
- let itype = this.playType + 1
- if (itype >= 4) {
- this.playType = 0
- ToastUtil.showToast('连续播放')
- } else if (itype === 1) {
- this.playType = 1
- ToastUtil.showToast('单曲循环')
- } else if (itype === 2) {
- this.playType = 2
- ToastUtil.showToast('单曲播完')
- } else if (itype === 3) {
- this.playType = 3
- ToastUtil.showToast('随机播放')
- } else if (itype === 0) {
- this.playType = 0
- ToastUtil.showToast('连续播放')
- }
- PreferencesUtil.putSync('musicPlayType', this.playType)
- this.setCurrentPlayMode()
- }
- private sessionSetLoopModeCallback = (mode: number) => {
- if (this.mIjkMediaPlayer != null) {
- ToastUtil.showToast('当前播放模式:' + mode)
- Logger.info('onecold 当前播放模式= ' + mode)
- let hmPlayMode = mode + 1
- if (hmPlayMode >= 4) {
- hmPlayMode = 0
- }
- if (hmPlayMode === 1) {
- this.playType = 1
- ToastUtil.showToast('单曲循环')
- } else if (hmPlayMode === 0) {
- this.playType = 2
- ToastUtil.showToast('单曲播完')
- } else if (hmPlayMode === 3) {
- this.playType = 3
- ToastUtil.showToast('随机播放')
- } else if (hmPlayMode === 2) {
- this.playType = 0
- ToastUtil.showToast('连续播放')
- }
- PreferencesUtil.putSync('musicPlayType', this.playType)
- // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
- let playBackState: avSession.AVPlaybackState = {
- loopMode: hmPlayMode,
- };
- this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
- console.info(`set setLoopMode AVPlaybackState successfully`);
- }).catch((err: BusinessError) => {
- console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
- });
- }
- }
- setCurrentPlayMode() {
- if (!this.avSessionController) {
- return;
- }
- let mLoopMode = 0
- switch (this.playType) {
- case 0:
- mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
- break;
- case 1:
- mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
- break;
- case 2:
- mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
- break;
- case 3:
- mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
- break;
- }
- // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
- let playBState: avSession.AVPlaybackState = {
- loopMode: mLoopMode,
- isFavorite:Utility.getIsFav(this.favList,this.currentSong),
- };
- this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
- console.info(`set setLoopMode AVPlaybackState successfully`);
- }).catch((err: BusinessError) => {
- console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
- });
- }
- private sessionToggleFavoriteCallback = (assetId: string) => {
- if (this.mIjkMediaPlayer != null && this.currentSong) {
- console.info(`on toggleFavorite `);
- // 应用收到收藏命令,进行收藏处理。
- this.isFac = Utility.getIsFav(this.favList,this.currentSong)
- this.doFav(this.currentSong)
- // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
- let playbackState: avSession.AVPlaybackState = {
- isFavorite:!this.isFac,
- };
- this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
- console.info(`SetAVPlaybackState successfully`);
- }).catch((err: BusinessError) => {
- console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
- });
- }
- }
- private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
- device: avSession.OutputDeviceInfo) => {
- let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
- if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
- connectState === avSession.ConnectionState.STATE_CONNECTED) {
- await this.startCasting();
- } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
- connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
- (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
- connectState === avSession.ConnectionState.STATE_CONNECTED)) {
- if (device) {
- this.endCasting();
- }
- }
- };
- private async startCasting() {
- this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
- this.setPlaybackStateChangeListener();
- this.pause();
- this.initQueueItem();
- this.prepare();
- let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
- refToIsCasting?.set(true);
- this.castSeek = true;
- this.isCastPlaying = true;
- }
- async changeCasting() {
- this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
- this.initQueueItem();
- this.prepare();
- this.setPlaybackStateChangeListener();
- this.isCastPlaying = true;
- this.castSeek = true;
- }
- public endCasting() {
- this.avSessionController.getAvSession()?.stopCasting();
- this.stopCast();
- this.isCastPlaying = false;
- let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
- refToIsCasting?.set(false);
- this.pause();
- this.setIsPlaying(false);
- // if (this.curIndex === this.curSource.index) {
- // this.play
- // this.seek(this.currentTime * 1000);
- // this.setIsPlaying(true);
- // } else {
- // this.pauseVideo();
- // this.setIsPlaying(false);
- // }
- }
- public setIsPlaying(isPlayer: boolean) {
- this.isPlaying = isPlayer;
- }
- private setPlaybackStateChangeListener(): void {
- this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
- this.castController?.on('endOfStream', this.reloadCasting);
- this.castController?.on('playNext', this.playNextCallback);
- this.castController?.on('playPrevious', this.playPreviousCallback);
- }
- private updateSessionPlayState(isPlay: boolean): void {
- // if(!this.isBgPlayOpen)
- // return
- Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
- this.setAVSessionPlayState({
- state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
- position: {
- elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
- updateTime: new Date().getTime()
- }
- });
- }
- private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
- this.avSessionController.setAvSessionPlayState(playbackState)
- }
- private positionChange(position: number) {
- this.currentTime2 = position / 1000;
- this.currentStringTime = secondToTime(Math.floor(position / 1000));
- }
- private playDurationChange(duration: number) {
- this.duration = duration;
- this.durationTime = Math.floor(this.duration / 1000);
- this.durationStringTime = secondToTime((this.durationTime));
- }
- private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
- const duration = playbackState?.extras?.duration;
- if (typeof duration === 'number') {
- this.playDurationChange(duration as number);
- }
- if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
- this.positionChange(playbackState?.position?.elapsedTime);
- }
- if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
- playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
- playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
- playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
- this.isCastPlaying = false;
- }
- if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
- this.isCastPlaying = true;
- }
- };
- private reloadCasting = async () => {
- let item = this.songList[this.curIndex];
- let uri = fileUri.getUriFromPath(item.filePath);
- let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
- // description.startPosition = 0;
- this.castItem = {
- itemId: this.curIndex,
- description: {
- assetId: item.filePath,
- title: item.name,
- artist: '',
- // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
- // mediaUri: item.filePath,
- fdSrc: {
- fd: file.fd
- },
- // 该字段大写,音频'AUDIO',视频'VIDEO'
- mediaType: 'VIDEO',
- mediaSize: item.videoSize,
- //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
- startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
- // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
- duration: this.duration,
- // albumCoverUri: 'https://www.example.jpeg',
- // albumTitle: '《ExampleAlbum》',
- appName: this.appName,
- // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
- // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
- }
- };
- this.prepare();
- this.isCastPlaying = true;
- };
- public playNextCallback = (): void => {
- this.playNext()
- };
- public playPreviousCallback = (): void => {
- this.playPrevious()
- };
- async prepare() {
- await this.castController?.prepare(this.castItem);
- await this.castController?.start(this.castItem);
- }
- public initQueueItem() {
- let item = this.songList[this.curIndex];
- let time = this.currentTime;
- let uri = fileUri.getUriFromPath(item.filePath);
- let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
- this.castItem = {
- itemId: this.curIndex,
- description: {
- assetId: item.filePath,
- title: item.name,
- artist: '',
- // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
- fdSrc: {
- fd: file.fd
- },
- // 该字段大写,音频'AUDIO',视频'VIDEO'
- mediaType: 'AUDIO',
- mediaSize: item.videoSize,
- //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
- startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
- // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
- duration: this.duration,
- // albumCoverUri: 'https://www.example.jpeg',
- // albumTitle: '《ExampleAlbum》',
- appName: this.appName,
- // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
- // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
- }
- };
- }
- async stopCast() {
- try {
- this.castController?.off('playbackStateChange');
- this.castController?.off('endOfStream');
- this.castController?.off('playNext');
- this.castController?.off('playPrevious');
- this.castController?.off('error');
- } catch (error) {
- hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
- }
- }
- private sessionPlayCallback = (): void => {
- this.playOrPause()
- };
- private sessionPauseCallback = (): void => {
- this.playOrPause()
- };
- private playOrPause() {
- if (!this.debounce()) {
- return;
- }
- if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
- this.pause();
- } else {
- this.startPlayOrResumePlay();
- this.playChange()
- }
- }
- private sessionPlayNextCallback = (): void => {
- this.playNext()
- };
- private sessionPlayPreviousCallback = (): void => {
- this.playPrevious()
- };
- private sessionStopCallback = (): void => {
- this.stop()
- };
- private sessionFastForwardCallback = (time?: number) => {
- if (!time) {
- return;
- }
- if (this.mIjkMediaPlayer != null) {
- const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
- let seeTime = curPosition + time * 1000;
- // 限制 seekValue 在合法范围内
- if (seeTime < 0) {
- seeTime = 0;
- } else if (seeTime > this.duration) {
- seeTime = this.duration;
- }
- Logger.info('onecold seeTime= ' + seeTime)
- this.setSeekToActionProgress(seeTime)
- this.seekTo(seeTime + "")
- }
- };
- /**
- * Gesture method onActionUpdate.
- *
- * @param event Gesture event.手势拖动设置快进和后退
- */
- private setSeekToActionProgress(position: number) {
- // let position = this.mIjkMediaPlayer.getCurrentPosition();
- let duration = this.mIjkMediaPlayer.getDuration();
- let pos = 0;
- if (duration > 0) {
- this.slideEnable = true;
- let curPercent = position / duration;
- pos = curPercent * 100;
- if (pos > this.PROGRESS_MAX_VALUE) {
- this.progressValue = this.PROGRESS_MAX_VALUE
- } else {
- this.progressValue = pos;
- }
- }
- // LogUtils.getInstance()
- // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
- this.totalTime = this.stringForTime(duration);
- if (position > duration) {
- position = duration;
- }
- this.isCurrentTime = true;
- this.currentTime = this.stringForTime(position);
- this.isCurrentTime = false
- }
- private sessionRewindCallback = (time?: number) => {
- if (!time) {
- return;
- }
- if (this.mIjkMediaPlayer != null) {
- const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
- let seeTime = curPosition - time * 1000;
- // 限制 seekValue 在合法范围内
- if (seeTime < 0) {
- seeTime = 0;
- } else if (seeTime > this.duration) {
- seeTime = this.duration;
- }
- Logger.info('onecold seeTime= ' + seeTime)
- this.setSeekToActionProgress(seeTime)
- this.seekTo(seeTime + "")
- }
- };
- private sessionSeekCallback = (seekTime: number) => {
- if (this.mIjkMediaPlayer != null) {
- const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
- this.seekTo(seekTime + "")
- }
- };
- private async getFileSize(filePath: string): Promise<number> {
- try {
- const stat = await fs.stat(filePath);
- return stat.size;
- } catch (err) {
- console.error('Failed to get file size: ' + err.message);
- return 0;
- }
- }
- private pause() {
- if (this.mIjkMediaPlayer.isPlaying()) {
- this.savePlaybackPosition();
- this.mIjkMediaPlayer.pause();
- this.setProgress();
- this.mDestroyPage = true;
- this.CONTROL_PlayStatus = PlayStatus.PAUSE;
- this.updateSessionPlayState(false)
- this.playChange()
- }
- }
- private stop() {
- this.savePlaybackPosition();
- this.CONTROL_PlayStatus = PlayStatus.INIT;
- this.mIjkMediaPlayer.stop();
- this.mIjkMediaPlayer.release();
- this.stopProgressTask();
- this.updateSessionPlayState(false)
- this.playChange()
- this.watchStatus();
- }
- //保持记忆播放功能
- private savePlaybackPosition() {
- if (this.mIjkMediaPlayer != null) {
- const position = this.mIjkMediaPlayer.getCurrentPosition();
- // ToastUtil.showToast('保存记忆播放 = ' + position)
- const duration = this.mIjkMediaPlayer.getDuration();
- const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
- // 如果播放位置接近视频末尾,则保存 position 为 0
- const playbackPosition = (duration - position < threshold) ? 0 : position;
- PreferencesUtil.putSync(this.videoUrl, playbackPosition);
- }
- }
- //获取记忆播放功能
- private restorePlaybackPosition() {
- const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
- // ToastUtil.showToast('position = ' + position)
- if (this.mIjkMediaPlayer != null && position > 0) {
- // ToastUtil.showToast('seekTo = ' + position)
- this.seekTo(position + "");
- }
- }
- private seekTo(value: string) {
- // this.stopProgressTask();
- if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
- ToastUtil.showToast('wma格式不支持拖动快进。')
- return
- }
- this.mIjkMediaPlayer.seekTo(value);
- // this.startPlayOrResumePlay()
- // 在这里恢复计时器状态
- this.setProgress()
- // this.startProgressTask();
- }
- // 添加到下一首播放
- private addToNextPlay(song: VideoItem) {
- if (!this.debounce()) {
- return;
- }
- if (this.currentSong) {
- if (this.currentSong === song) {
- ToastUtil.showToast('当前已经在播放这首歌了!')
- return
- }
- }
- // 如果未开始播放或队列为空
- if (this.curIndex === -1 || this.songList.length === 0) {
- this.songList = [song];
- this.curIndex = 0;
- this.doPlay(song)
- return;
- }
- // 插入到当前索引+1的位置
- const insertPos = this.curIndex + 1;
- this.songList.splice(insertPos, 0, song);
- this.songList = [...this.songList]; // 触发状态更新
- this.sonDataSource.pushArrayData(this.songList)
- ToastUtil.showToast('已添加至下一首播放')
- }
- //下一个
- private playNext() {
- if (!this.debounce()) {
- return;
- }
- if (this.playType == 3) { //3:随机播放
- this.randomPlay()
- return;
- }
- if (ArrayUtil.isNotEmpty(this.songList)) {
- if (this.curIndex == this.songList.length - 1) {
- this.curIndex = 0;
- } else {
- this.curIndex++;
- }
- this.CONTROL_PlayStatus = PlayStatus.INIT;
- this.stop();
- this.currentSong = this.songList[this.curIndex]
- this.videoUrl = this.songList[this.curIndex].filePath;
- this.name = this.songList[this.curIndex].name
- this.startPlayOrResumePlay()
- }
- }
- // 存储已播放的歌曲索引
- private playedIndices: Set<number> = new Set();
- //随机播放
- private randomPlay() {
- // if (!this.debounce()) {
- // return;
- // }
- if (ArrayUtil.isNotEmpty(this.songList)) {
- if (this.songList.length > 3) {
- // 如果所有歌曲都播放过一次,清空已播放索引集合
- if (this.playedIndices.size === this.songList.length) {
- this.playedIndices.clear();
- }
- // 随机选择一个未播放的歌曲索引
- let newIndex: number;
- do {
- newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
- } while (this.playedIndices.has(newIndex));
- this.curIndex = newIndex;
- this.playedIndices.add(newIndex);
- } else {
- // 当歌曲数量小于或等于3时,直接播放下一首
- if (this.curIndex == this.songList.length - 1) {
- this.curIndex = 0;
- } else {
- this.curIndex++;
- }
- }
- this.CONTROL_PlayStatus = PlayStatus.INIT;
- this.stop();
- this.currentSong = this.songList[this.curIndex];
- this.videoUrl = this.songList[this.curIndex].filePath;
- this.name = this.songList[this.curIndex].name;
- this.startPlayOrResumePlay();
- }
- }
- private playIndex(index: number) {
- if (!this.debounce()) {
- return;
- }
- if (ArrayUtil.isNotEmpty(this.songList)) {
- this.CONTROL_PlayStatus = PlayStatus.INIT;
- this.stop();
- this.currentSong = this.songList[this.curIndex]
- this.videoUrl = this.songList[index].filePath;
- this.name = this.songList[index].name
- this.curIndex = index;
- this.startPlayOrResumePlay()
- }
- }
- //上一个
- private playPrevious() {
- if (!this.debounce()) {
- return;
- }
- if (this.playType == 3) { //3:随机播放
- this.randomPlay()
- return;
- }
- if (this.curIndex == 0) {
- this.curIndex = this.songList.length - 1;
- } else {
- this.curIndex--;
- }
- this.CONTROL_PlayStatus = PlayStatus.INIT;
- this.stop();
- this.currentSong = this.songList[this.curIndex]
- this.videoUrl = this.songList[this.curIndex].filePath;
- this.name = this.songList[this.curIndex].name
- this.startPlayOrResumePlay()
- }
- debounce() {
- const delay = 600;
- let cur = new Date().getTime();
- if (cur - this.last > delay) {
- this.last = cur;
- return true;
- }
- return false;
- }
- /**
- * Sets whether the screen is a constant based on the playback status.
- */
- watchStatus() {
- // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
- if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
- this.windowClass.setWindowKeepScreenOn(true);
- } else {
- this.windowClass.setWindowKeepScreenOn(false);
- }
- }
- /**
- * Volume gesture method onActionStart.
- *
- * @param event Gesture event.
- */
- private customDialogComponentIdMM: number = 0
- @Builder
- customDialogComponentMM() {
- Column() {
- Row() {
- Blank()
- Text('验证密码')
- .fontSize(22)
- .fontColor($r('app.color.pri_bg'))
- .margin({ top: 18 })
- Blank()
- Image($r('app.media.close'))
- .fillColor(Color.White)
- .margin({ top: 18, right: 18 })
- .width(20)
- .onClick(() => {
- promptAction.closeCustomDialog(this.customDialogComponentIdMM)
- })
- }
- .width('100%') // 使Row占据整个宽度
- .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
- Verify({
- onVerifyCompleted: this.handleVerifyCompleted.bind(this)
- });
- }.height('60%')
- .backgroundColor($r('app.color.index_background'))
- .justifyContent(FlexAlign.SpaceBetween)
- }
- private handleVerifyCompleted(isSuccess: boolean) {
- if (isSuccess) {
- console.log('验证成功');
- // 在这里处理验证成功后的逻辑
- promptAction.closeCustomDialog(this.customDialogComponentIdMM)
- this.currentPath = this.lockPath
- this.getSortedFiles(this.currentPath)
- } else {
- // console.log('验证失败');
- ToastUtil.showToast('验证失败')
- }
- }
- private showVerifyDialog() {
- promptAction.openCustomDialog({
- transition: TransitionEffect.asymmetric(
- TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
- TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
- ,
- TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
- TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
- ),
- builder: () => {
- this.customDialogComponentMM()
- },
- isModal: true,
- autoCancel: true,
- maskColor: Color.Transparent,
- alignment: DialogAlignment.Bottom,
- onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
- console.info("reason" + JSON.stringify(dismissDialogAction.reason))
- console.log("dialog onWillDismiss")
- if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
- dismissDialogAction.dismiss()
- }
- if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
- dismissDialogAction.dismiss()
- }
- }
- }).then((dialogId: number) => {
- this.customDialogComponentIdMM = dialogId
- })
- }
- //左滑操作 移动文件 重命名 删除等操作
- @Builder
- DeleteButton(item: VideoItem, index: number, filePath: string) {
- Row() {
- //加入收藏
- Button() {
- Image(Utility.getIsFav(this.favList,item)?$r('app.media.add_fac_light2'):$r('app.media.add_fac'))
- .fillColor(Color.White)
- .width(20)
- }
- .width(40)
- .height(40)
- .type(ButtonType.Circle)
- .backgroundColor($r('app.color.title_bar_bg'))
- .margin(5)
- .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
- .onClick(() => {
- if(item){
- this.doFav(item)
- }
- })
- //加入下一首播放
- Button() {
- Image($r('app.media.next_to_play'))
- .fillColor(Color.White)
- .width(20)
- }
- .width(40)
- .height(40)
- .type(ButtonType.Circle)
- .backgroundColor($r('app.color.title_bar_bg'))
- .margin(5)
- .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
- .onClick(() => {
- this.addToNextPlay(item);
- })
- //复制文件
- Button() {
- Image($r('app.media.copy'))
- .fillColor(Color.White)
- .width(20)
- }
- .width(40)
- .height(40)
- .type(ButtonType.Circle)
- .backgroundColor($r('app.color.title_bar_bg'))
- .margin(5)
- .id(filePath + 'copy')
- .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
- .onClick(() => {
- this.showCopyDialog(false, item, index, filePath + 'copy');
- })
- //移动文件
- Button() {
- Image($r('app.media.cut'))
- .fillColor(Color.White)
- .width(20)
- }
- .width(40)
- .height(40)
- .type(ButtonType.Circle)
- .backgroundColor($r('app.color.title_bar_bg'))
- .margin(5)
- .id(filePath)
- .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
- .onClick(() => {
- this.showCutDialog(false, item, index, filePath);
- })
- Button() {
- Image($r('app.media.cut_current'))
- .fillColor(Color.White)
- .width(20)
- }
- .width(40)
- .height(40)
- .type(ButtonType.Circle)
- .backgroundColor($r('app.color.title_bar_bg'))
- .margin(5)
- .id(filePath + 'current')
- .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
- (this.isHasDir ? Visibility.Visible : Visibility.None))
- .onClick(() => {
- this.showCutDialog(true, item, index, filePath + 'current');
- })
- //重命名
- Button() {
- Image($r('app.media.rename2'))
- .fillColor(Color.White)
- .width(20)
- }
- .width(40)
- .height(40)
- .type(ButtonType.Circle)
- .backgroundColor($r('app.color.title_bar_bg'))
- .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
- (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
- item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
- .margin(5)
- .onClick(() => {
- this.showReNameDialog(item, index + '', filePath)
- })
- Button() {
- Image($r('app.media.delete2'))
- .fillColor(Color.White)
- .width(20)
- }
- .width(40)
- .height(40)
- .type(ButtonType.Circle)
- .backgroundColor($r('app.color.title_bar_bg'))
- .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
- (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
- item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
- .margin(5)
- .onClick(() => {
- this.showWarnIsDeleteFile(item, index + '', filePath)
- })
- Button() {
- Image($r('app.media.share2'))
- .fillColor(Color.White)
- .width(20)
- }
- .width(40)
- .height(40)
- .type(ButtonType.Circle)
- .backgroundColor($r('app.color.title_bar_bg'))
- .margin(5)
- .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
- .onClick(() => {
- Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
- })
- }
- }
- /**
- * 穿山甲banner广告
- */
- private declare bannerAd: CSJNativeExpressAd;
- @State private status: string = "未加载"
- @State private isShowAd: boolean = false
- private declare mAdSlot: AdSlot;
- private mBiddingAdm = '' //服务端bidding才需要设置
- private expressLoadAdListener: NativeExpressAdListener = {
- /**
- * 加载失败的回调
- *
- * @param code
- * @param message
- */
- onError: (code: number, message: string) => {
- console.error("加载广告失败,code=" + code + ",message=" + message);
- this.status = "加载广告失败,code=" + code + ",message=" + message;
- },
- /**
- * 广告加载成功的回调,接入方可以在这个回调中进行渲染
- *
- * @param ads 返回的广告列表
- */
- onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
- console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
- if (ads && ads.length > 0) {
- ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
- ad.setExpressInteractionListener({
- /**
- *广告的点击回调
- * @param type 广告的交互类型
- */
- onAdClicked: (type: number) => {
- console.log("BannerExpressAdPage==onAdClicked......");
- },
- /**
- * 广告的展示回调 每个广告仅回调一次
- * @param type 广告的交互类型
- */
- onAdShow: (type: number) => {
- console.log("BannerExpressAdPage==onAdShow......");
- },
- /**
- * 模板渲染失败
- */
- onRenderFail: (code: number, msg: string) => {
- console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
- },
- /**
- * 模板渲染成功
- * @param width 返回view的宽 单位 vp
- * @param height 返回view的高 单位 vp
- */
- onRenderSuccess: (width: number, height: number) => {
- console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
- this.bannerAd = ad;
- this.status = "广告加载完成待展示";
- this.showBannerAd()
- }
- })
- //渲染广告
- ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
- this.setDislikeCallback(ad); //设置dislike
- ad.render(this.getUIContext())
- this.status = "广告加载中...";
- });
- }
- }
- }
- private setDislikeCallback(ad: CSJNativeExpressAd) {
- ad.setDislikeCallback({
- /**
- * dislike show
- */
- onShow: () => {
- console.log("BannerExpressAdPage==dislike......show");
- },
- /**
- * @param position 选择的位置
- * @param value 选择的内容
- * @param enforceRemove 是否强制关闭广告
- */
- onSelected: (position: number, value: string, enforceRemove: boolean) => {
- this.isShowAd = false;
- console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
- ",enforce=" + enforceRemove);
- },
- /**
- * 点击取消
- */
- onCancel: () => {
- console.log("BannerExpressAdPage==dislike......onCancel");
- }
- })
- }
- /**
- * 加载Banner广告
- */
- loadBannerAd(rit: string) {
- if (Utility.isNoble()) {
- return
- }
- if (!Utility.isPassInstallTime(2)) {
- return
- }
- this.isShowAd = false;
- let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
- this.mAdSlot = new AdSlotBuilder()
- .setCodeId(rit)
- .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
- .setAdCount(1)
- .setBidAdm(this.mBiddingAdm)
- .build()
- PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
- adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
- this.status = "广告加载中..."
- }
- /**
- * 展示Banner广告
- */
- showBannerAd() {
- if (!this.bannerAd) {
- return
- }
- this.isShowAd = true
- this.status = "已展示"
- }
- /**
- * 穿山甲广告代码结束
- */
- }
- //视频气泡窗口的布局
- @Builder
- function customPopupBuilder(dataBu: BubbleBean) {
- List() {
- LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
- ListItem() {
- Row() {
- Column() {
- Image(dataBu.imageRes[index])
- .height(28)
- .alignSelf(ItemAlign.Center)
- }
- .width(32)
- Text(item)
- .padding({
- top: 10,
- bottom: 10,
- right: 10,
- left: 10
- })
- .textAlign(TextAlign.Start)
- .width("100%")
- }
- .margin({ top: 6, bottom: 6 })
- }.onClick(() => {
- dataBu.onItemClick?.(index)
- })
- })
- }
- .width(120)
- .divider({
- strokeWidth: 1,
- color: "#22FFFFFF"
- })
- }
- // Function to calculate a hash for the file list
- function simpleHash(fileList: string[]): string {
- let hash = 0;
- const str = fileList.join(',');
- for (let i = 0; i < str.length; i++) {
- const char = str.charCodeAt(i);
- hash = (hash << 5) - hash + char;
- hash |= 0; // Convert to 32bit integer
- }
- return hash.toString();
- }
- interface MoreItem {
- id: number;
- image: Resource;
- title: string;
- }
- //视频气泡窗口的布局
- @Builder
- function cutPopupBuilder(dataBu: BubbleBean) {
- Column() {
- Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
- .padding({
- top: 10,
- bottom: 10,
- right: 10,
- left: 10
- })
- .textAlign(TextAlign.Start)
- .width(160)
- .fontWeight(666)
- .fontSize(16)
- List() {
- ForEach(dataBu.data, (item: string, index: number) => {
- ListItem() {
- Row() {
- Column() {
- Image($r('app.media.music_group'))
- .height(28)
- .alignSelf(ItemAlign.Center)
- }
- .width(32)
- Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
- .padding({
- top: 10,
- bottom: 10,
- right: 10,
- left: 10
- })
- .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
- .fontSize(15)
- }
- .margin({ top: 7, bottom: 7 })
- }.onClick(() => {
- dataBu.onItemClick?.(index)
- })
- })
- }
- .width(150)
- .divider({
- strokeWidth: 1,
- color: "#22FFFFFF"
- })
- }
- .height(300)
- .padding({
- bottom:30
- })
- }
|