| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397 |
- import TitleBar from './TitleBar'
- import { curves, display, MenuModifier,PiPWindow, promptAction, router, SymbolGlyphModifier, window } from '@kit.ArkUI';
- import { VideoItem } from '../viewmodel/VideoItem';
- import { LengthMetrics, SegmentButton,SegmentButtonOptions } from '@kit.ArkUI';
- import { getWebdavVideoItems, getWebdavCurrentPlayIndex } from '../pages/WebDavMainPage';
- import {
- ButtonFancyModifier,
- ImageFancyModifier,
- ShadowModifier,
- SymbolGlyphFancyModifier } from '../common/util/AttributeModifierUtil'
- import {
- AppUtil,
- ArrayUtil,
- Base64Util,
- DateUtil,
- DeviceUtil,
- FileUtil,
- GlobalContext,
- LogUtil,
- MD5,
- PreferencesUtil,
- RandomUtil,
- StrUtil,
- ToastUtil
- } from '@pura/harmony-utils';
- import { imagePathToPixelMap } from '../common/util/CommUtils';
- import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
- import { CommonConstants } from '../common/constants/CommonConstants';
- import { EventConstants } from '../common/constants/EventConstants';
- import Logger from '../common/util/Logger';
- import { photoAccessHelper } from '@kit.MediaLibraryKit';
- import { BusinessError, emitter } from '@kit.BasicServicesKit';
- 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 { MessageEvents, util, worker, ErrorEvent } from '@kit.ArkTS';
- import { Verify } from './Verify';
- import { taskpool } from '@kit.ArkTS';
- import { RotatingCover } from './RotatingCover';
- import { PlayConstants } from '../common/constants/PlayConstants';
- import { effectKit } from '@kit.ArkGraphics2D';
- import { ColorConversion } from '../common/util/ColorConversion';
- import { LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
- import { AvSessionController } from '../controller/AvSessionController';
- import { repairAudioMetadata, convertDsfToWav, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
- import { FFMpegTags,Utility } from '../common/util/Utility';
- import { TagsContentCover } from '../view/TagsContentCover';
- import {
- // DeviceChangeReason,
- 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 { UniversalDetector } from '@ohos/juniversalchardet';
- import { SettingPage } from '../pages/SettingPage';
- import { secondToTime,getTransverterText } 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 FileDeletionWatcher from '../common/util/FileDeletionWatcher';
- 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 { deviceInfo } from '@kit.BasicServicesKit';
- import { ensureSmbFileCached } from '../common/network/SmbFileCache';
- import { findWebDavCacheIfExists, triggerWebDavCacheDownload } from '../common/network/WebDavFileCache';
- import { navidromeApi } from '../common/network/NavidromeApi';
- import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
- import app from '@system.app';
- import { TextNodeController } from './PipLyricTextBuilder';
- import { IndexerView } from './IndexerView';
- import { KeyCode } from '@kit.InputKit';
- import { KnockController } from '../controller/KnockController';
- import { DeleteComptent } from '../view/DeleteComptent';
- import { ABLoopComptent } from '../view/ABLoopComptent';
- import { FixMessyView } from '../view/FixMessyView';
- import { parseCueFile,CueTrack,CueInfo } from '../common/util/CueUtils';
- import { CueComptent } from '../view/CueComptent';
- import PlaylistTable from '../common/util/PlaylistTable';
- import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
- import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
- import { convertPlaylistSongsToVideoItems, emptyView,updateAllSongsSortOrder } from '../pages/PlaylistDetailPage';
- import { Playlist, PlaylistSong } from '../viewmodel/Playlist';
- import { Song } from '../viewmodel/Song';
- import { SongType } from '../common/enums/SongType';
- import { RemoteDriveManager, WebDavAuthInfo as WebDavManagerAuthInfo,
- buildHttpHeadersWithWebDav,
- WebDavAuthItem} from '../common/util/RemoteDriveManager';
- import PermissionUtil from '../common/util/PermissionUtil'
- import { EditAudio, setRingTone } from './EditAudio';
- import { ExtractAccompaniment } from './ExtractAccompaniment';
- import { ExtractAudioFromVideo } from './ExtractAudioFromVideo';
- import { AudioFormatConverter } from './AudioFormatConverter';
- import { MergeAudio } from './MergeAudio';
- import { AIVoiceSeparation } from './AIVoiceSeparation';
- import { WebDavUrlUtil } from '../common/util/WebDavUrlUtil';
- import { ChangeTone } from './ChangeTone';
- import {
- hdsEffect,
- HdsVisualComponent,
- HdsSceneController,
- HdsSceneType,
- HdsVisualComponentAttribute,
- } from '@kit.UIDesignKit';
- import { GlobalAlphabetIndexerModifier } from '../Styels/GlobalStyles'
- import { getFirstLetter } from '../Constants';
- const TAG = 'LocalMusic';
- /**
- * 歌单播放事件数据
- */
- interface PlaylistEventData {
- playlistId: string;
- playlistName: string;
- songCount: number;
- startIndex: number;
- songFilePaths: string[];
- webDavAuthInfo?: WebDavAuthItem; // 新增WebDAV认证信息
- }
- const DEFAULT_INDEX =
- ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
- 'X', 'Y', 'Z']
- //排序类型
- 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
- case CommonConstants.TYPE_WEBDAV:
- case CommonConstants.TYPE_SMB:
- case CommonConstants.TYPE_NAVIDROME:
- return 3;
- default:
- return 4; // Unknown types, if any, go last
- }
- }
- function isWebDavType(type: number): boolean {
- return type === CommonConstants.TYPE_WEBDAV;
- }
- function isSmbType(type: number): boolean {
- return type === CommonConstants.TYPE_SMB;
- }
- function isNavidromeType(type: number): boolean {
- return type === CommonConstants.TYPE_NAVIDROME;
- }
- function isRemoteCloudType(type: number): boolean {
- return isWebDavType(type) || isSmbType(type) || isNavidromeType(type);
- }
- function getShareNameFromFilePath(filePath?: string): string | undefined {
- if (!filePath) {
- return undefined;
- }
- const match = filePath.match(/^smb:\/\/[^/]+\/([^/]+)/i);
- return match && match[1] ? match[1] : undefined;
- }
- function removeSharePrefixFromPath(path: string, primaryShare?: string, secondaryShare?: string): string {
- const uniqueShares: string[] = [];
- [primaryShare, secondaryShare].forEach((name?: string) => {
- const cleaned = name ? name.replace(/^\/+|\/+$/g, '') : '';
- if (cleaned.length > 0 && !uniqueShares.some(item => item.toLowerCase() === cleaned.toLowerCase())) {
- uniqueShares.push(cleaned);
- }
- });
- if (uniqueShares.length === 0) {
- return path;
- }
- let result = path;
- for (let i = 0; i < uniqueShares.length; i++) {
- const share = uniqueShares[i];
- const lowerPath = result.toLowerCase();
- const lowerShare = share.toLowerCase();
- if (lowerPath === lowerShare) {
- result = '';
- break;
- }
- const prefix = `${lowerShare}/`;
- if (lowerPath.startsWith(prefix)) {
- result = result.substring(share.length + 1);
- break;
- }
- }
- return result;
- }
- function extractSmbRelativePath(song: VideoItem, shareNameOverride?: string): string {
- const shareFromFilePath = getShareNameFromFilePath(song.filePath);
- const shareName = shareNameOverride ?? shareFromFilePath;
- if (song.remote_rel_path && song.remote_rel_path.length > 0) {
- const cleaned = song.remote_rel_path.replace(/^\/+/, '');
- return removeSharePrefixFromPath(cleaned, shareName, shareFromFilePath);
- }
- if (!song.filePath) {
- return '';
- }
- const match = song.filePath.match(/^smb:\/\/[^/]+\/([^/]+)(\/.*)?$/i);
- if (!match) {
- return song.filePath.replace(/^\/+/, '');
- }
- const remainder = match[2] ? match[2].replace(/^\/+/, '') : '';
- if (remainder.length === 0) {
- return '';
- }
- return remainder;
- }
- const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
- interface MetadataExtractionOptions {
- context?: common.Context;
- autoParseMusicName?: boolean;
- }
- interface WorkerEditMusicResult {
- success: boolean;
- error?: string;
- coverResult?: boolean;
- needRefreshList?: boolean;
- metadataResult?: boolean;
- }
- interface LocalEditMusicPayload {
- context: Context;
- item: VideoItem;
- titleStr: string;
- artistStr: string;
- ablumStr: string;
- yearStr: string;
- genreStr: string;
- trackStr: string;
- albumArtistStr: string;
- composerStr: string;
- lyricistStr: string;
- commentStr: string;
- discStr: string;
- lyricConStr: string;
- imagePathStr: string;
- currentPath: string;
- packName: string;
- modeType: number;
- autoParseMusicName: boolean;
- }
- interface WorkerMetadataPayload {
- originFilePath: string;
- originId?: string;
- bit_rate?: string;
- duration?: string;
- sampleRate?: string;
- mimeType?: string;
- md5Str?: string;
- videoSize?: number;
- size?: string;
- pixelMapPath?: string;
- artist?: string;
- album?: string;
- name?: string;
- lyricContent?: string;
- bits_per_raw_sample?: string;
- channels?: string;
- channel_layout?: string;
- start_time?: string;
- genre?: string;
- year?: string;
- probe_score?: number;
- track?: string;
- disc?: string;
- ALBUMARTIST?: string;
- COMPOSER?: string;
- COMMENT?: string;
- LYRICIST?: string;
- nb_streams?: number;
- nb_programs?: number;
- error?: string;
- }
- interface WebDavMetadataUpdatePayload {
- filePath: string;
- pixelMapPath?: string;
- name?: string;
- artist?: string;
- }
- const metadataExtractionInFlight: Set<string> = new Set();
- function scheduleMetadataExtractionFromCache(
- song: VideoItem,
- cachePath: string,
- options?: MetadataExtractionOptions
- ): void {
- if (!song || !cachePath || !song.filePath || !options || !options.context) {
- return;
- }
- if (!isRemoteCloudType(song.type ?? -1)) {
- return;
- }
- if (metadataExtractionInFlight.has(song.filePath)) {
- return;
- }
- if (song.bit_rate && song.sampleRate && song.duration) {
- return;
- }
- metadataExtractionInFlight.add(song.filePath);
- workerInstance.postMessage({
- code: 5,
- data: options.context,
- data2: cachePath,
- data3: song.type,
- data4: {
- name:song.name,
- originFilePath: song.filePath,
- originId: song.id,
- autoParseMusicName: options.autoParseMusicName ?? false
- }
- });
- }
- function sanitizePlaybackUrl(rawUrl: string | null | undefined): string {
- if (!rawUrl) {
- return '';
- }
- try {
- const decoded = decodeURI(rawUrl);
- const encoded = encodeURI(decoded);
- // encodeURI 不会处理 #,手动转义避免播放器把剩余内容当作片段
- return encoded.replace(/#/g, '%23');
- } catch (error) {
- const err = error as Error;
- Logger.warn(TAG, `URL 编码失败,使用降级方案: ${err?.message}`);
- return rawUrl.replace(/ /g, '%20').replace(/#/g, '%23');
- }
- }
- function cloneVideoItem(item: VideoItem): VideoItem {
- const copy = new VideoItem(
- item.name,
- item.id,
- item.filePath,
- item.type,
- item.videoSize,
- item.cTime,
- item.size,
- item.pixelMapPath,
- item.artist,
- item.album,
- item.fileName,
- item.lastPlayed
- );
- copy.parentPath = item.parentPath;
- copy.isFav = item.isFav;
- copy.size = item.size;
- copy.pixelMapPath = item.pixelMapPath;
- copy.artist = item.artist;
- copy.album = item.album;
- copy.duration = item.duration;
- copy.mimeType = item.mimeType;
- copy.sampleRate = item.sampleRate;
- copy.trackCount = item.trackCount;
- copy.lastPlayedStr = item.lastPlayedStr;
- copy.playCount = item.playCount;
- copy.lyricContent = item.lyricContent;
- copy.md5Str = item.md5Str;
- copy.extra_json = item.extra_json;
- copy.pyStr = item.pyStr;
- copy.bit_rate = item.bit_rate;
- copy.probe_score = item.probe_score;
- copy.year = item.year;
- copy.nb_streams = item.nb_streams;
- copy.nb_programs = item.nb_programs;
- copy.genre = item.genre;
- copy.track = item.track;
- copy.bits_per_raw_sample = item.bits_per_raw_sample;
- copy.channels = item.channels;
- copy.channel_layout = item.channel_layout;
- copy.start_time = item.start_time;
- copy.ALBUMARTIST = item.ALBUMARTIST;
- copy.COMPOSER = item.COMPOSER;
- copy.LYRICIST = item.LYRICIST;
- copy.COMMENT = item.COMMENT;
- copy.disc = item.disc;
- copy.webdav_account_id = item.webdav_account_id;
- copy.remote_rel_path = item.remote_rel_path;
- return copy;
- }
- /**
- * 异步设置videoUrl的辅助方法,处理WebDAV URL的构建
- * @param song 歌曲对象
- * @returns Promise<string> 完整的URL
- */
- /**
- * 设置videoUrl,通过webdav_account_id设置完整的 URL
- * @param song 歌曲对象
- * @returns Promise<string> 完整的URL
- */
- async function setVideoUrlForSong(song: VideoItem, options?: MetadataExtractionOptions): Promise<string> {
- const metadataOptions = options ?? {};
- if (isWebDavType(song.type) && song.webdav_account_id) {
- try {
- Logger.info(TAG, `WebDAV 路径信息 remote_rel_path: ${song.remote_rel_path}`);
- Logger.info(TAG, `WebDAV 路径信息 filePath: ${song.filePath}`);
- const relativePath = song.remote_rel_path || song.filePath;
- const manager = RemoteDriveManager.getInstance();
- const account = await manager.getWebDavAccountById(song.webdav_account_id);
- if (account) {
- const cachePath = await findWebDavCacheIfExists(account, relativePath);
- if (cachePath) {
- Logger.info(TAG, `WebDAV 缓存命中,直接播放: ${cachePath}`);
- scheduleMetadataExtractionFromCache(song, cachePath, metadataOptions);
- return cachePath;
- }
- const fullUrlFromAccount = WebDavUrlUtil.buildFullUrl(account, relativePath);
- if (fullUrlFromAccount) {
- const sanitizedUrl = sanitizePlaybackUrl(fullUrlFromAccount);
- const downloadPromise = triggerWebDavCacheDownload(account, relativePath, sanitizedUrl);
- if (downloadPromise) {
- downloadPromise.then((completedPath?: string | null) => {
- if (completedPath) {
- scheduleMetadataExtractionFromCache(song, completedPath, metadataOptions);
- }
- }).catch((error: Error) => {
- Logger.error(TAG, `WebDAV 缓存后台下载失败: ${error.message}`);
- });
- }
- Logger.info(TAG, `WebDAV 启动异步缓存: ${relativePath}`);
- return sanitizedUrl;
- }
- }
- const fallbackUrl = await WebDavUrlUtil.buildFullUrlByAccountId(song.webdav_account_id, relativePath);
- if (fallbackUrl) {
- Logger.warn(TAG, `WebDAV 使用全局查询到的URL: ${fallbackUrl}`);
- return sanitizePlaybackUrl(fallbackUrl);
- }
- Logger.error(TAG, `WebDAV URL构建失败,使用原始路径: ${relativePath}`);
- return sanitizePlaybackUrl(relativePath);
- } catch (error) {
- Logger.error(TAG, `WebDAV URL构建出错: ${(error as Error).message}`);
- const fallbackPath = song.remote_rel_path || song.filePath;
- return sanitizePlaybackUrl(fallbackPath);
- }
- }
- if (isNavidromeType(song.type) && song.webdav_account_id) {
- try {
- const manager = RemoteDriveManager.getInstance();
- const account = await manager.getWebDavAccountById(song.webdav_account_id);
- if (!account) {
- throw new Error('Navidrome账号不可用');
- }
- const navSongId = song.remote_rel_path || song.id || song.filePath;
- const streamUrl = await navidromeApi.buildStreamUrl(account, navSongId);
- Logger.info(TAG, `Navidrome 流地址构建成功: ${streamUrl}`);
- return sanitizePlaybackUrl(streamUrl);
- } catch (error) {
- const err = error as Error;
- Logger.error(TAG, `Navidrome URL构建失败: ${err.message}`);
- throw new Error(err.message);
- }
- }
- if (isSmbType(song.type) && song.webdav_account_id) {
- try {
- const manager = RemoteDriveManager.getInstance();
- const account = await manager.getWebDavAccountById(song.webdav_account_id);
- if (!account) {
- throw new Error('SMB账号不可用');
- }
- const relativePath = extractSmbRelativePath(song, account.smbShare);
- const cachedPath = await ensureSmbFileCached(account, relativePath);
- Logger.info(TAG, `SMB 缓存路径: ${cachedPath}`);
- scheduleMetadataExtractionFromCache(song, cachedPath, metadataOptions);
- return cachedPath;
- } catch (error) {
- const err = error as Error;
- Logger.error(TAG, `SMB 缓存失败: ${err.message}`);
- throw new Error(err.message);
- }
- }
- if (isWebDavType(song.type)) {
- Logger.warn(TAG, `WebDAV歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
- return sanitizePlaybackUrl(song.filePath);
- }
- if (isSmbType(song.type)) {
- Logger.warn(TAG, `SMB歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
- return song.filePath;
- }
- if (isNavidromeType(song.type)) {
- throw new Error('Navidrome歌曲缺少webdav_account_id,无法构建播放链接');
- }
- return song.filePath;
- }
- // 定义接口
- interface HiCarAspectRatio {
- ratio: number;
- name: string;
- }
- 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;
- }
- const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
- const ITEM_HEIGHT: number = 65; // 列表项中高度
- const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
- //功能强大的音乐播放器
- @Preview
- @Component
- export struct LocalMusic {
- // 字母表
- @State alphaBet: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
- 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
- @State alphaBetStyle: GlobalAlphabetIndexerModifier = new GlobalAlphabetIndexerModifier()
- @State selectAlphaBetIndex: number = 0
- @State isShowAlphaBet: boolean = false
- @State isScrolling: boolean = false
- @State isTouchingAlphaBet: boolean = false
- @State alphabetHeight: number = 0
- public enableShowAlphabet: boolean = true // 是否显示字母表
- @State isShowPrecious: boolean = false //播控条显示上一首按钮
- //背景两侧流光控制器
- @State sceneBgController: HdsSceneController|undefined = deviceInfo.sdkApiVersion>=20
- &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
- new HdsSceneController()
- .setSceneParams({
- backgroundMaskColors: [Color.Green, Color.Red],
- firstEdgeFlowLight: {
- startPos: 0,
- endPos: 0.5,
- color: Color.Red
- },
- secondEdgeFlowLight: {
- startPos: 0,
- endPos: -0.5,
- color: Color.Green
- }
- }) : undefined;
- //背景流光控制器
- @State bgController: hdsEffect.ShaderEffectController|undefined = deviceInfo.sdkApiVersion>=20
- &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
- new hdsEffect.ShaderEffectController():undefined;
- @State showAddSheet:boolean = false
- searchController: SearchController = new SearchController()
- @State rightTopImage:Resource = $r('sys.symbol.sort')
- @State isEditAudio:boolean = false
- @State isExtractAcc:boolean = false
- @State isConverter:boolean = false
- @State isAIVoiceSeparation:boolean = false
- @State isExtractAudio:boolean = false
- @State isMergeAudio:boolean = false
- @State isCopyFileToDownLoad: boolean = false
- @State isChangeTone:boolean = false
- @State offHeight: number = 75
- @State currentSongList: Array<VideoItem> = []//当前歌单
- @Consume currentSongListName:string //当前歌单名称
- @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
- @State isRefreshing: boolean = false;
- @State maxRefreshingHeight: number = 100.0;
- private contentNode?: ComponentContent<Object> = undefined;
- // WebDAV相关实例变量(现在改为从内存读取,不再需要存储)
- @State ratioL: number = 1;
- @State mediaKuCount: number = 0;
- @State albumCount: number = 0;
- @State artistCount: number = 0;
- @State fastForwardSeconds: string = '10'
- @State isShowBackFast: boolean = true//快进快退按钮
- @State isCanAuto:boolean = true
- @State opacityValueImage: number = 1;
- @State tipPopup:boolean = false
- @Consume mType: number;
- @StorageProp('themeColor') themeColor: string =
- PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
- themeMode: number = 0;
- @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))
- private playlistTable: PlaylistTable | null = null
- private deletionWatcher: FileDeletionWatcher | null = null
- @State allPlaylists: Playlist[] = []
- @State isZero: boolean = false
- @State fileList: Array<string> = []
- @State dirList: Array<VideoItem> = []
- @Consume videoLocalList:VideoItem[]
- @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
- @State listRefreshKey: number = 0
- // @State mediaKuList: Array<VideoItem> = []; //媒体库文件
- @StorageProp('mediaKuList') 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
- private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
- @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 @Watch('onTopBarhange')isShowTitleBar: boolean = true //是否显示分类导航条
- @State isShowAllBar: boolean = true //是否显示播放全部条
- @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
- @State isShowHistory: boolean = true //是否显示最近播放
- @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
- @State isGridMusic: boolean = false //是否网格布局
- @State isCircleBtn: boolean = false //是否圆形播放按钮
- @State twoFingerType: number = 3 //双支放大缩小的类型
- @State isScrollHide: boolean = false //是否滚动隐藏
- @State isSameTimePlay: boolean = false //是否和其他app同时播放
- @State isStartAutoPlay: boolean = false //启动后自动播放
- @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
- @State isShowHeader: boolean = true
- @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
- @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
- @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
- @State isSwipe: boolean = false //listItem的左滑开关
- @State openSkipSongAnimate: boolean = true//切歌动画效果
- @State customizeBgPath: string | undefined = '';
- @State isDarkMode: boolean = false
- @State lyricTextWeight: number = 400
- @State lyricTextWeightPip: number = 400
- @State currentSwiperIndex: number = 0
- @State blurValue: number = 0 //背景模糊
- @State bgBrightness: number = 0 //背景亮度
- private listScroller: ListScroller = new ListScroller()
- private playListScroller: Scroller = new Scroller()
- @State isOneKeyTags:boolean = false
- @State isFixMessy:boolean = false
- @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
- @StorageProp('topSafeHeight') topSafeHeight: number = 0;
- @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
- @StorageProp('windowWidth') windowWidth: number = 0;
- @StorageProp('windowHeight') windowHeight: number = 0;
- @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
- @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
- private UNKONWN:string = '';
- private listArea: Area = {
- width: 0,
- height: 0,
- position: {},
- globalPosition: {}
- }
- @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
- ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
- // WebDAV认证信息缓存(作为实例变量,比全局上下文更可靠)
- private currentWebDavAuthInfo: WebDavAuthItem | null = null;
- //瀑布流的列数横竖屏动态切换
- onIsLandscapeChange() {
- if(this.isLandscape){
- this.columns = 4
- }else{
- this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
- }
- }
- onColorModeChange() {
- this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
- }
- //bar导航条显示状态变化,不显示的话把topBarHeight=0
- onTopBarhange(){
- if(this.isShowTitleBar){
- console.log('onecold 导航条显示')
- this.topBarHeight = 50
- this.offHeight = 75
- }else{
- console.log('onecold 导航条隐藏')
- this.topBarHeight = 0
- if(this.twoFingerType!=4){
- this.offHeight = 30
- }
- }
- }
- //点击某个歌单id发生变化的时候回调
- onIDChange(){
- console.log('onecold 歌单id发生变化this.currentSongListID='+this.currentSongListID)
- console.log('onecold 歌单id发生变化this.currentSongListName='+this.currentSongListName)
- if(this.modeType==4){
- this.isShowTitleBar = false
- this.titleName = this.currentSongListName
- this.rightTopImage = $r('sys.symbol.sort')
- //获取缓存
- const cacheSongs:string =PreferencesUtil.getStringSync(this.currentSongListID+'currentSongList', '')
- console.log('onecold 歌单id发生变化获取缓存2 cacheSongs = '+cacheSongs)
- if(StrUtil.isNotEmpty(cacheSongs)){
- this.currentSongList = JSON.parse(cacheSongs) as VideoItem[]
- this.updateListData(this.currentSongList, true)
- }
- this.doSongListTask()//获取歌单信息
- }
- }
- async doSongListTask() {
- // 初始化歌单数据库
- const playlistTable = new PlaylistTable(this.context);
- // 查询歌单中的所有歌曲
- const playlistSongs: PlaylistSong[] = await playlistTable.queryPlaylistSongs(this.currentSongListID);
- console.log('onecold 歌单id发生变化获取缓存7 playlistSongs='+playlistSongs.length)
- if (ArrayUtil.isEmpty(playlistSongs)) {
- this.updateListData([], true)
- } else {
- this.currentSongList = await convertPlaylistSongsToVideoItems(this.context, playlistSongs);
- console.log('onecold 从数据库读取的歌曲为 playlistSongs='+this.currentSongList.length)
- this.updateListData(this.currentSongList, true)
- if (ArrayUtil.isNotEmpty(this.currentSongList)&&this.currentSongList.length > 100) {
- // 只保存前100条记录到缓存中
- let canceList = this.currentSongList.slice(0, 100);
- PreferencesUtil.putSync(this.currentSongListID+'currentSongList',
- JSON.stringify(canceList))
- } else {
- PreferencesUtil.putSync(this.currentSongListID+'currentSongList', JSON.stringify(this.currentSongList));
- }
- }
- this.isRefreshing = false
- }
- onModeChange() {
- this.isFavMusic = false
- this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, false)
- switch (this.modeType) {
- case 0:
- this.getSortedFiles(this.currentPath)
- break
- case 1:
- this.rightTopImage = $r('sys.symbol.sort')
- this.updateListData(this.mediaKuList)
- this.titleName = Utility.resourceToString(this.context,$r('app.string.media_ku'))
- break
- case 2:
- this.rightTopImage = $r('sys.symbol.sort')
- this.updateListData(this.artistList)
- this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
- break
- case 3:
- this.rightTopImage = $r('sys.symbol.sort')
- this.updateListData(this.albumList)
- this.titleName = 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;
- @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 favList: Array<VideoItem> = []
- @Consume isFavMusic: boolean
- @State isClickedPLayAll: boolean = false;
- private scrollerForlist: ListScroller = new ListScroller();
- private knockController: KnockController | undefined = undefined;
- // 修改为:
- imagesF: ImageFrameInfo[] = CommonConstants.IMAGE_FRAME_INFO;
- @StorageProp('animationState') 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 = this.getUIContext().getHostContext() as common.UIAbilityContext
- doSwipBack() {
- if(this.isSearchMode){
- console.info('onecold doSwipBack = ' +this.isSearchMode)
- this.isSearchMode = false
- if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
- this.searchText = ''
- this.getSortedFiles(this.currentPath)
- return
- }
- this.onSearchInput('')
- return
- }
- this.isZero = false
- if (this.modeType !== 0 && this.isCanBack) {
- this.onModeChange()
- this.isCanBack = false
- // 返回专辑列表时恢复滚动偏移量,支持列表和网格
- setTimeout(() => {
- if (this.modeType == 2) {
- if (this.isGridMusic||this.twoFingerType==4) {
- let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
- let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
- if(this.twoFingerType==4){
- this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
- }else{
- this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
- }
- } else {
- let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
- this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
- }
- } else if (this.modeType == 3) {
- if (this.isGridMusic||this.twoFingerType==4) {
- let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
- let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 0
- if(this.twoFingerType==4){
- this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
- }else{
- this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
- }
- } else {
- let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
- this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
- }
- }
- }, 200)
- 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 = !this.isShowDrawer
- this.offsetX = 0
- })
- return
- }
- //返回上一级歌单的滚动位置
- setTimeout(() => {
- if (this.modeType == 0) {
- if (this.isGridMusic||this.twoFingerType==4) {
- let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
- let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
- if(this.twoFingerType==4){
- this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
- }else{
- this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
- }
- } else {
- let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
- this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
- }
- }
- }, 300)
- this.currentPath = Utility.getParentDirectory(this.currentPath)
- Logger.info('this.currentPath2 = ' + this.currentPath)
- this.getSortedFiles(this.currentPath)
- }
- // 组件生命周期
- aboutToAppear() {
- console.info('onecold aboutToAppear sdkApiVersion = '+deviceInfo.sdkApiVersion)
- if(ArrayUtil.isNotEmpty(this.videoLocalList)&&this.modeType==0){
- this.updateListData(this.videoLocalList)
- }
- // 初始化 PlaylistTable
- this.playlistTable = new PlaylistTable(getContext(this))
- this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
- this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
- if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
- this.tipPopup = !this.tipPopup
- PreferencesUtil.putSync('isFirstTiped',false)
- }
- this.initSetting()
- this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
- Utility.getAppName(getContext(this)).then((appName: string) => {
- this.appName = appName
- })
- this.packName = AppUtil.getBundleName()
- this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
- this.loadCacheFromStorage(); // 加载文件夹缓存
- // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
- this.initLoadCache()
- this.mkDownLoadDir()
- let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
- // 监听广播事件(打开其他应用处理)
- emitter.on(eventMusic, (eventData: emitter.EventData) => {
- this.saveVideoDatas([eventData.data?.message], true)
- });
- //侧滑广播接收时间
- let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
- // 监听广播事件(打开其他应用处理)
- emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
- animateTo({ duration: 555 }, () => {
- this.doSwipBack()
- })
- });
- //ScanFilePage广播接收时间
- let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
- // 监听ScanFilePage广播事件(更新数据库)
- emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
- this.doUpdateData()
- });
- // 监听歌单播放请求事件
- let eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY }
- emitter.on(eventPlaylistPlay, async (eventData: emitter.EventData) => {
- const data = eventData.data as Record<string, Object>
- if (!data) {
- Logger.error('heanup eventPlaylistPlay: eventData.data is undefined or null')
- return
- }
- // 检查歌单播放数据结构
- if (data.playlistId && data.songFilePaths && data.startIndex !== undefined) {
- const playlistData: PlaylistEventData = {
- playlistId: data.playlistId as string,
- playlistName: data.playlistName as string,
- songCount: data.songCount as number,
- startIndex: data.startIndex as number,
- songFilePaths: data.songFilePaths as string[]
- }
- await this.handlePlaylistPlayRequest(
- playlistData.playlistId,
- playlistData.playlistName,
- playlistData.songFilePaths,
- playlistData.startIndex
- )
- return
- }
- Logger.error('heanup eventPlaylistPlay: 接收到无效的数据结构')
- });
- let eventRefreshSort: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_REFRESH_SORT }
- // 监听广播事件(通用设置配置更新)
- emitter.on(eventRefreshSort, (eventData: emitter.EventData) => {
- if(this.modeType ==4){
- this.doSongListTask()//获取歌单信息
- }
- });
- let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
- // 监听广播事件(通用设置配置更新)
- emitter.on(eventSetting, (eventData: emitter.EventData) => {
- this.doChangeSetting()
- });
- let event: Callback<InterruptEvent> = (event) => {
- // LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
- console.info(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
- this.savePlaybackPosition()
- if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
- this.pause();
- } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
- console.info(`onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
- console.info('onecold startPlayOrResumePlay 514')
- this.startPlayOrResumePlay();
- } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
- this.stop();
- }
- }
- this.mIjkMediaPlayer.on('audioInterrupt', event);
- // 音频设备断连回调处理
- // let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
- // LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
- // if (event.reason === DeviceChangeReason.REASON_NEW_DEVICE_AVAILABLE) { // 音频设备连接
- //
- // } else if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
- // this.pause();
- // }
- // }
- // // 订阅音频设备断开和连接事件
- // this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
- const eventPause: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_PAUSE }
- // 监听广播事件(hicar断开暂停播放)
- emitter.on(eventPause, (eventData: emitter.EventData) => {
- this.pause();
- });
- this.makeWorker()
- //折叠屏的屏幕显示模式变化
- display.on('foldDisplayModeChange', (data) => {
- this.doChangeBarHeight()
- });
- display.on('foldStatusChange', (data) => {
- Logger.info('onecold foldStatusChange ')
- });
- this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
- // 读取 themeMode 并同步 currentColorMode
- this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
- this.applyThemeMode(this.themeMode)
- let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
- AppStorage.setOrCreate('themeColor', themeColor);
- this.themeColor = themeColor;
- this.doChangeSetting()
- this.windowClass.on('windowSizeChange', (size) => {
- LogUtil.info('onecold windowSizeChange')
- this.doChangeBarHeight()
- let viewWidth = px2vp(size.width);
- let viewHeight = px2vp(size.height);
- if(this.isPhoneLan()){
- this.is_auto_hide_progress = false
- if(this.isHiCar()){
- return
- }
- setTimeout(() => {
- this.is_auto_hide_progress = true
- }, 6000)
- }else{
- this.startAutoHide()
- }
- });
- this.eventHub.on('onStateChange', (fg: boolean) => {
- if (fg && this.curState === 'STARTED') {
- this.stopPip();
- }
- });
- }
- //载入媒体库,艺术家,专辑等缓存
- initLoadCache(){
- this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
- this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
- this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
- let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
- let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
- if(ArrayUtil.isNotEmpty(cachedList)){
- this.mediaKuList = cachedList
- if(this.modeType==1){
- this.updateListData(this.mediaKuList)
- }
- }
- let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
- let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
- if(ArrayUtil.isNotEmpty(artistCachedList)){
- this.artistList = artistCachedList
- let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
- const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
- this.artistMap = new Map(parsedArray);
- // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
- if(this.modeType==2){
- this.updateListData(this.artistList)
- }
- }
- let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
- let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
- if(ArrayUtil.isNotEmpty(albumCachedList)){
- this.albumList = albumCachedList
- let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
- const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
- this.albumMap = new Map(parsedArray);
- if(this.modeType==3){
- this.updateListData(this.albumList)
- }
- }
- }
- startAutoHide() {
- if(this.isHiCar()){
- return
- }
- if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
- console.info('onecold startAutoHide')
- this.is_auto_hide_progress = false
- setTimeout(() => {
- this.is_auto_hide_progress = true
- }, 6000)
- }
- }
- applyThemeMode(mode: number) {
- let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
- if (mode === 1) {
- colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
- } else if (mode === 2) {
- colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
- }
- AppStorage.setOrCreate('currentColorMode', colorMode)
- AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
- PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
- AppStorage.setOrCreate('themeMode', mode)
- this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
- // 只有强制浅色/深色时才主动设置
- const context = getContext(this) as common.UIAbilityContext
- context.getApplicationContext().setColorMode(colorMode)
- }
- initSetting() {
- this.isShowPrecious = PreferencesUtil.getBooleanSync('isShowPrecious', false)
- 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, '')
- this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, false)
- this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
- this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
- this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
- this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
- this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
- this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
- this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
- this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, false)
- this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
- this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 2)
- this.isCoverTop = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP, true)
- this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
- this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
- this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
- this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
- this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
- this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
- this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
- this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
- this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
- this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
- this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
- this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
- this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
- this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
- this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
- this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
- this.isCopyFileToDownLoad = PreferencesUtil.getBooleanSync(SettingPage.IS_COPYFILE_TO_DOWNLOAD, false)
- if(this.volumeSmall){
- this.volume = 0.5
- }else{
- this.volume = 1
- }
- //如果是hicar连接状态,这些都是false
- if(this.isHiCar()){
- this.isShowTitleBar = false//不显示导航栏
- this.columns=4
- if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
- {
- this.isShowHeader = false//二级菜单不显示头部
- this.isGridMusic= false//用list不用网格
- this.isCoverTopBig = false
- }
- this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
- }
- if (this.isSavePlayMode) {
- this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
- }
- }
- doChangeSetting() {
- this.initSetting()
- this.deleteCache(this.currentPath)
- if (this.modeType === 0) {
- this.getSortedFiles(this.currentPath)
- }
- }
- doChangeBarHeight() {
- if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
- (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
- this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
- this.setBarHeightNormal()
- }
- }
- onPageShow() {
- this.knockController?.immersiveListening();
- app.setImageCacheCount(100);
- // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
- app.setImageRawDataCacheSize(104857600);
- Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
- }
- //开启线程查看各个数据库
- makeWorker() {
- setTimeout(() => {
- if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
- ToastUtil.showToast('请到文件扫描页面导入音乐!')
- //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
- // workerInstance.postMessage({
- // code: 1,
- // data1: this.context,
- // data2: this.rootPath,
- // data3: this.lockPath,
- // data4: PreferencesUtil.getStringSync('COVER_API', ''),
- // data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
- // });
- PreferencesUtil.putSync('isFirstApp', false)
- } else {
- workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
- workerInstance.postMessage({ code: 3, data: this.context });
- workerInstance.postMessage({ code: 4, data: this.context });
- this.getHistoryList(false)
- }
- }, 1000)
- workerInstance.onmessage = (e: MessageEvents): void => {
- switch (e.data.code) {
- case 101: //第一次扫描文件夹入库
- ToastUtil.showToast('刷新同步数据库成功!')
- Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
- this.doAllUpdateData()
- break;
- case 102: //查询媒体库列表
- this.isRefreshing = false
- this.mediaKuList = e.data.data
- Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
- Utility.doSortListAscending(this.mediaKuList)
- AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
- if (this.modeType === 1) {
- this.updateListData(this.mediaKuList)
- }
- PreferencesUtil.putSync('mediaKuCount', this.mediaKuList.length)
- // 处理媒体库前100条记录,列表长度并存储到PreferencesUtil
- if (ArrayUtil.isNotEmpty(this.mediaKuList)&&this.mediaKuList.length > 100) {
- // 只保存前100条记录到缓存中
- let truncatedList = this.mediaKuList.slice(0, 100);
- PreferencesUtil.putSync('mediaKuList', JSON.stringify(truncatedList));
- } else {
- PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
- }
- break;
- case 103: //收到查询艺术家列表
- this.isRefreshing = false
- this.artistMap = e.data.data1;
- this.artistList = e.data.data2;
- PreferencesUtil.putSync('artistCount', this.artistList.length)
- // 处理艺术家前100条记录,列表长度并存储到PreferencesUtil
- if (ArrayUtil.isNotEmpty(this.artistList)&&this.artistList.length > 100) {
- // 只保存前100条记录到缓存中
- let truncatedList = this.artistList.slice(0, 100);
- PreferencesUtil.putSync('artistList', JSON.stringify(truncatedList));
- } else {
- PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
- }
- // 处理并缓存前60条艺术家数据
- const sortedEntries = Array.from(this.artistMap.entries())
- .sort((a, b) => b[1].length - a[1].length)
- .slice(0, 60);
- PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
- break;
- case 104: //收到查询专辑列表
- this.isRefreshing = false
- this.albumMap = e.data.data1;
- this.albumList = e.data.data2
- //查询完毕在启动是否自动播放
- if (this.isStartAutoPlay&&this.isCanAuto) {
- this.isCanAuto = false
- console.info('onecold startPlayOrResumePlay 757')
- this.startPlayOrResumePlay()
- }
- PreferencesUtil.putSync('albumCount', this.albumList.length)
- // 处理专辑前100条记录,列表长度并存储到PreferencesUtil
- if (ArrayUtil.isNotEmpty(this.albumList)&&this.albumList.length > 100) {
- // 只保存前100条记录到缓存中
- let truncatedList = this.albumList.slice(0, 100);
- PreferencesUtil.putSync('albumList', JSON.stringify(truncatedList));
- } else {
- PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
- }
- const mapArrayAlbum = Array.from(this.albumMap.entries())
- .sort((a, b) => b[1].length - a[1].length)
- .slice(0, 60);
- PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
- break;
- case 105: // 缓存完成后返回的元数据
- this.handleWorkerMetadataPayload(e.data.data as WorkerMetadataPayload);
- break;
- case 106: // 编辑音乐元数据和封面完成
- this.handleEditMusicResult(e.data);
- break;
- }
- };
- // 在调用terminate后,执行onexit
- workerInstance.onexit = (code) => {
- metadataExtractionInFlight.clear();
- Logger.info(TAG, 'workerInstance 线程已退出,code: ' + code);
- }
- workerInstance.onerror = (err: ErrorEvent) => {
- metadataExtractionInFlight.clear();
- console.error('workerInstance 线程执行发生异常: ' + err.message)
- }
- }
- private handleWorkerMetadataPayload(payload: WorkerMetadataPayload | undefined): void {
- if (!payload || !payload.originFilePath) {
- return;
- }
- metadataExtractionInFlight.delete(payload.originFilePath);
- if (payload.error) {
- Logger.warn(TAG, `缓存文件元数据解析失败: ${payload.error}`);
- return;
- }
- this.applyMetadataToCollections(payload.originFilePath, payload);
- }
- private applyMetadataToCollections(filePath: string, payload: WorkerMetadataPayload): void {
- const targets: Array<VideoItem> = [];
- if (this.currentSong && this.currentSong.filePath === filePath) {
- targets.push(this.currentSong);
- }
- const collectFromList = (list?: Array<VideoItem>) => {
- if (!list || list.length === 0) {
- return;
- }
- const found = Utility.getItemByFilePath(list, filePath);
- if (found) {
- targets.push(found);
- }
- };
- collectFromList(this.songList);
- collectFromList(this.videoLocalList);
- collectFromList(this.historyList);
- collectFromList(this.favList);
- const remoteManager = RemoteDriveManager.getInstance();
- collectFromList(remoteManager.webDavSongs);
- const updated = new Set<VideoItem>();
- const webDavUpdates: Map<string, WebDavMetadataUpdatePayload> = new Map();
- for (let i = 0; i < targets.length; i++) {
- const target = targets[i];
- if (!target || updated.has(target)) {
- continue;
- }
- updated.add(target);
- this.mergeVideoItemWithPayload(target, payload);
- if (target.type === CommonConstants.TYPE_WEBDAV && StrUtil.isNotEmpty(target.filePath)) {
- webDavUpdates.set(target.filePath, {
- filePath: target.filePath,
- pixelMapPath: target.pixelMapPath,
- name: target.name,
- artist: target.artist
- });
- }
- }
- if (this.currentSong && this.currentSong.filePath === filePath) {
- this.mergeVideoItemWithPayload(this.currentSong, payload);
- if (payload.name) {
- this.name = payload.name;
- }
- if (payload.artist) {
- this.artist = payload.artist;
- }
- if (payload.pixelMapPath) {
- this.cover = payload.pixelMapPath;
- }
- if (payload.lyricContent) {
- this.applyInlineLyricContent(payload.lyricContent);
- }
- this.currentSong = cloneVideoItem(this.currentSong);
- AppStorage.setOrCreate('currentSong', this.currentSong);
- }
- const primaryTarget = targets.length > 0 ? targets[0] : undefined;
- if (primaryTarget) {
- this.persistRemoteMetadataToDb(primaryTarget).catch((error: Error) => {
- Logger.error(TAG, `缓存元数据持久化失败: ${error.message}`);
- });
- }
- if (webDavUpdates.size > 0) {
- const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
- emitter.emit(eventUpdate, { data: Array.from(webDavUpdates.values()) });
- }
- }
- private handleEditMusicResult(result: WorkerEditMusicResult): void {
- // 关闭进度条
- DialogHelper.closeLoading();
- if (result.success) {
- console.log("heanup 编辑信息成功,数据库已同步");
- if (result.coverResult) {
- ToastUtil.showToast('内嵌封面成功');
- }
- ToastUtil.showToast('内嵌音乐标签成功');
- this.isShowMoreView = false;
- this.name = this.titleStr;
- // 同步当前播放的歌曲信息
- if (this.editingItem && this.editingItem.filePath == this.currentSong?.filePath) {
- this.currentSong.name = this.titleStr;
- this.artist = this.artistStr;
- this.currentSong.artist = this.artistStr;
- this.currentSong.album = this.ablumStr;
- this.currentSong.year = this.yearStr;
- this.currentSong.genre = this.genreStr;
- this.currentSong.track = this.trackStr;
- this.currentSong.lyricContent = this.lyricConStr;
- this.currentSong.ALBUMARTIST = this.albumArtistStr;
- this.currentSong.COMPOSER = this.composerStr;
- this.currentSong.LYRICIST = this.lyricistStr;
- this.currentSong.COMMENT = this.commentStr;
- }
- // if (result.needRefreshList && this.modeType == 0) {
- // this.deleteCache(this.currentPath);
- // this.getSortedFiles(this.currentPath);
- // }
- // 同步编辑字段到本地列表
- if (this.editingItem) {
- this.syncEditedFields(this.editingItem);
- this.syncListsAfterEdit(this.editingItem.filePath);
- this.doUpateEditedFields(this.editingItem);
- }
- // 清理临时变量
- this.longItemFilePath = '';
- this.tempLyricContent = '';
- this.isShowEdit = false;
- this.imagePathStr = '';
- } else {
- console.error("heanup 编辑信息失败: " + result.error);
- ToastUtil.showToast('编辑失败: ' + (result.error || '未知错误'));
- // 清理临时变量
- this.longItemFilePath = '';
- this.tempLyricContent = '';
- this.isShowEdit = false;
- this.imagePathStr = '';
- }
- }
- private assignStringMetadata(target: VideoItem, key: keyof VideoItem, value?: string | null, allowEmpty = false): void {
- if (value === undefined || value === null) {
- return;
- }
- const text = value.toString();
- if (!allowEmpty && text.trim().length === 0) {
- return;
- }
- Reflect.set(target, key as string, value);
- }
- private assignNumberMetadata(target: VideoItem, key: keyof VideoItem, value?: number | null): void {
- if (value === undefined || value === null || Number.isNaN(value)) {
- return;
- }
- Reflect.set(target, key as string, value);
- }
- private mergeVideoItemWithPayload(target: VideoItem, payload: WorkerMetadataPayload): void {
- if (!target || !payload) {
- return;
- }
- this.assignStringMetadata(target, 'name', payload.name);
- this.assignStringMetadata(target, 'artist', payload.artist);
- this.assignStringMetadata(target, 'album', payload.album);
- this.assignStringMetadata(target, 'bit_rate', payload.bit_rate);
- this.assignStringMetadata(target, 'duration', payload.duration);
- this.assignStringMetadata(target, 'sampleRate', payload.sampleRate);
- this.assignStringMetadata(target, 'mimeType', payload.mimeType);
- this.assignStringMetadata(target, 'size', payload.size);
- this.assignStringMetadata(target, 'pixelMapPath', payload.pixelMapPath);
- this.assignStringMetadata(target, 'lyricContent', payload.lyricContent, true);
- this.assignStringMetadata(target, 'genre', payload.genre);
- this.assignStringMetadata(target, 'track', payload.track);
- this.assignStringMetadata(target, 'bits_per_raw_sample', payload.bits_per_raw_sample);
- this.assignStringMetadata(target, 'channels', payload.channels);
- this.assignStringMetadata(target, 'channel_layout', payload.channel_layout);
- this.assignStringMetadata(target, 'start_time', payload.start_time);
- this.assignStringMetadata(target, 'year', payload.year);
- this.assignStringMetadata(target, 'disc', payload.disc);
- this.assignStringMetadata(target, 'ALBUMARTIST', payload.ALBUMARTIST);
- this.assignStringMetadata(target, 'COMPOSER', payload.COMPOSER);
- this.assignStringMetadata(target, 'LYRICIST', payload.LYRICIST);
- this.assignStringMetadata(target, 'COMMENT', payload.COMMENT, true);
- this.assignNumberMetadata(target, 'videoSize', payload.videoSize);
- this.assignNumberMetadata(target, 'probe_score', payload.probe_score);
- this.assignNumberMetadata(target, 'nb_streams', payload.nb_streams);
- this.assignNumberMetadata(target, 'nb_programs', payload.nb_programs);
- }
- private mergeVideoItemFromSource(target: VideoItem, source: VideoItem): void {
- if (!target || !source) {
- return;
- }
- this.assignStringMetadata(target, 'name', source.name);
- this.assignStringMetadata(target, 'artist', source.artist);
- this.assignStringMetadata(target, 'album', source.album);
- this.assignStringMetadata(target, 'bit_rate', source.bit_rate);
- this.assignStringMetadata(target, 'duration', source.duration);
- this.assignStringMetadata(target, 'sampleRate', source.sampleRate);
- this.assignStringMetadata(target, 'trackCount', source.trackCount);
- this.assignStringMetadata(target, 'mimeType', source.mimeType);
- this.assignStringMetadata(target, 'size', source.size);
- this.assignStringMetadata(target, 'pixelMapPath', source.pixelMapPath);
- this.assignStringMetadata(target, 'lyricContent', source.lyricContent, true);
- this.assignStringMetadata(target, 'genre', source.genre);
- this.assignStringMetadata(target, 'track', source.track);
- this.assignStringMetadata(target, 'bits_per_raw_sample', source.bits_per_raw_sample);
- this.assignStringMetadata(target, 'channels', source.channels);
- this.assignStringMetadata(target, 'channel_layout', source.channel_layout);
- this.assignStringMetadata(target, 'start_time', source.start_time);
- this.assignStringMetadata(target, 'year', source.year);
- this.assignStringMetadata(target, 'disc', source.disc);
- this.assignStringMetadata(target, 'ALBUMARTIST', source.ALBUMARTIST);
- this.assignStringMetadata(target, 'COMPOSER', source.COMPOSER);
- this.assignStringMetadata(target, 'LYRICIST', source.LYRICIST);
- this.assignStringMetadata(target, 'COMMENT', source.COMMENT, true);
- this.assignNumberMetadata(target, 'videoSize', source.videoSize);
- this.assignNumberMetadata(target, 'probe_score', source.probe_score);
- this.assignNumberMetadata(target, 'nb_streams', source.nb_streams);
- this.assignNumberMetadata(target, 'nb_programs', source.nb_programs);
- if (source.remote_rel_path && StrUtil.isEmpty(target.remote_rel_path)) {
- target.remote_rel_path = source.remote_rel_path;
- }
- }
- private async hydrateRemoteSongFromDb(item: VideoItem | undefined): Promise<void> {
- if (!item || !isRemoteCloudType(item.type)) {
- return;
- }
- const storagePath = item.remote_rel_path || WebDavUrlUtil.toStoragePath(item.filePath);
- if (!storagePath) {
- return;
- }
- try {
- const cached = await this.table.queryVideoByFilePath(storagePath);
- if (!cached) {
- return;
- }
- this.mergeVideoItemFromSource(item, cached);
- if (StrUtil.isEmpty(item.remote_rel_path)) {
- item.remote_rel_path = storagePath;
- }
- if (item === this.currentSong) {
- if (StrUtil.isNotEmpty(item.name)) {
- this.name = item.name;
- }
- if (StrUtil.isNotEmpty(item.artist)) {
- this.artist = item.artist!;
- }
- if (StrUtil.isNotEmpty(item.pixelMapPath)) {
- this.cover = item.pixelMapPath!;
- }
- if (StrUtil.isNotEmpty(item.lyricContent) && StrUtil.isEmpty(this.lyricContent)) {
- this.applyInlineLyricContent(item.lyricContent as string);
- }
- }
- } catch (error) {
- Logger.error(TAG, `hydrateRemoteSongFromDb 失败: ${(error as Error).message}`);
- }
- }
- private applyInlineLyricContent(content: string): void {
- if (StrUtil.isEmpty(content)) {
- return;
- }
- this.lyricContent = content;
- const lines = content.split('\n').map(line => line.trim());
- const lyric = this.parser.parse(lines);
- this.lyricController.setLyric(lyric);
- this.lyricControllerXF.setLyric(lyric);
- this.lyricControllerSingle.setLyric(lyric);
- }
- private extractParentPathFromStoragePath(path: string): string {
- if (!path) {
- return '';
- }
- const lastSlash = path.lastIndexOf('/');
- if (lastSlash <= 0) {
- return '';
- }
- return path.substring(0, lastSlash);
- }
- private async persistRemoteMetadataToDb(target: VideoItem): Promise<void> {
- if (!this.context || !target || !isWebDavType(target.type)) {
- return;
- }
- const storagePath = target.remote_rel_path || WebDavUrlUtil.toStoragePath(target.filePath);
- if (!storagePath) {
- return;
- }
- target.remote_rel_path = target.remote_rel_path || storagePath;
- const table = new MediaTable(this.context);
- await new Promise<void>((resolve) => {
- table.getRdbStore(this.context as Context, () => resolve());
- });
- const cloneItem = cloneVideoItem(target);
- cloneItem.filePath = storagePath;
- cloneItem.remote_rel_path = storagePath;
- cloneItem.parentPath = this.extractParentPathFromStoragePath(storagePath);
- await table.saveOrUpdateWebDavItem(cloneItem);
- }
- onPageHide(): void {
- this.knockController?.immersiveDisableListening();
- }
- @State isFirstStartPlay: boolean = false
- private async startFileDeletionWatcher(): Promise<void> {
- if (!this.rootPath) {
- return;
- }
- if (!this.deletionWatcher) {
- this.deletionWatcher = new FileDeletionWatcher(this.context, this.table);
- }
- try {
- await this.deletionWatcher.watchDirectories([
- this.rootPath,
- this.lockPath,
- this.favPath,
- this.historyPath
- ]);
- } catch (error) {
- Logger.error(TAG, `初始化文件删除监听失败: ${(error as Error).message}`);
- }
- }
- //获取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
- PreferencesUtil.putSync('download_path', this.rootPath+'/')
- this.currentPath = this.rootPath
- 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)
- }
- // await this.startFileDeletionWatcher();
- this.getSortedFiles(this.rootPath).then(async () => {
- this.isFavMusic = false
- //穿山甲
- // this.loadBannerAd(CSJUtil.getBannerID())
- 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.isFirstStartPlay = true
- this.sonDataSource.pushArrayData(this.songList)
- if (this.currentSong === undefined) {
- this.isFirstStartPlay = false
- this.currentSong = this.songList[0]
- }
- // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
- this.videoUrl = await setVideoUrlForSong(this.currentSong, {
- context: this.context,
- autoParseMusicName: this.autoParseMusicName
- });
- Logger.info(TAG, `WebDAV URL同步构建完成: ${this.videoUrl}`);
- this.name = this.currentSong.name
- this.cover = this.currentSong.pixelMapPath
- AppStorage.setOrCreate('currentSong',this.currentSong) ;
- } else {
- this.name = '空空如也'
- }
- })
- 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)
- }
- })
- }
- getHistoryList(isRefresh: boolean) {
- this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
- this.historyList = result
- // for (let i = 0; i < this.historyList.length; i++) {
- //
- // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
- // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
- // }
- if (isRefresh) {
- this.videoLocalList = this.historyList
- this.updateListData(this.videoLocalList, true)
- }
- })
- }
- // 组件消失生命周期
- aboutToDisappear() {
- console.info('LifeCycleComponent aboutToDisappear');
- this.deletionWatcher?.stop();
- this.knockController?.immersiveDisableListening();
- this.curIndex = 0
- emitter.off(EventConstants.EVENT_AUDIO_OPEN);
- emitter.off(EventConstants.EVENT_SCAN_UPDATE);
- emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
- emitter.off(EventConstants.EVENT_SETTING_UPDATE);
- this.mDestroyPage = true;
- this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
- if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
- this.stop();
- }
- this.mIjkMediaPlayer.off('audioInterrupt');
- if (workerInstance) {
- workerInstance.terminate();
- }
- this.stopPip();
- this.destroyPipController()
- }
- async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean,openItem?:VideoItem) {
- this.isFavMusic = false
- console.info('onecold getSortedFiles 1 curPath '+curPath)
- if (isWorkerPost) {
- workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
- }
- if (this.modeType !== 0) {
- return
- }
- console.info('onecold getSortedFiles 2')
- this.isCanBack = false
- this.currentPath = curPath
- console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
- this.titleName = getFileDirName(this.currentPath,this.rootPath)
- if (curPath === this.rootPath) {
- this.rightTopImage = $r('sys.symbol.sort')
- } else {
- this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
- if (this.rootPath === Utility.getParentDirectory(curPath)) {
- this.rightTopImage = $r('sys.symbol.chevron_left')
- }
- }
- // 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.isRefreshing) {
- // this.videoLocalList = cachedValue;
- Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
- if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
- this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
- }
- this.isRefreshing = false
- 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,
- '')
- if (this.isShowDir(item.name)) {
- directories.push(item);
- }
- // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
- // Utility.doSortListAscending(directories)
- } else {
- if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
- 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)) {
- if (this.currentPath != this.rootPath) {
- if (files) {
- this.currentTitleCover = Utility.getFirstCoverFromList(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].name}`);
- }
- // this.setButtonStatus()
- this.openMusic(isOpen, destPath,openItem)
- this.isRefreshing = false
- });
- }
- //第三方app打开天天静听导入音乐后播放
- openMusic(isOpen?: boolean, destPath?: string,openItem?:VideoItem){
- if (isOpen&&destPath) {
- 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
- }
- if(openItem){
- this.doPlay(openItem,0,false,true)
- // this.isShowPlay = true
- this.setShowPlayTrue()
- }
- }
- }
- //扫描文件夹入库
- 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, this.autoParseMusicName);
- mediaItems.push(mediaItem);
- this.table.insert(mediaItem, (id: number) => {
- });
- }
- }
- }
- return mediaItems;
- }
- updateListData(mList: Array<VideoItem>, noSort?: boolean) {
- animateTo({ duration: 666 }, () => {
- this.opacityItem = 0.5;
- });
- 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: 666 }, () => {
- this.opacityItem = 1;
- });
- //添加到字母索引表
- this.setAlphaBet()
- this.setButtonStatus()
- }, 200);
- }
- getCurFileList(): Array<VideoItem> {
- if(this.isSearchMode){
- return this.filteredList
- }
- 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
- }
- }
- @Builder
- SortMenuBuilder() {
- Menu() {
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
- content: "按艺术家升序"
- })
- .onClick(async () => {
- this.doSortType(0)
- PreferencesUtil.put(SettingPage.SORT_TYPE, 0)
- this.updateListData(this.videoLocalList, true)
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
- content: "按艺术家降序"
- })
- .onClick(async () => {
- this.doSortType(1)
- PreferencesUtil.put(SettingPage.SORT_TYPE, 1)
- this.updateListData(this.videoLocalList, true)
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat_size_square')),
- content: "按专辑升序"
- })
- .onClick(async () => {
- this.doSortType(2)
- PreferencesUtil.put(SettingPage.SORT_TYPE, 2)
- this.updateListData(this.videoLocalList, true)
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.character_arrow_clockwise')),
- content: "按专辑降序"
- })
- .onClick(async () => {
- this.doSortType(3)
- PreferencesUtil.put(SettingPage.SORT_TYPE, 3)
- this.updateListData(this.videoLocalList, true)
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
- content: $r('app.string.sort_by_name')
- })
- .onClick(async () => {
- this.doSortType(4)
- PreferencesUtil.put(SettingPage.SORT_TYPE, 4)
- this.updateListData(this.videoLocalList, true)
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
- content: '按名称降序'
- })
- .onClick(async () => {
- this.doSortType(5)
- PreferencesUtil.put(SettingPage.SORT_TYPE, 5)
- this.updateListData(this.videoLocalList, true)
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
- content: $r('app.string.sort_by_time')
- })
- .onClick(async () => {
- this.doSortType(6)
- PreferencesUtil.put(SettingPage.SORT_TYPE, 6)
- this.updateListData(this.videoLocalList, true)
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
- content: '按添加时间降序'
- })
- .onClick(async () => {
- this.doSortType(7)
- PreferencesUtil.put(SettingPage.SORT_TYPE, 7)
- this.updateListData(this.videoLocalList, true)
- })
- }.attributeModifier(new MenuModifier())
- }
- @Builder
- SortMenuForArtistAblumBuilder() {
- Menu() {
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
- content: $r('app.string.sort_by_name')
- })
- .onClick(async () => {
- this.doSortType(4)
- // PreferencesUtil.put(SettingPage.SORT_TYPE, 2)
- this.updateListData(this.videoLocalList, true)
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
- content: '按名称降序'
- })
- .onClick(async () => {
- this.doSortType(5)
- this.updateListData(this.videoLocalList, true)
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
- content: '按数量升序'
- })
- .onClick(async () => {
- this.doSortType(8)
- this.updateListData(this.videoLocalList, true)
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
- content: '按数量降序'
- })
- .onClick(async () => {
- this.doSortType(9)
- this.updateListData(this.videoLocalList, true)
- })
- }.attributeModifier(new MenuModifier())
- }
- 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,this.isShowFileName)
- break;
- case 5:
- Utility.doSortListDescending(this.videoLocalList,this.isShowFileName)
- 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;
- case 8:
- this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
- // 1. Sort by type first
- const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
- if (typeOrder !== 0) {
- return typeOrder;
- }
- // 2. Then sort by artist count (numeric comparison)
- let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
- if(this.modeType === 2){
- sortMap = this.artistMap
- }else{
- sortMap = this.albumMap
- }
- const aArtistCount: number = sortMap.get(a.name)?.length || 0;
- const bArtistCount: number = sortMap.get(b.name)?.length || 0;
- return aArtistCount - bArtistCount;
- });
- break;
- case 9:
- this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
- // 1. Sort by type first
- const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
- if (typeOrder !== 0) {
- return typeOrder;
- }
- let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
- if(this.modeType === 2){
- sortMap = this.artistMap
- }else{
- sortMap = this.albumMap
- }
- const aArtistCount: number = sortMap.get(a.name)?.length || 0;
- const bArtistCount: number = sortMap.get(b.name)?.length || 0;
- return bArtistCount - aArtistCount;
- });
- 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: [
- { 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') },
- ],
- 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;
- case 3:
- this.goSelectMusic()
- break;
- }
- }
- })
- }
- //拉起音频
- goSelectMusic() {
- if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
- DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
- DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
- ) {
- ToastUtil.showToast('暂时不支持该设备')
- return
- }
- try {
- let documentSelectOptions = new picker.DocumentSelectOptions();
- documentSelectOptions.authMode = true
- documentSelectOptions.multiAuthMode = true
- if( deviceInfo.sdkApiVersion>=21){//如果api大于21 ,可以支持1w首歌以上
- documentSelectOptions.maxSelectNumber = 20000
- }
- documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
- let documentPicker = new picker.DocumentViewPicker(this.context);
- documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
- if (documentSelectResult !== null && documentSelectResult !== undefined) {
- this.saveVideoDatas(documentSelectResult)
- }
- console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
- JSON.stringify(documentSelectResult));
- }).catch((err: BusinessError) => {
- console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
- });
- } catch (error) {
- let err: BusinessError = error as BusinessError;
- console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
- }
- }
- async showTips() {
- try {
- this.getUIContext().getPromptAction().showDialog({
- title: '导入指南',
- message:'用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
- + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
- '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
- '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后去文件扫描一下。\n',
- buttons: [
- {
- text: '知道了',
- color: '#000000'
- },
- ]
- }, (err, data) => {
- if (err) {
- console.error('showDialog err: ' + err);
- return;
- }
- console.info('showDialog success callback, click button: ' + data.index);
- });
- } catch (error) {
- let message = (error as BusinessError).message;
- let code = (error as BusinessError).code;
- console.error(`showDialog args error code is ${code}, message is ${message}`);
- };
- // 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;
- }
- console.info('onecold this.isCopyFileToDownLoad = ' + this.isCopyFileToDownLoad);
- if(this.isCopyFileToDownLoad||this.currentPath==this.lockPath||isOpen){
- this.saveVideoDatasToDownLoad(uris,isOpen)
- return
- }
- // 初始化进度条
- 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')
- });
- // 计算处理总数用于进度计算
- const totalItems = uris.length;
- let processedItems = 0;
- for (let i = 0; i < uris.length; i++) {
- let filePath = uris[i];
- try {
- 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, this.autoParseMusicName);
- console.info('onecold saveVideoDatas filePath = ' + filePath)
- if (!filePath.includes(this.rootPath)) {
- console.info('onecold saveVideoDatas mediaItem.parentPath111 = ' + mediaItem.parentPath)
- mediaItem.parentPath = this.currentPath;
- }
- console.info('onecold saveVideoDatas mediaItem.parentPath = ' + mediaItem.parentPath)
- this.table.insert(mediaItem, (id: number) => {
- // 插入完成回调
- });
- }
- }
- // 更新进度
- processedItems++;
- this.progress = Math.floor((processedItems / totalItems) * 100);
- DialogHelper.updateLoading(' 正在处理', this.progress);
- } catch (error) {
- Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
- // 即使出错也更新进度
- processedItems++;
- this.progress = Math.floor((processedItems / totalItems) * 100);
- DialogHelper.updateLoading(' 正在处理', this.progress);
- }
- }
- // 关闭进度条
- DialogHelper.closeLoading();
- this.isZero = false
- // 删除目标路径缓存
- setTimeout(() => {
- this.cache.delete(this.currentPath);
- this.getSortedFiles(this.currentPath,false,uris[0],isOpen)
- this.setButtonStatus()
- }, 500);
- }
- async saveVideoDatasToDownLoad(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: this.themeColor,
- fontColor: this.themeColor
- });
- // 计算所有文件的总大小
- 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, this.autoParseMusicName);
- this.table.insert(mediaItem, (id: number) => {
- // 删除目标路径缓存
- this.cache.delete(this.currentPath);
- this.getSortedFiles(this.currentPath, true, destPath, isOpen,mediaItem)
- });
- }
- }
- } 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));
- // }
- //
- //
- //
- // }
- async goSelectImage(item: VideoItem): Promise<string | undefined> {
- if (!item) {
- return undefined;
- }
- try {
- let selectUris: Array<string> = [];
- let photoPicker = new photoAccessHelper.PhotoViewPicker();
- let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
- photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
- photoSelectOptions.maxSelectNumber = 1;
- const photoSelectResult = await photoPicker.select(photoSelectOptions);
- selectUris = photoSelectResult.photoUris;
- console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
- let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
- console.info('file fd: ' + file.fd);
- let name = await MD5.digestSync(this.videoUrl)+'.jpg'
- 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);
- if (item.filePath == this.currentSong?.filePath) {
- this.cover = imagePath
- }
- if (item) {
- item.pixelMapPath = imagePath
- }
- this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
- if (success) {
- this.doUpdateData()
- console.log("onecold 更新音乐封面成功,数据库已同步");
- } else {
- console.error("onecold 更新音乐封面数据库失败原因: " + error);
- }
- });
- LogUtil.debug("onecold this.cover =" + this.cover)
- return FileUtil.getFilePath(imagePath); // Return the image path here
- } catch (err) {
- console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
- return undefined;
- }
- }
- // 拉起picker选择文件管理器
- async callFilePickerSelectFile(): Promise<void> {
- try {
- let DocumentSelectOptions = new picker.DocumentSelectOptions();
- if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
- DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
- } else {
- DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
- }
- 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));
- }
- }
- //重命名的对话框
- showReNameDialog(item: VideoItem, index: string, filePath: string) {
- if(!item.filePath.includes(this.packName)){
- ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限重命名')
- return
- }
- 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.color = this.themeColor
- 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, this.autoParseMusicName);
- 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)// .setHeight(this.isCoverOpacity()?100:420)
- .setBackgroundColor(Color.Black)
- .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
- .show()
- } else {
- pup = XPopup.Builder()
- .setPopupPosition(popupPosition)
- .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
- .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.color = this.themeColor
- 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, this.autoParseMusicName);
- 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
- if (this.isDarkMode) {
- pup = XPopup.Builder()
- .setPopupPosition(popupPosition)
- .atView(id)
- .setMaxHeight('60%')
- .setBackgroundColor(Color.Black)
- .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
- .show();
- } else {
- pup = XPopup.Builder()
- .setPopupPosition(popupPosition)
- .atView(id)
- .setMaxHeight('60%')
- .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, this.autoParseMusicName);
- this.videoLocalList[index] = mediaItem;
- }
- this.cache.delete(this.currentPath)
- this.getSortedFiles(this.currentPath, true)
- }).catch((error: BusinessError) => {
- console.error(error.message);
- });
- }
- build() {
- Stack() {
- this.ContentBuild()
- Stack() {
- this.PlayController()
- }
- .hitTestBehavior(HitTestMode.Transparent)
- .opacity(this.barBottomOpacity)
- .width('90%')
- .borderRadius(20)
- .margin({ bottom:DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_2IN1
- ? 30 :this.bottomSafeHeight })
- .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
- .backgroundImage( this.cover)
- .visibility(this.isMultiSelect ? Visibility.None : Visibility.Visible)
- .backgroundImageSize( { width: '100%' })
- .opacity(0.9)
- .clickEffect({ level: ClickEffectLevel.HEAVY })
- }
- .alignContent(Alignment.Bottom)
- .width('100%')
- .height('100%')
- }
- @Builder
- ContentBuild() {
- Scroll() {
- Column() {
- Stack() {
- //libraryname加上去后onKeyEvent监听不了,因为目前的解决方案是上面的XComponent,去掉libraryname
- XComponent({ id: 'for_onKeyEvent',type: XComponentType.SURFACE,
- controller: this.xcomponentController })
- .onLoad(async (event?: object) => {
- })
- .focusable(true)
- .height(0)
- .focusOnTouch(true)
- .defaultFocus(true) // 自动获取键盘焦点
- .onKeyEvent((event?: KeyEvent) => {
- console.info('onecold点击 onKeyEvent')
- // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
- if (!event || event.type !== KeyType.Down) {
- return;
- }
- console.info('onecold点击 onKeyEvent event.keyCode: ' + event.keyCode)
- //空格键 Space key controls pause/play
- if (event.keyCode === KeyCode.KEYCODE_SPACE|| event.keyCode === KeyCode.KEYCODE_MEDIA_PLAY_PAUSE) {
- this.playOrPause()
- }
- if (event.keyCode === KeyCode.KEYCODE_DPAD_UP) {
- this.playPrevious()
- }
- if (event.keyCode === KeyCode.KEYCODE_DPAD_DOWN) {
- this.playNext()
- }
- // Right-click to fast forward
- if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
- this.fastForward()
- }
- // Left-click to rewind
- if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
- this.backForward()
- }
- })
- 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)
- .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
- height:this.isLandscape?'80%': '43%',
- dragBar: true,
- showClose: true,
- preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
- blurStyle:BlurStyle.Thin,
- backgroundColor:Color.Transparent,
- title: { title: 'AB循环' }
- })
- Stack() {
- Column() {
- if(this.twoFingerType==4){
- this.getWaterView()
- }else{
- if(this.isGridMusic){
- this.getGridView()
- }else {
- this.getList()
- }
- }
- if (this.modeType ==0||this.modeType==4) {
- Column() {
- emptyView(this.themeColor)
- }
- .position({ top: 200 })
- .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
- .animation({ duration: 500 }),
- TransitionEffect.scale({ x: 0, y: 0 })))
- .justifyContent(FlexAlign.Center)
- .opacity(this.isZero ? 1 : 0)
- .visibility(this.isZero && !this.isFavMusic && !this.isHistory
- ? Visibility.Visible : Visibility.None)
- .animation({
- duration: 500,
- curve: 'ease-in-out' // 可选动画曲线
- })
- .width('100%')
- }
- }
- .layoutWeight(1)
- .height('100%')
- // 右侧居中的字母表索引
- this.indexBuilder()
- this.topTitleBar()
- }
- .alignContent(Alignment.Top)
- .layoutWeight(1)
- .height('100%')
- Row() {
- Button(this.isAllSelected ? '反选' : '全选', { type: ButtonType.Circle, stateEffect: true })
- .width(45)
- .height(45)
- .fontSize(10)
- .margin({ top: 10, bottom: 10, right: 6 })
- .backgroundColor(this.themeColor)
- .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
- .onClick(() => {
- if (this.isAllSelected) {
- // 全不选
- this.selectedFiles = [];
- } else {
- // 全选
- this.selectedFiles = [...this.getCurFileList()];
- }
- this.isAllSelected = !this.isAllSelected;
- })
- Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
- .width(72)
- .height(45)
- .fontSize(10)
- .margin({ top: 10, bottom: 10, right: 6 })
- .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
- .backgroundColor(this.themeColor)
- .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
- transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
- })
- .onClick(() => {
- // if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
- this.isOneKeyTags = !this.isOneKeyTags
- // }else{
- // ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限批量内嵌')
- // }
- })
- Button('合并', { type: ButtonType.Circle, stateEffect: true })
- .width(45)
- .height(45)
- .fontSize(10)
- .margin({ top: 10, bottom: 10, right: 6 })
- .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
- .backgroundColor(this.themeColor)
- .bindContentCover($$this.isMergeAudio, this.MergeAudioBuilder(), {
- transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
- })
- .onClick(() => {
- if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
- this.isMergeAudio = !this.isMergeAudio
- }else{
- ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限合并')
- }
- })
- Button('+歌单', { type: ButtonType.Circle, stateEffect: true })
- .width(45)
- .height(45)
- .fontSize(10)
- .margin({ top: 10, bottom: 10, right: 6 })
- .backgroundColor(this.themeColor)
- .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
- .onClick(async () => {
- this.longItemFilePath = ''
- await this.openAddToPlaylistDialog(this.selectedFiles)
- })
- // Button('乱码', { type: ButtonType.Circle, stateEffect: true })
- // .width(45)
- // .height(45)
- // .fontSize(10)
- // .margin({ top: 10, bottom: 10, right: 6 })
- // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
- // .backgroundColor(this.themeColor)
- // .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
- // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
- // })
- // .onClick(() => {
- // this.isFixMessy = !this.isFixMessy
- // })
- // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
- // .width('35%')
- // .height(60)
- // .id('music_cut')
- // .margin({ top: 10, bottom: 10, right: 6 })
- // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
- // .backgroundColor(this.themeColor)
- // .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(this.themeColor)
- // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
- // .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(this.themeColor)
- // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
- // .onClick(() => {
- // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
- // })
- Button('删除', { type: ButtonType.Circle, stateEffect: true })
- .width(45)
- .height(45)
- .fontSize(10)
- .margin({ top: 10, bottom: 10, right: 6 })
- .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
- .backgroundColor(this.themeColor)
- .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
- .onClick(() => {
- this.showWarnIsDelete()
- })
- Button('取消', { type: ButtonType.Circle, stateEffect: true })
- .width(45)
- .height(45)
- .fontSize(10)
- .margin({ top: 10, bottom: 10, right: 6 })
- .backgroundColor(this.themeColor)
- .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
- .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: 20 }) // 将 Row 固定在底部
- }
- .width('100%')
- .height('100%')
- .alignContent(Alignment.Top)
- }
- .width('100%')
- .height('100%')
- .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
- .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
- .backgroundImagePosition(Alignment.Center)
- .backdropBlur(this.blurValue)
- .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
- .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
- }
- }
- //字母表索引
- @Builder
- indexBuilder(){
- if(this.enableShowAlphabet){
- Column({space: 5}){
- if(this.isShowAlphaBet){
- AlphabetIndexer({arrayValue: this.alphaBet,selected: this.selectAlphaBetIndex})
- .attributeModifier(this.alphaBetStyle)
- .usingPopup(this.isTouchingAlphaBet)
- .onAreaChange((old_value,new_value)=>{
- this.alphabetHeight = new_value.height as number
- })
- .popupPosition({
- x: 40,
- y: this.alphabetHeight / 2
- })
- .onSelect((index: number) => {
- this.onSelectIndexItem(this.alphaBet[index])
- })
- .onTouch((event: TouchEvent) =>{
- this.isShowAlphaBet = true
- if(event.type === TouchType.Up || event.type === TouchType.Cancel){
- this.isTouchingAlphaBet = false
- }else{
- this.isTouchingAlphaBet = true
- }
- })
- .transition(
- TransitionEffect.translate({x: 10})
- .combine(TransitionEffect.opacity(0.1))
- .animation({
- duration: 150,
- curve: Curve.EaseInOut,
- })
- )
- }else{
- Blank()
- .layoutWeight(1)
- }
- // ListLocateButton()
- // .onClick(() =>{
- // this.locateSong()
- // })
- // .clickEffect({level:ClickEffectLevel.LIGHT,scale: 0.5})
- // .margin({
- // bottom: 10
- // })
- }
- .padding({
- bottom: 0
- })
- .position({x:'92%'})
- .height('100%')
- .justifyContent(FlexAlign.Center)
- }
- }
- onSelectIndexItem(letter: string) {
- let songs = this.videoLocalList
- let targetIndex = -1;
- for (let i = 0; i < songs.length; i++) {
- let song = songs[i]
- let text = this.isShowFileName?song.fileName:song.name
- if(this.sortType === 0||this.sortType==1){
- text = song.artist
- }else if(this.sortType === 2||this.sortType==3){
- text = song.album
- }
- if(text){
- let firstPinyin = getFirstLetter(text)
- if (firstPinyin&&firstPinyin === letter) {
- targetIndex = i;
- break;
- }
- }
- }
- if (targetIndex !== -1) {
- this.listScroller.scrollToIndex(targetIndex);
- }
- }
- // 找到对应字母表的索引
- findAlphaBetIndex(song: VideoItem):number{
- let text = this.isShowFileName?song.fileName:song.name
- if(this.sortType === 0||this.sortType==1){
- text = song.artist
- }else if(this.sortType === 2||this.sortType==3){
- text = song.album
- }
- if(text){
- let firstLetter = getFirstLetter(text)
- for(let i=0;i<this.alphaBet.length;i++){
- if(this.alphaBet[i] === firstLetter){
- return i
- }
- }
- }
- return 0
- }
- async setAlphaBet(){
- return new Promise<void>((resolve,reject) => {
- try {
- let songs = this.videoLocalList
- if(songs.length > 40000){
- this.alphaBet = []
- resolve()
- return
- }
- let alphabetSet = new Set<string>();
- for (let song of songs) {
- let text = this.isShowFileName?song.fileName:song.name
- if(this.sortType === 0||this.sortType==1){
- text = song.artist
- }else if(this.sortType === 2||this.sortType==3){
- text = song.album
- }
- if(text){
- let firstPinyin = getFirstLetter(text)
- if(!alphabetSet.has(firstPinyin)){
- alphabetSet.add(firstPinyin)
- }
- }
- // const pyStr = song.pyStr
- // if(pyStr){
- // if(!alphabetSet.has(pyStr)){
- // alphabetSet.add(pyStr)
- // }
- // }
- }
- this.alphaBet = Array.from(alphabetSet).sort((a,b)=>{
- if(this.sortType ===4||this.sortType==0||this.sortType==2||this.sortType==6){
- return a.localeCompare(b)
- }else{
- return b.localeCompare(a)
- }
- })
- if(this.videoLocalList.length > 0){
- this.listScroller.scrollToIndex(0)
- this.selectAlphaBetIndex = 0
- }
- resolve()
- }catch (e) {
- console.error('testTag','排序字母表出错',JSON.stringify(e))
- resolve()
- }
- })
- }
- @Builder
- topTitleBar(){
- Column() {
- Row({ space: 15 }) {
- if (!this.isSearchMode ) {
- //左侧滑动按钮
- Button({ type: ButtonType.Circle, stateEffect: true }) {
- SymbolGlyph(this.rightTopImage)
- .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
- }
- .attributeModifier(new ButtonFancyModifier(40, 40))
- .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
- .animation({ duration: 300, curve: Curve.Ease })
- .onClick(() => {
- this.doSwipBack()
- })
- .attributeModifier(new ShadowModifier())
- .zIndex(0)
- }else{
- //左侧搜索返回按钮
- Button({ type: ButtonType.Circle, stateEffect: true }) {
- SymbolGlyph($r('sys.symbol.chevron_left'))
- .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
- }
- .attributeModifier(new ButtonFancyModifier(40, 40))
- .margin({bottom:5})
- .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
- .animation({ duration: 300, curve: Curve.Ease })
- .onClick(() => {
- this.isSearchMode = false
- if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
- this.searchText = ''
- this.getSortedFiles(this.currentPath)
- return
- }
- this.onSearchInput('')
- })
- .attributeModifier(new ShadowModifier())
- .zIndex(0)
- }
- if (!this.isSearchMode) {
- Text(this.titleName)
- .margin({left:3,right:10})
- .fontColor($r('app.color.text_color'))
- .fontSize(this.twoFingerType==3?19:this.twoFingerType==2?17:15)
- .maxLines(1)
- .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
- .layoutWeight(1)
- .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
- }
- //搜索框
- Search({ controller: this.searchController,value: this.searchText, placeholder: '搜索标题、艺术家...' })
- .searchButton('搜索',{fontColor:this.themeColor})
- .searchIcon({
- src: $r('sys.media.ohos_ic_public_search_filled')
- })
- .cancelButton({
- style: CancelButtonStyle.CONSTANT,
- icon: {
- src: $r('sys.media.ohos_ic_public_cancel_filled')
- }
- })
- .layoutWeight(1)
- .height(40)
- .maxLength(20)
- .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
- .placeholderColor(Color.Grey)
- .placeholderFont({ size: 14, weight: 400 })
- .textFont({ size: 14, weight: 400 })
- .onSubmit((value: string) => {
- console.log('onecold onSubmit ='+value)
- this.searchController.stopEditing()
- this.onSearchInput(this.searchText);
- })
- .onChange((value: string) => {
- console.log('onecold onChange ='+value)
- this.onSearchInput(value);
- })
- .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
- .animation({ duration: 300, curve: Curve.Ease })
- //搜索按钮
- if (!this.isSearchMode) {
- Button({ type: ButtonType.Circle, stateEffect: true }) {
- SymbolGlyph($r('sys.symbol.magnifyingglass'))
- .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
- }
- .attributeModifier(new ButtonFancyModifier(40, 40))
- .animation({ duration: 300, curve: Curve.Ease })
- .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
- .attributeModifier(new ShadowModifier())
- .zIndex(0)
- .onClick(()=>{
- this.isSearchMode = true
- })
- //排序按钮
- Button({ type: ButtonType.Circle, stateEffect: true }) {
- SymbolGlyph($r('sys.symbol.list_number'))
- .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
- }
- .attributeModifier(new ButtonFancyModifier(40, 40))
- .animation({ duration: 300, curve: Curve.Ease })
- .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
- .bindMenu((this.modeType==2&&!this.isCanBack)||(this.modeType==3&&!this.isCanBack)
- ?this.SortMenuForArtistAblumBuilder:this.SortMenuBuilder)
- .attributeModifier(new ShadowModifier())
- .zIndex(0)
- //添加按钮
- Button({ type: ButtonType.Circle, stateEffect: true }) {
- SymbolGlyph($r('sys.symbol.plus'))
- .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
- }
- .attributeModifier(new ButtonFancyModifier(40, 40))
- .animation({ duration: 300, curve: Curve.Ease })
- .visibility(this.modeType==0||this.modeType==1?Visibility.Visible:Visibility.None)
- .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
- .bindSheet($$this.showAddSheet, this.addSheet(), {
- height: SheetSize.FIT_CONTENT,
- dragBar: true,
- showClose: true,
- preferType: SheetType.CENTER ,
- title: {
- title: '导入音乐'
- }
- })
- .onClick(() => {
- this.showAddSheet = !this.showAddSheet;
- })
- .attributeModifier(new ShadowModifier())
- .zIndex(0)
- }
- }
- }
- .padding({ top: this.topSafeHeight+10, left: 10, right: 10 })
- .width('100%')
- }
- @Builder
- addSheet() {
- Scroll() {
- Column() {
- Column() {
- Row() {
- Text('导入音乐复制到DownLoad目录')
- .margin({ left: 18 })
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .fontWeight(480)
- .layoutWeight(1)
- Toggle({ type: ToggleType.Switch, isOn: this.isCopyFileToDownLoad })
- .selectedColor(this.themeColor)
- .switchPointColor(Color.White)
- .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
- .margin({ right: 18 })
- .onChange((checked: boolean) => {
- this.isCopyFileToDownLoad = checked;
- PreferencesUtil.put(SettingPage.IS_COPYFILE_TO_DOWNLOAD, this.isCopyFileToDownLoad)
- })
- .width(50)
- .height(30);
- }
- .height(88)
- }
- .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
- .backgroundColor($r('app.color.start_window_background'))
- .borderRadius(15)
- .margin({
- left: 30,
- right: 30,
- top: 10,
- bottom: 10
- })
- .padding(0)
- .border({
- color: Color.White,
- width: 1.8
- })
- Menu() {
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder_badge_plus')),
- content: "新建文件夹"
- })
- .backgroundColor($r('app.color.silvery'))
- .border({
- width: { bottom: 1 },
- color: '#12ec5c87'
- })
- .margin(10)
- .padding({left:15,right:15})
- .onClick(async () => {
- this.showMkDialog()
- this.showAddSheet = !this.showAddSheet
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder')),
- content: $r('app.string.import_from_files')
- })
- .padding({left:15,right:15})
- .backgroundColor($r('app.color.silvery'))
- .border({
- width: { bottom: 1 },
- color: '#12ec5c87'
- })
- .margin(10)
- .onClick(async () => {
- this.callFilePickerSelectFile()
- this.showAddSheet = !this.showAddSheet
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square')),
- content: '全选导入'
- // content: '从下载文件夹导入(路径:Download/' +
- // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
- })
- .padding({left:15,right:15})
- .backgroundColor($r('app.color.silvery'))
- .border({
- width: { bottom: 1 },
- color: '#12ec5c87'
- })
- .margin(10)
- .onClick(async () => {
- this.goSelectMusic()
- this.showAddSheet = !this.showAddSheet
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.save')),
- content: '自动导入教程'
- // content: '从下载文件夹导入(路径:Download/' +
- // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
- })
- .padding({left:15,right:15})
- .backgroundColor($r('app.color.silvery'))
- .border({
- width: { bottom: 1 },
- color: '#12ec5c87'
- })
- .margin(10)
- .onClick(async () => {
- this.showTips()
- this.showAddSheet = !this.showAddSheet
- })
- }.attributeModifier(new MenuModifier())
- .margin({bottom:30})
- }
- .layoutWeight(1)
- }
- }
- @Builder
- TagsContentCoverBuilder() {
- Scroll() {
- Column() {
- TagsContentCover(
- {
- selectedFiles:this.selectedFiles,
- isOneKeyTags:this.isOneKeyTags,
- table:this.table,
- onTagsResult:(result: boolean,deleteCache_path?:string)=>{
- this.isMultiSelect = false
- if(result){//如果嵌入成功,更新数据
- setTimeout(()=>{
- this.doUpdateData()
- },500)
- }
- console.info('onecold onTagsResult deleteCache_path =' +deleteCache_path)
- if(deleteCache_path){
- this.deleteCache(deleteCache_path)
- }
- }
- }
- )
- }
- }
- .width('100%')
- .height('100%')
- }
- @Builder
- FixMessyViewBuilder() {
- Scroll() {
- Column() {
- FixMessyView(
- {
- selectedFiles:this.selectedFiles,
- isFixMessy:this.isFixMessy,
- onFixResult:(result: boolean)=>{
- this.isMultiSelect = false
- if(result){//如果嵌入成功,更新数据
- this.deleteCache(this.currentPath)
- this.doUpdateData()
- }
- }
- }
- )
- }
- }
- .width('100%')
- .height('100%')
- }
- //剪辑音频
- @Builder
- EditAudioBuilder(item:VideoItem) {
- Scroll() {
- Column() {
- EditAudio(
- {
- mVideoItem:item,
- currentPath:this.currentPath,
- videoUrl:this.videoUrl,
- CONTROL_PlayStatus:this.CONTROL_PlayStatus,
- currentTime:this.currentTime,
- progressValue:this.progressValue,
- onBack:()=>{
- this.isEditAudio = !this.isEditAudio
- },
- onSeeOutputPath:(outPutPath:string)=>{
- this.isEditAudio = !this.isEditAudio
- this.longItemFilePath = ''
- this.modeType = 0
- this.isShowFileName = true
- this.getSortedFiles(FileUtil.getParentPath(outPutPath))
- },
- onPlayOrPause:()=>{
- if(this.videoUrl==item.filePath){
- this.playOrPause()
- }else{//如果不是当前播放的,则播放该文件
- this.videoUrl==item.filePath
- this.doPlay(item,0,false,true)
- }
- },
- onSliderChange:(value:number)=>{
- if(this.videoUrl!=item.filePath){
- this.videoUrl==item.filePath
- return
- }
- 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 + "");
- LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
- this.isSeekTo = false;
- },
- onResult:(result: boolean,outPath:string)=>{
- if(result){//如果剪辑成功,更新数据
- this.doUpdateData()
- }else{
- ToastUtil.showToast('剪辑失败')
- }
- }
- }
- )
- }
- }
- .width('100%')
- .height('100%')
- }
- //提取伴奏
- @Builder
- ConverterBuilder(item:VideoItem) {
- Scroll() {
- Column() {
- AudioFormatConverter(
- {
- mVideoItem:item,
- videoUrl:this.videoUrl,
- currentPath:this.currentPath,
- CONTROL_PlayStatus:this.CONTROL_PlayStatus,
- currentTime:this.currentTime,
- progressValue:this.progressValue,
- onBack:()=>{
- this.isConverter = !this.isConverter
- this.longItemFilePath = ''
- },
- onPlayOrPause:()=>{
- if(this.videoUrl==item.filePath){
- this.playOrPause()
- }else{//如果不是当前播放的,则播放该文件
- this.videoUrl==item.filePath
- this.doPlay(item,0,false,true)
- }
- },
- onSeeOutputPath:(outPutPath:string)=>{
- this.isConverter = !this.isConverter
- this.longItemFilePath = ''
- this.modeType = 0
- this.isShowFileName = true
- this.getSortedFiles(FileUtil.getParentPath(outPutPath))
- },
- onSliderChange:(value:number)=>{
- if(this.videoUrl!=item.filePath){
- this.videoUrl==item.filePath
- return
- }
- this.isSeekTo = true;
- this.mDestroyPage = false;
- this.showLoadIng();
- let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
- this.seekTo(seekValue + "");
- this.isSeekTo = false;
- },
- onResult:(result: boolean,outPath:string)=>{
- if(result){//如果成功,更新数据
- this.doUpdateData()
- }else{
- ToastUtil.showToast('格式转化失败')
- }
- }
- }
- )
- }
- }
- .width('100%')
- .height('100%')
- }
- //提取伴奏
- @Builder
- ExtractAccBuilder(item:VideoItem) {
- Scroll() {
- Column() {
- ExtractAccompaniment(
- {
- mVideoItem:item,
- currentPath:this.currentPath,
- videoUrl:this.videoUrl,
- CONTROL_PlayStatus:this.CONTROL_PlayStatus,
- currentTime:this.currentTime,
- progressValue:this.progressValue,
- onBack:()=>{
- this.isExtractAcc = !this.isExtractAcc
- this.longItemFilePath = ''
- },
- onPlayOrPause:()=>{
- if(this.videoUrl==item.filePath){
- this.playOrPause()
- }else{//如果不是当前播放的,则播放该文件
- this.videoUrl==item.filePath
- this.doPlay(item,0,false,true)
- }
- },
- onSeeOutputPath:(outPutPath:string)=>{
- this.isExtractAcc = !this.isExtractAcc
- this.longItemFilePath = ''
- this.modeType = 0
- this.isShowFileName = true
- this.getSortedFiles(FileUtil.getParentPath(outPutPath))
- },
- onSliderChange:(value:number)=>{
- if(this.videoUrl!=item.filePath){
- this.videoUrl==item.filePath
- return
- }
- this.isSeekTo = true;
- this.mDestroyPage = false;
- this.showLoadIng();
- let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
- this.seekTo(seekValue + "");
- this.isSeekTo = false;
- },
- onResult:(result: boolean,outPath:string)=>{
- if(result){//如果成功,更新数据
- this.doUpdateData()
- }else{
- ToastUtil.showToast('提取伴奏失败')
- }
- }
- }
- )
- }
- }
- .width('100%')
- .height('100%')
- }
- //AI人声分离
- @Builder
- AiBuilder(item:VideoItem) {
- Scroll() {
- Column() {
- AIVoiceSeparation(
- {
- mVideoItem:item,
- videoUrl:this.videoUrl,
- currentPath:this.currentPath,
- CONTROL_PlayStatus:this.CONTROL_PlayStatus,
- currentTime:this.currentTime,
- progressValue:this.progressValue,
- onBack:()=>{
- this.isAIVoiceSeparation = !this.isAIVoiceSeparation
- this.longItemFilePath = ''
- },
- onPlayOrPause:()=>{
- if(this.videoUrl==item.filePath||this.isPlaying){
- this.playOrPause()
- }else{//如果不是当前播放的,则播放该文件
- this.videoUrl==item.filePath
- this.doPlay(item,0,false,true)
- }
- },
- onPlayPath:(path:string)=>{
- this.videoUrl==path
- const itemP = Utility.getItemByFilePath(this.videoLocalList,path)
- if(itemP)
- this.doPlay(itemP,0,false,true)
- },
- onSeeOutputPath:(outPutPath:string)=>{
- this.isAIVoiceSeparation = !this.isAIVoiceSeparation
- this.longItemFilePath = ''
- this.modeType = 0
- this.isShowFileName = true
- this.getSortedFiles(FileUtil.getParentPath(outPutPath))
- },
- onSliderChange:(value:number)=>{
- if(this.videoUrl!=item.filePath){
- this.videoUrl==item.filePath
- return
- }
- this.isSeekTo = true;
- this.mDestroyPage = false;
- this.showLoadIng();
- let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
- this.seekTo(seekValue + "");
- this.isSeekTo = false;
- },
- onResult:(result: boolean,outPath:string)=>{
- if(result){//如果成功,更新数据
- this.doUpdateData()
- }else{
- ToastUtil.showToast('Ai人声分离失败')
- }
- }
- }
- )
- }
- }
- .width('100%')
- .height('100%')
- }
- //变速变调
- @Builder
- ChangeToneBuilder(item:VideoItem) {
- Scroll() {
- Column() {
- ChangeTone(
- {
- mVideoItem:item,
- currentPath:this.currentPath,
- videoUrl:this.videoUrl,
- CONTROL_PlayStatus:this.CONTROL_PlayStatus,
- currentTime:this.currentTime,
- progressValue:this.progressValue,
- onBack:()=>{
- this.isChangeTone = !this.isChangeTone
- this.longItemFilePath = ''
- },
- onPlayOrPause:()=>{
- if(this.videoUrl==item.filePath){
- this.playOrPause()
- }else{//如果不是当前播放的,则播放该文件
- this.videoUrl==item.filePath
- this.doPlay(item,0,false,true)
- }
- },
- onSeeOutputPath:(outPutPath:string)=>{
- this.isChangeTone = !this.isChangeTone
- this.longItemFilePath = ''
- this.modeType = 0
- this.isShowFileName = true
- this.getSortedFiles(FileUtil.getParentPath(outPutPath))
- },
- onSliderChange:(value:number)=>{
- if(this.videoUrl!=item.filePath){
- this.videoUrl==item.filePath
- return
- }
- this.isSeekTo = true;
- this.mDestroyPage = false;
- this.showLoadIng();
- let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
- this.seekTo(seekValue + "");
- this.isSeekTo = false;
- },
- onResult:(result: boolean,outPath:string)=>{
- if(result){//如果成功,更新数据
- this.doUpdateData()
- }else{
- ToastUtil.showToast('变速变调失败')
- }
- }
- }
- )
- }
- }
- .width('100%')
- .height('100%')
- }
- //提取视频中的音频
- @Builder
- extractAudioFromVideoBuilder(item:VideoItem) {
- Scroll() {
- Column() {
- ExtractAudioFromVideo(
- {
- mVideoItem:item,
- currentPath:this.currentPath,
- videoUrl:this.videoUrl,
- CONTROL_PlayStatus:this.CONTROL_PlayStatus,
- currentTime:this.currentTime,
- progressValue:this.progressValue,
- onBack:()=>{
- this.isExtractAudio = !this.isExtractAudio
- this.longItemFilePath = ''
- },
- onPlayOrPause:()=>{
- if(this.videoUrl==item.filePath){
- this.playOrPause()
- }else{//如果不是当前播放的,则播放该文件
- this.videoUrl==item.filePath
- this.doPlay(item,0,false,true)
- }
- },
- onSeeOutputPath:(outPutPath:string)=>{
- this.isExtractAudio = !this.isExtractAudio
- this.longItemFilePath = ''
- this.modeType = 0
- this.isShowFileName = true
- this.getSortedFiles(FileUtil.getParentPath(outPutPath))
- },
- onSliderChange:(value:number)=>{
- if(this.videoUrl!=item.filePath){
- this.videoUrl==item.filePath
- return
- }
- this.isSeekTo = true;
- this.mDestroyPage = false;
- this.showLoadIng();
- let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
- this.seekTo(seekValue + "");
- this.isSeekTo = false;
- },
- onResult:(result: boolean,outPath:string)=>{
- if(result){//如果成功,更新数据
- this.doUpdateData()
- }else{
- ToastUtil.showToast('提取音频失败')
- }
- }
- }
- )
- }
- }
- .width('100%')
- .height('100%')
- }
- //合并音频
- @Builder
- MergeAudioBuilder() {
- Scroll() {
- Column() {
- MergeAudio(
- {
- videoUrl:this.videoUrl,
- CONTROL_PlayStatus:this.CONTROL_PlayStatus,
- currentPath:this.currentPath,
- selectedFiles:this.selectedFiles,
- currentTime:this.currentTime,
- progressValue:this.progressValue,
- onBack:()=>{
- this.isMergeAudio = !this.isMergeAudio
- this.longItemFilePath = ''
- },
- // onPlayPath:(path:string)=>{
- // if(this.videoUrl==item.filePath){
- // this.playOrPause()
- // }else{//如果不是当前播放的,则播放该文件
- // this.videoUrl==item.filePath
- // this.doPlay(item,0,false,true)
- // }
- //
- // },
- onSeeOutputPath:(outPutPath:string)=>{
- this.isMergeAudio = !this.isMergeAudio
- this.longItemFilePath = ''
- this.modeType = 0
- this.isShowFileName = true
- this.getSortedFiles(FileUtil.getParentPath(outPutPath))
- },
- onResult:(result: boolean,outPath:string)=>{
- if(result){//如果成功,更新数据
- this.doUpdateData()
- }else{
- if(this.selectedFiles.length>=3){
- ToastUtil.showToast('合并数量太多导致失败')
- }else{
- ToastUtil.showToast('合并失败')
- }
- }
- }
- }
- )
- }
- }
- .width('100%')
- .height('100%')
- }
- asyncCurrentPathData() {
- if (this.modeType == 0) {
- workerInstance.postMessage({
- code: 1,
- data1: this.context,
- data2: this.currentPath,
- data3: this.lockPath,
- data4: PreferencesUtil.getStringSync('COVER_API', ''),
- data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
- });
- }
- }
- // 处理文件选择的函数
- handleFileSelection(item: VideoItem, checked: boolean) {
- if (checked) {
- if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
- this.selectedFiles.push(item);
- }
- } else {
- const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
- if (index > -1) {
- this.selectedFiles.splice(index, 1);
- }
- }
- }
- private deleteComponentId: number = 0
- //多选删除文件
- showWarnIsDelete(){
- this.getUIContext().getPromptAction().openCustomDialog({
- builder: () => {
- this.deleteComptentBuilder()
- },
- isModal:true,
- showInSubWindow:false,
- maskColor: Color.Transparent,
- dialogTransition: // 设置弹窗内容显示的过渡效果
- TransitionEffect.translate({ x: 0, y: 290, z: 0 })
- .animation({ duration: 600, curve: Curve.Smooth }),
- maskTransition: // 设置蒙层显示的过渡效果
- TransitionEffect.opacity(0)
- .animation({ duration: 600, curve: Curve.Smooth })
- }).then((dialogId: number) => {
- this.deleteComponentId = dialogId
- })
- .catch((error: BusinessError) => {
- console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
- })
- }
- @Builder
- deleteComptentBuilder(){
- DeleteComptent({
- selectedFiles:this.selectedFiles,
- onCancel:()=>{
- this.isMultiSelect = false
- this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
- },
- onDeleteResult:(result: boolean)=>{
- this.isMultiSelect = false
- this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
- if(result){//如果删除成功,更新数据
- this.selectedFiles = [];
- this.isAllSelected = false
- this.cache.delete(this.currentPath);
- this.getSortedFiles(this.currentPath, true);
- }
- }
- })
- }
- //多选移动文件
- 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.color = this.themeColor
- 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, this.autoParseMusicName);
- 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();
- }
- }
- /**
- * 加载所有歌单
- */
- async loadAllPlaylists() {
- try {
- this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
- LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
- } catch (error) {
- LogUtil.error('heaunp Failed to load playlists: ' + error.message)
- }
- }
- /**
- * 显示添加到歌单对话框
- */
- async openAddToPlaylistDialog(items: VideoItem | VideoItem[]) {
- const songs = Array.isArray(items) ? items : [items]
- const musicItems = songs.filter(song => song.type !== CommonConstants.TYPE_IS_DIR)
- if (musicItems.length === 0) {
- ToastUtil.showToast('请选择要添加的歌曲')
- return
- }
- // 加载最新的歌单列表
- await this.loadAllPlaylists()
- showAddToPlaylistDialog(
- musicItems,
- this.allPlaylists,
- async (playlistId: string) => {
- // 添加歌曲到歌单
- const success = await this.playlistTable?.addSongsToPlaylist(playlistId,
- musicItems.map(song => song.filePath))
- if (success) {
- const count = musicItems.length
- ToastUtil.showToast(count > 1 ? `已添加 ${count} 首歌曲` : '已添加到歌单')
- // 重新加载歌单列表
- await this.loadAllPlaylists()
- } else {
- ToastUtil.showToast(musicItems.length > 1 ? '选中的歌曲已在该歌单中' : '歌曲已在该歌单中')
- }
- this.longItemFilePath = ''
- if (this.isMultiSelect) {
- this.isMultiSelect = false
- this.isAllSelected = false
- this.selectedFiles = []
- }
- },
- () => {
- LogUtil.info('取消添加到歌单')
- },
- () => {
- // 创建新歌单
- showCreatePlaylistDialog(
- async (name: string, description: string, coverPath?: string) => {
- const success = await this.playlistTable?.createPlaylist(name, description, coverPath)
- if (success) {
- ToastUtil.showToast('歌单创建成功')
- // 重新加载歌单列表并打开添加对话框
- await this.loadAllPlaylists()
- await this.openAddToPlaylistDialog(musicItems)
- } else {
- ToastUtil.showToast('歌单创建失败')
- }
- },
- () => {
- // 取消创建歌单
- }
- )
- }
- )
- }
- 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,data2:this.packName });
- 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.color = this.themeColor
- 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, this.autoParseMusicName);
- 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) {
- Button({ type: ButtonType.Normal, stateEffect: true }) {
- Row() {
- Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
- $r('app.media.music_group'))
- .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
- .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
- .fillColor(this.themeColor)// .fontSize(33)
- .alt($r('app.media.music_group'))
- .borderRadius('100%')
- // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
- // .autoResize(true) // 重采样,可减少内存占用
- .clip(true)
- .sourceSize({width:38, height:38})
- .margin({ left: 20, top: 8, bottom: 8 })
- Column() {
- Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
- .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
- .maxLines(1)// .width('88%')
- .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
- .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(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
- .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(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
- .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)
- .alignSelf(ItemAlign.Center)
- .id(item.filePath)
- .visibility(this.isShowAlphaBet?Visibility.None:Visibility.Visible)
- .animation({ duration: 300, curve: Curve.Ease })
- }
- }
- .backgroundColor(Color.Transparent)
- .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
- .width('98%')
- .reuseId('dir_item')
- .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
- .opacity(this.opacityItem) // 绑定透明度
- }
- 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) {
- Button({ type: ButtonType.Normal, stateEffect: true }) {
- Row() {
- Stack() {
- Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
- .fillColor(this.themeColor)
- .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
- .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
- .alt($r('app.media.music_red'))
- .borderRadius(this.isCoverRectangle?13:'100%')
- .clip(true)
- .draggable(false)
- .sourceSize({width:38, height:38})
- // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
- // .autoResize(true) // 重采样,可减少内存占用
- .opacity(this.opacityItem)// 绑定透明度
- .margin({ left: 20 })
- .gesture(LongPressGesture()
- .onAction(async () => {
- //如果是专辑和艺术家的首页,不能长按
- if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
- return
- //如果是我的收藏 最近播放等也不能长按
- if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
- item.name === LocalMusic.STR_HISTORY_MUSIC
- )
- return
- this.longItemFilePath = item.filePath
- this.tempLyricContent = await this.getLyricContent(item)
- LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
- })
- .onActionEnd((event: GestureEvent) => {
- }))
- .onClick(()=>{
- if (this.isMultiSelect) {
- const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
- this.handleFileSelection(item, !isChecked);
- } else {
- this.doPlay(item,index)
- this.setShowPlayTrue()
- }
- })
- }
- Column() {
- Column() {
- Text(this.isShowFileName?item.fileName :item.name)
- .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
- .maxLines(1)
- .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
- .animation({
- duration: 555,
- curve: 'Linear',
- })
- .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
- $r('app.color.text_color'))
- .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
- .padding({right:25})
- .bindPopup(this.longItemFilePath === item.filePath, {
- builder: this.MenuBuilder(item,index,item.filePath),
- placement: Placement.Top,
- // autoCancel: true,
- mask: {color:'#33000000'},
- // popupColor: Color.Yellow,
- enableArrow: false,//是否显示箭头
- showInSubWindow: false,
- onStateChange: (e) => {
- if (!e.isVisible) {
- this.longItemFilePath = ''
- this.tempLyricContent = ''
- }
- }
- })
- .gesture(LongPressGesture()
- .onAction(async () => {
- //如果是专辑和艺术家的首页,不能长按
- if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
- return
- //如果是我的收藏 最近播放等也不能长按
- if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
- item.name === LocalMusic.STR_HISTORY_MUSIC
- )
- return
- this.longItemFilePath = item.filePath
- this.tempLyricContent = await this.getLyricContent(item)
- LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
- })
- .onActionEnd((event: GestureEvent) => {
- })
- )
- Row() {
- Column(){
- Text(item.md5Str?.includes('Lossless')?
- Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
- .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
- .padding({ top: 3,right:6,left:6,bottom:3 })
- .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
- $r('app.color.text_color'))
- .fontWeight(500)
- .borderRadius(12)
- .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
- .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
- .backgroundColor('#FFC107')
- }
- .padding({ top: 8 })
- Text(StrUtil.isEmpty(item.artist) ? item.duration
- :this.twoFingerType==2? item.artist +' ' + item.duration
- : item.artist + ' ' + item?.duration)
- .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
- .padding({ top: 8 ,right:25})
- .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
- .maxLines(1)
- .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
- .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
- Color.Gray)
- .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
- Blank()
- Text(this.isShowFileName?item.duration:item.size)
- .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
- .padding({ top: 8 })
- .maxLines(1)
- .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
- ? Visibility.Visible : Visibility.None)
- .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
- Color.Gray)
- .margin({ left: StrUtil.isEmpty(item.artist) ?0:10 })
- }
- .gesture(LongPressGesture()
- .onAction(async () => {
- //如果是专辑和艺术家的首页,不能长按
- if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
- return
- //如果是我的收藏 最近播放等也不能长按
- if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
- item.name === LocalMusic.STR_HISTORY_MUSIC
- )
- return
- this.longItemFilePath = item.filePath
- this.tempLyricContent = await this.getLyricContent(item)
- LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
- })
- .onActionEnd((event: GestureEvent) => {
- })
- )
- }
- .height('100%')
- .width('100%')
- .margin({ right: 10 })
- .justifyContent(FlexAlign.Center)
- .alignItems(HorizontalAlign.Start)
- }
- .height('100%')
- .margin({ left: 5 })
- .layoutWeight(1)
- Column() {
- Checkbox({ name: 'checkbox' + index })
- .select(this.selectedFiles.some(x => x.filePath === item.filePath))
- .selectedColor(this.themeColor)
- .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,right:18 })
- .width(22)
- .height(22)
- ImageAnimator()
- .images(this.imagesF)// 动画数组
- .duration(1000)// 持续
- .state(this.animationState)// 动画状态
- .fillMode(FillMode.Forwards)
- .width(18)
- .margin({ right: 20, top: 8, bottom: 8 })
- .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
- Visibility.None)
- .height(18)
- .iterations(-1) // 播放次数
- }
- }
- }
- .backgroundColor(Color.Transparent)
- .width('100%')
- .reuseId('file_item')
- .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
- }
- private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
- @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
- buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
- direction: Direction.Ltr,
- buttonPadding:{top:12,bottom:12},
- backgroundColor: Color.Transparent,
- fontSize:14,
- selectedFontSize:15,
- selectedFontColor:Color.White,
- selectedBackgroundColor: this.themeColor,
- localizedTextPadding: {
- end: LengthMetrics.vp(20),
- start: LengthMetrics.vp(20)
- }
- })
- @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
- //当胶囊按钮的选择发生变化时调用此函数
- capsuleSelectedIndexesChanged() {
- this.modeType = this.tabSelectedIndexes[0]
- }
- @Builder
- tabTitle() {
- Column({ space: 2 }) {
- SegmentButton({ options: this.tabOptions, selectedIndexes: $tabSelectedIndexes })
- Line()
- .width('100%')
- .height(1)
- .backgroundColor($r('app.color.index_background'))
- .opacity(this.barOpacity)
- .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
- }
- .width('100%')
- .height(this.topBarHeight)
- .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
- }
- // @Builder
- // tabTitle() {
- // Column() {
- // // 使用 Stack 布局来实现绝对定位效果
- // Stack() {
- // // 背景动画容器
- // Row() {
- // ForEach(this.tabs, (i: string, index) => {
- // Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
- // Flex()
- // .backgroundColor(this.isDarkMode ? $r('app.color.tab_item_bg') : this.themeColor)
- // .borderRadius(20)
- // .padding(10)
- // .margin(6)
- // .width('100%')
- // .height('100%')
- // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
- // .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: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5,
- // right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 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)
- // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
- // .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)
- // }
- // .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
- // }
- @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
- @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
- isShowCoverHeader() {
- if (!this.isShowHeader) {
- return false
- }
- if (this.modeType == 0) {
- if (this.isHistory || this.isFavMusic) {
- return true
- }
- if (this.currentPath != this.rootPath) {
- return true
- }
- }
- return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
- }
- getCoverTitleBg(): ResourceStr | image.PixelMap {
- if (this.isCustomizeBg) {
- return ('rgba(255,255,255,0.2)')
- }
- if (this.isDarkMode) {
- return $r('app.color.user_center_card_background')
- }
- return this.currentTitleCover
- }
- // 第二步:popup构造器定义弹框内容
- @Builder popupBuilder() {
- Column({ space: 2 }) {
- Text('友情提示:双指缩放可以放大缩小列表')
- .fontSize(12)
- .fontWeight(FontWeight.Regular)
- .fontColor($r('app.color.text_color'))
- }
- .justifyContent(FlexAlign.SpaceAround)
- .width(220)
- .height(55)
- .padding(15)
- }
- //搜索功能的实现
- @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:
- case 1:
- mSearchList = this.mediaKuList
- break;
- case 2:
- mSearchList = this.artistList
- break;
- case 3:
- mSearchList = this.albumList
- break;
- default :
- mSearchList = this.videoLocalList
- break;
- }
- // 新增条件判断:空输入时显示所有数据
- if (this.searchText === '') {
- this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
- } else {
- this.filteredList = mSearchList.filter((item: VideoItem) => {
- //支持模糊匹配和艺术家 专辑匹配
- const regex = new RegExp(this.searchText.toLowerCase().replace(/\s+/g, '.*'), 'i');
- return regex.test(item.name.toLowerCase())||
- regex.test(item.fileName?.toLowerCase() ?? "") ||
- regex.test(item.artist?.toLowerCase() ?? "") ||
- regex.test(item.album?.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)
- if(this.modeType==4&&this.playlistTable){
- updateAllSongsSortOrder(this.playlistTable, this.videoLocalList,this.currentSongListID)
- }
- }
- //瀑布流布局 支持双指缩放
- @State columns: number = 2;
- @State waterFlowScale: number = 1;
- @State imageScale: number = 1;
- @State waterFlowOpacity: number = 1;
- @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
- private columnChanged: boolean = false;
- private oldColumn: number = this.columns;
- private pinchTime: number = 0;
- // 根据缩放阈值改变列数,触发WaterFlow重新布局
- changeColumns(scale: number) {
- if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
- this.columns--;
- this.columnChanged = true;
- } else if (scale < 1 && this.columns < 4) {
- this.columns++;
- this.columnChanged = true;
- }
- }
- @Builder
- getWaterView(){
- Scroll(this.scroller) {
- Column() {
- Blank().height(this.topSafeHeight + 55)
- WaterFlow({
- scroller:this.waterScroller,
- layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
- }) {
- LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
- FlowItem() {
- this.MusicWaterCardItem(item,index)
- }
- .width('100%')
- .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
- .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
- {
- preview: MenuPreviewMode.IMAGE,
- previewAnimationOptions: { scale: [0.8, 1.0] },
- })
- .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
- {
- preview: MenuPreviewMode.IMAGE,
- previewAnimationOptions: { scale: [0.8, 1.0] },
- })
- .transition(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }))
- .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
- TransitionEffect.scale({ x: 0, y: 0 })))
- .gesture(
- GestureGroup(GestureMode.Exclusive,
- SwipeGesture({ direction: SwipeDirection.Horizontal })
- .onAction((event: GestureEvent) => {
- if (event) {
- // this.sideBarController.openSideBar()
- }
- }),
- TapGesture({ count: 1, fingers: 1 })
- .onAction(async () => {
- })
- )
- )
- }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
- }
- // .columnsTemplate('repeat(auto-fit, 160)')
- .id('waterflow') // 设置id用于截图
- .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
- .columnsGap(12) // 列间距
- .rowsGap(16) // 行间距
- .cachedCount(6)
- .padding({bottom:this.bottomBarHeight+10})
- .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
- .animation({ duration: 500, curve: Curve.Ease }))
- .scrollBar(BarState.Off)
- // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
- // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
- .edgeEffect(EdgeEffect.Spring, { alwaysEnabled: true })
- .width('90%')
- .height('100%')
- .opacity(this.waterFlowOpacity)
- .scale({
- x: this.waterFlowScale,
- y: this.waterFlowScale,
- centerX: 0,
- centerY: 0
- })
- .onAppear(() => {
- this.scroller.scrollEdge(Edge.Top)
- })
- .nestedScroll({
- scrollForward: NestedScrollMode.PARENT_FIRST,
- scrollBackward: NestedScrollMode.SELF_FIRST
- })
- .priorityGesture(
- PinchGesture()
- .onActionStart((event: GestureEvent) => {
- // 双指捏合手势识别成功时截图
- this.pinchTime = event.timestamp;
- this.columnChanged = false;
- this.oldColumn = this.columns;
- this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
- if (error) {
- console.info('error:' + JSON.stringify(error));
- return;
- }
- this.waterFlowSnapshot = pixmap;
- if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
- console.info("onecold onActionStart oldColumn:" + this.oldColumn)
- if (this.oldColumn ===4) {
- this.twoFingerType =3
- this.isGridMusic = true
- }else if (this.oldColumn ===1) {
- this.twoFingerType =1
- this.isGridMusic = false
- }
- return;
- }
- })
- })
- .onActionUpdate((event: GestureEvent) => {
- // 手势更新:处理缩放逻辑和视觉效果
- // 边界限制:防止超出列数范围时继续缩放
- if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
- return;
- }
- // 节流处理:避免过于频繁的更新,提升性能
- if (event.timestamp - this.pinchTime < 10000000) {
- return;
- }
- this.pinchTime = event.timestamp;
- this.waterFlowScale = event.scale;
- this.imageScale = event.scale;
- // 根据缩放比例设置WaterFlow透明度
- this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
- this.waterFlowOpacity *= 3;
- if (!this.columnChanged) {
- this.changeColumns(event.scale);
- }
- // 列数改变后的缩放比例调整:避免出现空白区域
- if (this.columnChanged) {
- this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
- // 限制缩放范围,确保视觉效果自然
- if (event.scale < 1) {
- this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
- } else {
- this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
- }
- }
- })
- .onActionEnd((event: GestureEvent) => {
- // 手势结束:执行归位动画并保存状态
- // 执行归位动画:平滑过渡到正常状态
- this.getUIContext()?.animateTo({ duration: 300 }, () => {
- this.waterFlowScale = 1;
- this.waterFlowOpacity = 1;
- })
- // 持久化保存当前列数:下次启动时恢复
- PreferencesUtil.putSync('lastColumns', this.columns);
- })
- )
- //允许拖拽音乐和视频到List或Grid上自动导入视频
- .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
- .onDrop((event?: DragEvent) => {
- try {
- let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
- if (dragData !== undefined) {
- let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
- if (records.length > 0) {
- for (let i = 0; i < records.length; i++) {
- let types = records[i].getTypes();
- if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
- const fileUriUds =
- records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
- let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
- if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
- ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
- this.targetFile = fileUriUds.oriUri;
- this.saveVideoDatas([this.targetFile])
- hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
- }
- }
- }
- } else {
- hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
- }
- } else {
- hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
- }
- } catch (error) {
- const err = error as BusinessError;
- hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
- }
- })
- }
- }
- .scrollBar(BarState.Off)
- }
- //瀑布流卡片布局
- @Builder
- private MusicWaterCardItem(item: VideoItem, index: number) {
- Button({ type: ButtonType.Normal, stateEffect: false }) {
- Stack() {
- Column() {
- Image(item.pixelMapPath)
- .backgroundImageSize(ImageSize.Auto)
- .borderRadius({
- topLeft: 12,
- topRight : 12,
- bottomLeft: 0,
- bottomRight: 0
- })
- .draggable(false)// 禁止长按手势拖动
- .autoResize(true) // 重采样,可减少内存占用
- .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
- .width('100%')
- .height('auto')
- .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
- .objectFit(ImageFit.Auto)
- .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
- height: '99%' ,
- dragBar: true,
- onDisappear: () => {
- this.longItemFilePath = '';
- this.tempLyricContent = ''
- },
- showClose: true,
- preferType: SheetType.CENTER ,
- title: { title: '编辑标签' }
- })
- .draggable(false)
- .opacity(this.opacityItem)// 绑定透明度
- // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
- // .animation({ duration: 500, curve: Curve.Ease }))
- .animation({
- duration: 666,
- curve: 'ease-in-out' // 可选动画曲线
- })
- .margin({
- left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
- right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
- })
- Column() {
- Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
- .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
- .maxLines(1)
- .fontWeight(FontWeight.Bold)
- .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
- .animation({
- duration: 555,
- curve: 'Linear',
- })
- .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
- height: '95%',
- dragBar: true,
- showClose: true,
- onDisappear: () => {
- this.longItemFilePathDetail = '';
- },
- blurStyle:BlurStyle.Thin,
- backgroundColor:Color.Transparent,
- preferType: SheetType.CENTER ,
- title: { title: '详情' }
- })
- .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
- $r('app.color.text_color'))
- Column() {
- Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
- .fontSize(11)
- .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
- .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
- .fontColor($r('app.color.text_color'))
- Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
- .fontSize(11)
- .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
- .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
- .fontColor($r('app.color.text_color'))
- Row(){
- Column(){
- Text(item.md5Str?.includes('Lossless')?
- Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
- .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
- .padding({ top: 3,right:6,left:6,bottom:3 })
- .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
- $r('app.color.text_color'))
- .fontWeight(500)
- .borderRadius(12)
- .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
- .backgroundColor('#FFC107')
- .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
- }
- .margin({ top: 2 ,right:6})
- .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
- ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
- Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
- .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
- .maxLines(1)
- .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
- .margin({ top: 2})
- .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
- || item.type == CommonConstants.TYPE_IS_ALBUM
- || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
- .fontWeight(FontWeight.Medium)
- .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
- $r('app.color.text_color'))
- }
- }
- .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
- }
- .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
- : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
- (item.type==CommonConstants.TYPE_IS_DIR?48:58))
- .width('100%')
- .justifyContent(FlexAlign.Center)
- .margin({
- left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
- right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
- })
- }
- .width('100%')
- .borderRadius(12)
- .backgroundImage(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
- .backgroundImageSize({ height: '100%', width: '100%' })
- .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
- .animation({ curve: Curve.Sharp, duration: 300 })
- Checkbox({ name: 'checkbox' + index })
- .select(this.selectedFiles.some(x => x.filePath == item.filePath))
- .selectedColor(this.themeColor)
- .shape(CheckBoxShape.CIRCLE)
- .opacity(this.isMultiSelect ? 1 : 0)
- .animation({
- duration: 666,
- curve: 'Smooth' // 可选动画曲线
- })
- .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
- Visibility.None)
- .onChange((checked: boolean) => this.handleFileSelection(item, checked))
- .margin({ left: 20, top: 8, bottom: 8 })
- .width(38)
- .height(38)
- }
- }
- .backgroundColor(Color.Transparent)
- .width('100%')
- .height('auto')
- .padding({top:2})
- .shadow({
- radius: 10,
- type: ShadowType.BLUR,
- color: 'on_primary'
- })
- .reuseId('card_item')
- .onClick(() => {
- if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
- const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
- this.handleFileSelection(item, !isChecked);
- } else {
- this.doPlay(item, index)
- }
- })
- }
- // Grid布局的开始
- private dragRefOffSetX: number = 0;
- private dragRefOffSetY: number = 0;
- private FIX_VP_X: number = 180;
- private FIX_VP_Y: number = 84;
- isDraggable(index: number): boolean {
- return index >= 0;
- }
- getRowEnd(item: number) {
- if (item.toString() === '0') {
- return 1;
- } else {
- return 0;
- }
- }
- isInLeft(index: number) {
- return index % 2 == 0;
- }
- down(index: number): void {
- if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
- return;
- }
- this.offsetY -= this.FIX_VP_Y;
- this.dragRefOffSetY += this.FIX_VP_Y;
- this.itemMove(index, index + 1);
- }
- up(index: number): void {
- if (!this.isDraggable(index - 2)) {
- return;
- }
- this.offsetY += this.FIX_VP_Y;
- this.dragRefOffSetY -= this.FIX_VP_Y;
- this.itemMove(index, index - 1);
- }
- left(index: number): void {
- if (this.isInLeft(index)) {
- return;
- }
- if (!this.isDraggable(index - 1)) {
- return;
- }
- this.offsetX += this.FIX_VP_X;
- this.dragRefOffSetX -= this.FIX_VP_X;
- this.itemMove(index, index - 1)
- }
- right(index: number): void {
- if (!this.isInLeft(index)) {
- return;
- }
- if (!this.isDraggable(index + 1)) {
- return;
- }
- this.offsetX -= this.FIX_VP_X;
- this.dragRefOffSetX += this.FIX_VP_X;
- this.itemMove(index, index + 1)
- }
- private scroller: Scroller = new Scroller();
- private waterScroller: Scroller = new Scroller();
- @State startIndex: number = 0
- @State endIndex: number = 0
- @State scaleValue: number = 1
- @State pinchValue: number = 1
- layoutOptionsForHeader: GridLayoutOptions = {
- regularSize: [1, 1], // 只支持[1, 1]
- irregularIndexes: [0], // 索引为0的GridItem占用一行
- };
- @Builder
- getGridView() {
- Grid(this.scroller, this.layoutOptionsForHeader) {
- GridItem() {
- Column(){
- Blank().height(this.topSafeHeight + 45)
- }
- }
- LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
- GridItem() {
- Stack({ alignContent: Alignment.Center }) {
- this.MusicItemGrid(item, index)
- }
- }
- .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
- {
- preview: MenuPreviewMode.IMAGE,
- previewAnimationOptions: { scale: [0.8, 1.0] },
- })
- .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
- {
- preview: MenuPreviewMode.IMAGE,
- previewAnimationOptions: { scale: [0.8, 1.0] },
- })
- .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
- TransitionEffect.scale({ x: 0, y: 0 })))
- .clickEffect({ level: ClickEffectLevel.LIGHT })
- .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
- .zIndex(this.dragItem === index ? 1 : 0)
- .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
- }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
- }
- .width('94%')
- .height('100%')
- .editMode(true)
- .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
- .animation({ duration: 500, curve: Curve.Ease }))
- .padding({bottom:this.bottomBarHeight+this.bottomSafeHeight+10})
- .reuseId('grid_item')
- .layoutWeight(1)
- .scrollBar(BarState.Off)
- .supportAnimation(true)
- .cachedCount(this.twoFingerType==1?5:this.twoFingerType==2?4:3)
- .columnsTemplate(
- this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
- this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
- )
- .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
- .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
- .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
- .gesture(PinchGesture({ fingers: 2 })
- .onActionEnd((event: GestureEvent) => {
- this.setGridTwoFingers()
- })
- .onActionUpdate(e => {
- this.scaleValue = this.pinchValue * e.scale
- })
- .onActionStart(e => {
- }))
- .enableScrollInteraction(true)
- .onScrollIndex((start: number, end: number) => {
- this.startIndex = start
- this.endIndex = end
- })
- .onScrollFrameBegin((offset: number) => {
- if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
- (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
- this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
- if (this.isScrollHide) {
- this.setBarHeightHide2(offset)
- } else {
- this.setBarHeightNormal()
- }
- } else {
- this.setBarHeightHide(offset)
- }
- return { offsetRemain: offset };
- })
- .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
- .onDrop((event?: DragEvent) => {
- try {
- let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
- if (dragData !== undefined) {
- let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
- if (records.length > 0) {
- for (let i = 0; i < records.length; i++) {
- let types = records[i].getTypes();
- if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
- const fileUriUds =
- records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
- let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
- if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
- ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
- this.targetFile = fileUriUds.oriUri;
- this.saveVideoDatas([this.targetFile])
- hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
- }
- }
- }
- } else {
- hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
- }
- } else {
- hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
- }
- } catch (error) {
- const err = error as BusinessError;
- hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
- }
- })
- }
- @State targetFile: string = '';
- setGridTwoFingers() {
- this.pinchValue = this.scaleValue;
- Logger.info('this.pinchValue = ' + this.pinchValue);
- if (this.pinchValue >= 1) {
- this.twoFingerType++
- Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
- if(this.twoFingerType >= 4){
- this.twoFingerType = 4//切换成瀑布流
- this.columns = 4
- }
- } else {
- this.twoFingerType--
- Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
- if (this.twoFingerType < 1) {
- this.twoFingerType = 3
- this.isGridMusic = false
- PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
- }
- }
- PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
- PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
- this.pinchValue = 1;
- this.scaleValue = 1;
- }
- @State longItemFilePath: string = ''
- @State tempLyricContent: string = ''
- @State editingItem: VideoItem | null = null
- @Builder
- private MusicItemGrid(item: VideoItem, index: number) {
- Button({ type: ButtonType.Normal, stateEffect: false }) {
- Stack() {
- Column() {
- Image(item.pixelMapPath)
- .height(this.getGridHeight())
- .width(this.getGridWight())
- .draggable(false)
- .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
- .autoResize(true) // 重采样,可减少内存占用
- .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
- .clip(true)
- .borderRadius({
- topLeft: 12,
- topRight: 12,
- bottomLeft: 0,
- bottomRight: 0
- })
- .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
- height: '99%' ,
- dragBar: true,
- onDisappear: () => {
- this.longItemFilePath = '';
- this.tempLyricContent = ''
- },
- showClose: true,
- preferType: SheetType.CENTER ,
- title: { title: '编辑标签' }
- })
- .draggable(false)
- .opacity(this.opacityItem)// 绑定透明度
- .animation({
- duration: 666,
- curve: 'ease-in-out' // 可选动画曲线
- })
- .margin({
- left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
- right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
- })
- Column() {
- Text(this.isShowFileName&&item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
- .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
- .maxLines(1)
- .fontWeight(FontWeight.Bold)
- .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
- .animation({
- duration: 555,
- curve: 'Linear',
- })
- .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
- height: '95%',
- dragBar: true,
- showClose: true,
- onDisappear: () => {
- this.longItemFilePathDetail = '';
- },
- blurStyle:BlurStyle.Thin,
- backgroundColor:Color.Transparent,
- preferType: SheetType.CENTER ,
- title: { title: '详情' }
- })
- .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
- $r('app.color.text_color'))
- Column() {
- Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
- .fontSize(11)
- .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
- .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
- .fontColor($r('app.color.text_color'))
- Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
- .fontSize(11)
- .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
- .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
- .fontColor($r('app.color.text_color'))
- Row(){
- Column(){
- Text(item.md5Str?.includes('Lossless')?
- Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
- .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
- .padding({ top: 3,right:6,left:6,bottom:3 })
- .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
- $r('app.color.text_color'))
- .fontWeight(500)
- .borderRadius(12)
- .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
- .backgroundColor('#FFC107')
- .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
- }
- .margin({ top: 2 ,right:6})
- .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
- ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
- Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
- .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
- .maxLines(1)
- .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
- .margin({ top: 2})
- .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
- || item.type == CommonConstants.TYPE_IS_ALBUM
- || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
- .fontWeight(FontWeight.Medium)
- .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
- $r('app.color.text_color'))
- }
- }
- .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
- }
- .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
- .width(this.getGridWight())
- .justifyContent(FlexAlign.Center)
- .margin({
- left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
- right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
- })
- }
- .width(this.getGridWight())
- .borderRadius(12)
- .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?undefined:item.pixelMapPath)
- .backgroundImageSize({ height: '100%', width: '100%' })
- .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
- .animation({ curve: Curve.Sharp, duration: 300 })
- Checkbox({ name: 'checkbox' + index })
- .select(this.selectedFiles.some(x => x.filePath == item.filePath))
- .selectedColor(this.themeColor)
- .shape(CheckBoxShape.CIRCLE)
- .opacity(this.isMultiSelect ? 1 : 0)
- .animation({
- duration: 666,
- curve: 'Smooth' // 可选动画曲线
- })
- .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
- Visibility.None)
- .onChange((checked: boolean) => this.handleFileSelection(item, checked))
- .margin({ left: 20, top: 8, bottom: 8 })
- .width(38)
- .height(38)
- }
- }
- .backgroundColor(Color.Transparent)
- .width('100%')
- .padding({ top: 15 })
- .height(this.getGridAllHeight())
- .onClick(() => {
- if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
- const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
- this.handleFileSelection(item, !isChecked);
- } else {
- this.doPlay(item, index)
- }
- })
- }
- getGridAllHeight() {
- let heightG = 222
- switch (this.twoFingerType) {
- case 1:
- heightG = 143
- break;
- case 2:
- heightG = 178
- break;
- case 3:
- heightG = 222
- break;
- }
- return heightG
- }
- getGridHeight() {
- let heightG = 150
- switch (this.twoFingerType) {
- case 1:
- heightG = 80
- break;
- case 2:
- heightG = 110
- break;
- case 3:
- heightG = 150
- break;
- }
- return heightG
- }
- getGridWight() {
- let wightG = 158
- switch (this.twoFingerType) {
- case 1:
- wightG = 80
- break;
- case 2:
- wightG = 110
- break;
- case 3:
- wightG = 158
- break;
- }
- return wightG
- }
- @State isShowDetail:boolean = false
- @State longItemFilePathDetail:string =''
- @Builder
- MenuBuilder(item: VideoItem, index: number, filePath: string) {
- if(
- ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
- ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
- item.name === LocalMusic.STR_HISTORY_MUSIC)
- ){
- //如果是专辑和艺术家的首页,不能长按
- //如果是我的收藏 最近播放等也不能长按
- }else{
- Scroll() {
- Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
- Menu() {
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
- $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
- content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
- })
- .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
- .onClick(() => {
- if (item) {
- this.doFav(item)
- }
- this.longItemFilePath = ''
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
- content: '下一首播放'
- })
- .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
- .onClick(() => {
- this.addToNextPlay(item);
- this.longItemFilePath = ''
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
- content: '添加到歌单'
- })
- .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
- .onClick(async () => {
- this.longItemFilePath = ''
- await this.openAddToPlaylistDialog(item)
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
- content: '编辑标签'
- })
- .bindSheet($$this.isShowEdit, this.editSheet(item), {
- height: '99%',
- dragBar: true,
- showClose: true,
- preferType: SheetType.CENTER ,
- title: { title: '编辑标签' }
- })
- .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
- .onClick(async() => {
- this.initEditFields(item)
- this.tempLyricContent = await this.getLyricContent(item);
- if (StrUtil.isNotEmpty(this.tempLyricContent)) {
- this.lyricConStr = this.tempLyricContent
- }
- if(this.isGridMusic||this.twoFingerType==4){
- this.longItemFilePath = item.filePath
- }else{
- this.isShowEdit = !this.isShowEdit;
- }
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
- content: $r('app.string.select_all')
- })
- .onClick(() => {
- this.isMultiSelect = !this.isMultiSelect
- this.longItemFilePath = ''
- this.selectedFiles.push(item)
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.cut')),
- content: $r('app.string.edit_audio')
- })
- .bindContentCover($$this.isEditAudio, this.EditAudioBuilder(item), {
- transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
- })
- .onClick(() => {
- this.isEditAudio = !this.isEditAudio
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
- content: $r('app.string.extract_accompaniment')
- })
- .bindContentCover($$this.isExtractAcc, this.ExtractAccBuilder(item), {
- transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
- })
- .onClick(() => {
- if (!Utility.isNoble()) {
- this.showVipDialog()
- return
- }
- this.isExtractAcc = !this.isExtractAcc
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.repeat')),
- content: $r('app.string.converter_audio')
- })
- .bindContentCover($$this.isConverter, this.ConverterBuilder(item), {
- transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
- })
- .onClick(() => {
- if (!Utility.isNoble()) {
- this.showVipDialog()
- return
- }
- this.isConverter = !this.isConverter
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.ai_edit')),
- content: $r('app.string.vocal_separation')
- })
- .bindContentCover($$this.isAIVoiceSeparation, this.AiBuilder(item), {
- transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
- })
- .onClick(() => {
- this.isAIVoiceSeparation = !this.isAIVoiceSeparation
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_counterclockwise_clock')),
- content: $r('app.string.change_tone')
- })
- .bindContentCover($$this.isChangeTone, this.ChangeToneBuilder(item), {
- transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
- })
- .onClick(() => {
- this.isChangeTone = !this.isChangeTone
- })
- if(Utility.isVideoByExtension(item.filePath)){
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.identify_song')),
- content: $r('app.string.extract_audio')
- })
- .bindContentCover($$this.isExtractAudio, this.extractAudioFromVideoBuilder(item), {
- transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
- })
- .onClick(() => {
- this.isExtractAudio = !this.isExtractAudio
- })
- }
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.phone')),
- content: $r('app.string.set_ring')
- })
- .onClick(async () => {
- await PermissionUtil.activatePermission(item.filePath)
- // if(item.filePath.includes(this.packName)){
- setRingTone(this.context, item.filePath,item.name)
- // }else{
- // ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限设置铃声')
- // }
- this.longItemFilePath = ''
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
- content: $r('app.string.rename')
- })
- .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)
- .onClick(() => {
- this.showReNameDialog(item, index + '', filePath)
- this.longItemFilePath = ''
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
- content: $r('app.string.delete')
- })
- .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)
- .onClick(() => {
- this.selectedFiles.push(item)
- this.showWarnIsDelete()
- this.longItemFilePath = ''
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
- content: $r('app.string.detail')
- })
- .bindSheet($$this.isShowDetail, this.detailSheet(item), {
- height:'95%',
- dragBar: true,
- showClose: true,
- blurStyle:BlurStyle.Thin,
- preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
- backgroundColor:Color.Transparent,
- title: { title: '详情信息' }
- })
- .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
- .onClick(() => {
- if(this.isGridMusic||this.twoFingerType==4){
- this.longItemFilePathDetail = item.filePath
- }else{
- this.isShowDetail = !this.isShowDetail
- }
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
- content: $r('app.string.share')
- })
- .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
- .onClick(() => {
- Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
- this.longItemFilePath = ''
- })
- }
- .font({ size: 14, weight: FontWeight.Normal })
- }
- .width(180)
- }
- .height('auto')
- }
- }
- private listMaxScrollOffsetY: number = 0
- @State selectedIndex: number = -1
- setlistTwoFingers() {
- this.pinchValue = this.scaleValue;
- Logger.info('this.pinchValue = ' + this.pinchValue);
- if (this.pinchValue >= 1) {
- this.twoFingerType++
- Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
- if (this.twoFingerType > 3) {
- this.twoFingerType = 1
- this.isGridMusic = true
- PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
- }
- } else {
- this.twoFingerType--
- Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
- if (this.twoFingerType < 1) {
- this.twoFingerType = 4
- this.columns = 1
- }
- }
- PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
- PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
- this.pinchValue = 1;
- this.scaleValue = 1;
- }
- @Builder
- getList(){
- Stack() {
- Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
- this.getListView()
- }
- .pullDownRatio(this.ratioL)
- .pullToRefresh(true)
- .refreshOffset(0)
- .onOffsetChange((offset: number) => {
- // 越接近最大距离,下拉跟手系数越小。
- this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
- })
- .onStateChange((refreshStatus: RefreshStatus) => {
- console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
- })
- .onRefreshing(async () => {
- if(this.modeType==0){
- this.getHistoryList(false)
- this.asyncCurrentPathOnlyFile()
- }else if(this.modeType == 1){
- workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
- }else if(this.modeType == 2){
- workerInstance.postMessage({ code: 3, data: this.context });
- }else if(this.modeType == 3){
- workerInstance.postMessage({ code: 4, data: this.context });
- }else if(this.modeType == 4){
- this.doSongListTask()
- }
- console.log('onRefreshing test');
- })
- }
- }
- // 扫描当前目录下的文件,不扫描子目录
- asyncCurrentPathOnlyFile(){
- if(this.modeType==0){
- const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
- this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
- taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
- if(this.modeType==0){
- setTimeout(()=>{
- this.isRefreshing =false
- this.deleteCache(this.currentPath)
- this.getSortedFiles(this.currentPath)
- },500)
- }
- }).catch((e:object)=>{
- this.isRefreshing =false
- console.info("onecold task1 catch e: " + e);
- })
- }
- }
- @Builder
- getListView() {
- List({ scroller: this.listScroller }) {
- // ListItemGroup({ header: this.coverHeader() }) {
- 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) { //如果是穿山甲广告
- } 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 })
- }
- // .transition(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }))
- .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.9, y: 0.9 })
- .animation({ duration: 500 }),
- TransitionEffect.scale({ x: 0, y: 0 })))
- .clickEffect({ level: ClickEffectLevel.LIGHT })
- .swipeAction((
- (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
- && item.type !== CommonConstants.TYPE_IS_CSJAD &&
- !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
- start:null,edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
- .onClick(() => {
- if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
- const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
- this.handleFileSelection(item, !isChecked);
- } else {
- 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);
- });
- }
- let curListOffset = this.listScroller.currentOffset()
- // 获取手指信息
- let fingerInfo = event.fingerList[0]
- let clickPercentY =
- (fingerInfo.globalY - Number(this.listArea.globalPosition.y)) / Number(this.listArea.height)
- if (clickPercentY > 0.8 && !this.listScroller.isAtEnd()) {
- let scrollVelocity = clickPercentY > 0.9 ? 4 : 2
- if (this.listMaxScrollOffsetY - curListOffset.yOffset > scrollVelocity + 5) {
- this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset += scrollVelocity })
- }
- } else if (clickPercentY < 0.2 && curListOffset.yOffset >= 0) {
- let scrollVelocity = clickPercentY < 0.1 ? 4 : 2
- if (curListOffset.yOffset > scrollVelocity + 5) {
- this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset -= scrollVelocity })
- }
- }
- })
- .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 + '_' + this.listRefreshKey)
- // }
- }
- .onScrollStart(() => {
- this.isScrolling = true
- this.isShowAlphaBet = true
- })
- .onScrollIndex((start: number,center:number,end:number) => {
- this.selectedIndex = start
- if(start >= 0 && start < this.videoLocalList.length){
- this.selectAlphaBetIndex = this.findAlphaBetIndex(this.videoLocalList[start])
- }
- })
- .onScrollStop(() => {
- if(this.isScrolling){
- this.isScrolling = false
- }
- this.isShowAlphaBet = false
- })
- .scrollBar(BarState.Off)
- .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
- .gesture(PinchGesture({ fingers: 2 })
- .onActionEnd((event: GestureEvent) => {
- this.setlistTwoFingers()
- })
- .onActionUpdate(e => {
- this.scaleValue = this.pinchValue * e.scale
- })
- .onActionStart(e => {
- }))
- .contentStartOffset(this.topSafeHeight + 55)
- .scrollBar(BarState.Off)
- .contentEndOffset(this.bottomBarHeight+this.bottomSafeHeight)
- .cachedCount(10)
- // .reuseId('list_item')
- .borderRadius(20)
- .layoutWeight(1)
- .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
- .lanes(
- new BreakpointType<number>({
- sm: 1,
- md: 2,
- lg: 2,
- xl: 3,
- xxl: 4
- }).getValue(this.currentBreakpoint),
- new BreakpointType<number>({
- sm: 0,
- md: 12,
- lg: 12,
- xl: 16,
- xxl: 20
- }).getValue(this.currentBreakpoint)
- )
- .onAreaChange((oldValue: Area, newValue: Area) => {
- this.listArea = newValue
- if (this.twoFingerType == 3) {
- this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
- } else if (this.twoFingerType == 2) {
- this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
- } else if (this.twoFingerType == 1) {
- this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
- }
- })
- .onScrollFrameBegin((offset: number) => {
- //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
- // if (this.isPhoneLan()) {
- // this.setBarHeightHide(offset)
- // } else
- if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
- (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
- this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
- if (this.isScrollHide) {
- this.setBarHeightHide2(offset)
- } else {
- this.setBarHeightNormal()
- }
- } else {
- this.setBarHeightHide(offset)
- }
- return { offsetRemain: offset };
- })
- //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
- .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
- .onDrop((event?: DragEvent) => {
- try {
- let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
- if (dragData !== undefined) {
- let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
- if (records.length > 0) {
- for (let i = 0; i < records.length; i++) {
- let types = records[i].getTypes();
- if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
- const fileUriUds =
- records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
- let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
- if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
- ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
- this.targetFile = fileUriUds.oriUri;
- this.saveVideoDatas([this.targetFile])
- hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
- }
- }
- }
- } else {
- hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
- }
- } else {
- hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
- }
- } catch (error) {
- const err = error as BusinessError;
- hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
- }
- })
- }
- setBarHeightNormal() {
- this.hideDone = false;
- this.getUIContext().animateTo({
- duration: 300
- }, () => {
- this.bottomBarHeight = 68 + 0;
- this.topBarHeight = 50 + 0;
- this.barOpacity = 1;
- this.barBottomOpacity = 1
- this.currentYOffset = 0;
- this.isHiding = false;
- });
- }
- setBarHeightHide(offset: number) {
- 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;
- this.barBottomOpacity = 1 - this.currentYOffset / 100;
- } else {
- this.topBarHeight = 0;
- this.bottomBarHeight = 0;
- this.barBottomOpacity = 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 = 68 + 0;
- this.topBarHeight = 50 + 0;
- this.barOpacity = 1;
- this.barBottomOpacity = 1
- this.currentYOffset = 0;
- this.isHiding = false;
- });
- }
- }
- //这个方法没隐藏bottomBar,只隐藏topbar
- setBarHeightHide2(offset: number) {
- if (offset > 0 && !this.hideDone) {
- this.currentYOffset += offset;
- if (this.currentYOffset <= 100) {
- this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
- this.barOpacity = 1 - this.currentYOffset / 100;
- } else {
- this.topBarHeight = 0;
- this.barOpacity = 0;
- this.hideDone = true;
- }
- this.isHiding = true;
- }
- if (offset < 0 && this.isHiding) {
- this.hideDone = false;
- this.getUIContext().animateTo({
- duration: 300
- }, () => {
- this.topBarHeight = 50 + 0;
- this.barOpacity = 1;
- this.currentYOffset = 0;
- this.isHiding = false;
- });
- }
- }
- private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
- Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
- switch (item.type) {
- case CommonConstants.TYPE_IS_DIR:
- // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
- let offsetB = 0
- if(this.twoFingerType==4){
- if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
- let cur = this.waterScroller.currentOffset()
- if (cur && typeof cur.yOffset === 'number') {
- offsetB = cur.yOffset
- }
- }
- this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
- }else
- if (this.isGridMusic) {
- if (this.scroller && typeof this.scroller.currentOffset === 'function') {
- let cur = this.scroller.currentOffset()
- if (cur && typeof cur.yOffset === 'number') {
- offsetB = cur.yOffset
- }
- }
- this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
- } else {
- if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
- let cur = this.listScroller.currentOffset()
- if (cur && typeof cur.yOffset === 'number') {
- offsetB = cur.yOffset
- }
- }
- this.mScrollMap.set('lastListDirScrollOffset', offsetB)
- }
- if (item.name === LocalMusic.STR_LOCK_VIDEO) {
- this.showVerifyDialog()
- this.currentTitleName = '私密音频'
- this.currentTitleCover = $r('app.media.alt')
- } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
- this.titleName = '最近播放'
- this.currentTitleCover = $r('app.media.alt')
- this.currentTitleName = '最近播放'
- //加载动画效果
- this.updateListData(this.historyList, true)
- // this.videoLocalList = this.historyList
- if (ArrayUtil.isEmpty(this.historyList)) {
- ToastUtil.showToast('最近播放记录空空如也')
- } else {
- this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
- }
- this.isHistory = true
- } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
- this.titleName = '我的收藏'
- this.currentTitleName = '我的收藏'
- this.currentTitleCover = $r('app.media.alt')
- //加载动画效果
- this.updateListData(this.favList)
- if (ArrayUtil.isEmpty(this.favList)) {
- ToastUtil.showToast('无音乐收藏记录')
- } else {
- this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
- }
- this.isFavMusic = true
- } else {
- this.currentTitleName = item.name
- this.currentPath = item.filePath
- this.currentTitleCover = $r('app.media.alt')
- this.getSortedFiles(this.currentPath)
- }
- //进入歌单的时候的滚动位置在顶部
- if(this.twoFingerType==4){
- setTimeout(() => {
- this.waterScroller.scrollEdge(Edge.Top)
- this.scroller.scrollEdge(Edge.Top)
- }, 380)
- }else{
- if (this.isGridMusic) {
- this.scroller.scrollEdge(Edge.Top)
- }else{
- this.listScroller.scrollEdge(Edge.Top)
- }
- }
- this.rightTopImage = $r('sys.symbol.chevron_left')
- break;
- case CommonConstants.TYPE_IS_ARTIST:
- // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
- let offsetA = 0
- if(this.twoFingerType==4){
- if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
- let cur = this.waterScroller.currentOffset()
- if (cur && typeof cur.yOffset === 'number') {
- offsetA = cur.yOffset
- }
- }
- this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
- }else
- if (this.isGridMusic) {
- if (this.scroller && typeof this.scroller.currentOffset === 'function') {
- let cur = this.scroller.currentOffset()
- if (cur && typeof cur.yOffset === 'number') {
- offsetA = cur.yOffset
- }
- }
- this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
- } else {
- if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
- let cur = this.listScroller.currentOffset()
- if (cur && typeof cur.yOffset === 'number') {
- offsetA = cur.yOffset
- }
- }
- this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
- }
- let mList = this.artistMap.get(item.name)
- if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
- Utility.doSortListAscending(mList)
- this.isCanBack = true
- this.titleName = item.name
- this.currentTitleName = '艺术家:' + item.name
- if (item.pixelMapPath) {
- this.currentTitleCover = item.pixelMapPath
- }
- this.updateListData(mList)
- }
- this.rightTopImage = $r('sys.symbol.chevron_left')
- //进入歌单的时候的滚动位置在顶部
- if(this.twoFingerType==4){
- setTimeout(() => {
- this.waterScroller.scrollEdge(Edge.Top)
- this.scroller.scrollEdge(Edge.Top)
- }, 380)
- }else{
- if (this.isGridMusic) {
- this.scroller.scrollEdge(Edge.Top)
- }else{
- this.listScroller.scrollEdge(Edge.Top)
- }
- }
- break;
- case CommonConstants.TYPE_IS_ALBUM:
- // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
- let offset = 0
- if(this.twoFingerType==4){
- if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
- let cur = this.waterScroller.currentOffset()
- if (cur && typeof cur.yOffset === 'number') {
- offset = cur.yOffset
- }
- }
- this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
- }else
- if (this.isGridMusic) {
- if (this.scroller && typeof this.scroller.currentOffset === 'function') {
- let cur = this.scroller.currentOffset()
- if (cur && typeof cur.yOffset === 'number') {
- offset = cur.yOffset
- }
- }
- this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
- } else {
- if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
- let cur = this.listScroller.currentOffset()
- if (cur && typeof cur.yOffset === 'number') {
- offset = cur.yOffset
- }
- }
- this.mScrollMap.set('lastListAlBumScrollOffset', offset)
- }
- let albumList = this.albumMap.get(item.name)
- if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
- Utility.doSortListAscending(albumList)
- this.isCanBack = true
- this.titleName = item.name
- this.currentTitleName = '专辑:' + item.name
- if (item.pixelMapPath) {
- this.currentTitleCover = item.pixelMapPath
- }
- this.updateListData(albumList)
- this.mScrollMap.set(item.name, this.selectedIndex)
- this.rightTopImage = $r('sys.symbol.chevron_left')
- }
- //进入歌单的时候的滚动位置在顶部
- if(this.twoFingerType==4){
- setTimeout(() => {
- this.waterScroller.scrollEdge(Edge.Top)
- this.scroller.scrollEdge(Edge.Top)
- }, 380)
- }else{
- if (this.isGridMusic) {
- this.scroller.scrollEdge(Edge.Top)
- }else{
- this.listScroller.scrollEdge(Edge.Top)
- }
- }
- break;
- case CommonConstants.TYPE_IS_CSJAD:
- return
- break;
- case CommonConstants.TYPE_LOCAL:
- if(item&&item.filePath.toLowerCase().endsWith('.cue')){
- const cueinfo:CueInfo = await parseCueFile(item.filePath)
- const cueTracks:CueTrack[] = cueinfo.tracks
- console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
- if(ArrayUtil.isNotEmpty(cueTracks)){
- this.showCueDialog(cueTracks,cueinfo)
- }
- // this.showCueSheet = !this.showCueSheet
- return
- }
- if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
- this.stop();
- }
- if (isOpen) {
- this.currentSong = item
- if (index !== undefined) {
- this.curIndex = index
- }
- this.songList = []
- this.songList.push(item)
- this.sonDataSource.pushArrayData(this.songList)
- }else if(isFromSonPlayList){ //点击来自右下角的播放列表
- this.currentSong = item
- if (index !== undefined) {
- this.curIndex = index
- }
- // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
- Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
- }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]
- }
- AppStorage.setOrCreate('currentSong',this.currentSong) ;
- this.videoUrl = this.currentSong.filePath
- this.name = this.currentSong.name
- this.cover = this.currentSong.pixelMapPath
- this.artist = this.currentSong.artist
- LogUtil.info('onecold this.currentSong.cover =' + this.currentSong.pixelMapPath)
- LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
- this.startPlayOrResumePlay()
- break;
- case CommonConstants.TYPE_WEBDAV:
- case CommonConstants.TYPE_SMB:
- case CommonConstants.TYPE_NAVIDROME:
- // 处理网络音频播放(WebDAV/SMB)
- Logger.info(`heanup 处理云端音频播放: ${item.name}, URL: ${item.filePath}`)
- if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
- this.stop();
- }
- if (isOpen) {
- this.currentSong = item
- if (index !== undefined) {
- this.curIndex = index
- }
- this.songList = []
- this.songList.push(item)
- this.sonDataSource.pushArrayData(this.songList)
- } else if (isFromSonPlayList) {
- // 点击来自右下角的播放列表
- this.currentSong = item
- if (index !== undefined) {
- this.curIndex = index
- }
- // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
- Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
- } else {
- // 从全局网络音频列表中查找
- let globalVideoList = this.videoLocalList.filter(video => isRemoteCloudType(video.type)) as VideoItem[];
- this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
- if (this.curIndex === -1 && index !== undefined) {
- this.curIndex = index;
- }
- this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
- this.currentSong = this.songList[this.curIndex];
- this.sonDataSource.pushArrayData(this.songList)
- }
- await this.hydrateRemoteSongFromDb(this.currentSong);
- await this.hydrateRemoteSongFromDb(this.currentSong);
- AppStorage.setOrCreate('currentSong', this.currentSong);
- // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
- this.videoUrl = await setVideoUrlForSong(this.currentSong, {
- context: this.context,
- autoParseMusicName: this.autoParseMusicName
- });
- Logger.info(TAG, `WebDAV URL同步构建完成(分支2): ${this.videoUrl}`);
- this.name = this.currentSong.name
- this.cover = this.currentSong.pixelMapPath
- this.artist = this.currentSong.artist
- Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 完整URL: ${this.videoUrl}`)
- this.startPlayOrResumePlay()
- break;
- }
- }
- private cueComponentId: number = 0
- //显示cue分轨列表对话框
- showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
- this.getUIContext().getPromptAction().openCustomDialog({
- builder: () => {
- this.cueComptentBuilder(cueTracks,cueinfo)
- },
- isModal:true,
- showInSubWindow:false,
- maskColor: Color.Transparent,
- dialogTransition: // 设置弹窗内容显示的过渡效果
- TransitionEffect.translate({ x: 0, y: 390, z: 0 })
- .animation({ duration: 600, curve: Curve.Smooth }),
- maskTransition: // 设置蒙层显示的过渡效果
- TransitionEffect.opacity(0.5)
- .animation({ duration: 600, curve: Curve.Smooth })
- }).then((dialogId: number) => {
- this.cueComponentId = dialogId
- })
- .catch((error: BusinessError) => {
- console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
- })
- }
- @Builder
- cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
- CueComptent({
- title:cueinfo.title,
- cueTracks:cueTracks,
- isLongNameRoLL:this.isLongNameRoLL,
- onCancel:()=>{
- this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
- },
- onDoItemClick: async (item: CueTrack, index: number)=>{
- //获取cueinfo对应的filePath
- let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
- this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
- this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
- console.info('onecold cueinfo.filePath=', cueinfo.filePath)
- console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
- if (this.currentSong){
- if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
- this.stop();//播放之前先停止之前播放。
- }
- this.songList = globalVideoList
- this.sonDataSource.pushArrayData(this.songList)
- if (this.currentSong) {
- try {
- this.videoUrl = await setVideoUrlForSong(this.currentSong, {
- context: this.context,
- autoParseMusicName: this.autoParseMusicName
- });
- } catch (error) {
- Logger.error(TAG, `CUE 点播构建播放地址失败: ${(error as Error).message}`);
- this.videoUrl = this.currentSong.filePath;
- }
- }
- this.name = item.title||this.currentSong.name
- this.cover = this.currentSong.pixelMapPath
- this.artist = item.performer||this.currentSong.artist
- this.currentSong.name = this.name
- this.currentSong.artist = this.artist
- AppStorage.setOrCreate('currentSong',this.currentSong) ;
- this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
- }
- }
- })
- }
- @Builder
- PlayController() {
- Row() {
- if(this.isHiCar()){
- this.playConRigth()
- Column(){
- this.centerName()
- }.layoutWeight(1)
- .onClick(()=>{
- this.showPlayerView()
- })
- this.playConLeft(false)
- }else{
- this.playConLeft()
- this.playConRigth()
- }
- }
- .width('100%')
- .height(this.bottomBarHeight)
- .hitTestBehavior(HitTestMode.Transparent)
- .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
- modalTransition: ModalTransition.NONE,
- onWillDisappear: () => {
- this.setShowPlayFalse()
- },
- // backgroundColor: 'rgba(0, 0, 0, 0.9)',
- })
- .padding({
- left: 16,
- right: 16
- })
- }
- @State isFrontWhite: boolean = false
- @Builder
- centerName() {
- Column() {
- Text(this.currentSong?.name)
- .fontSize(16)
- .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
- .maxLines(1)
- .fontColor(Color.White)
- .fontWeight(500);
- Row() {
- Text(this.currentSong?.artist)
- .margin({ top: 2 })
- .fontSize(13)
- .textAlign(TextAlign.Start)
- .maxLines(1)
- .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
- .fontColor(Color.White)
- }
- .visibility(this.currentSong?.artist? Visibility.Visible:Visibility.None)
- }
- .geometryTransition('name', { follow: true }) // 绑定标识符
- .alignItems(HorizontalAlign.Center)
- }
- @Builder
- playConLeft(isLeft: boolean = true) {
- Row() {
- // RotatingCover({ songLabel: this.currentSong?.pixelMapPath })
- Image( StrUtil.isNotEmpty(this.currentSong?.pixelMapPath)?
- this.currentSong?.pixelMapPath:$r('app.media.music_red'))
- .height(45)
- .objectFit(ImageFit.Contain)
- .alt( $r('app.media.music_red'))
- .fillColor(this.themeColor)
- .borderRadius(8)
- .shadow({
- radius: 10,
- type: ShadowType.BLUR,
- color: 'on_primary'
- })
- .geometryTransition('cover', { follow: true }) // 绑定标识符
- Column() {
- Text(this.currentSong?.name)
- .fontSize(16)
- .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
- .maxLines(1)
- .fontColor(Color.White)
- .fontWeight(500);
- Row() {
- Text(this.currentSong?.artist)
- .margin({ top: 2 })
- .fontSize(13)
- .textAlign(TextAlign.Start)
- .maxLines(1)
- .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
- .fontColor(Color.White)
- }
- .visibility(this.currentSong?.artist? Visibility.Visible:Visibility.None)
- }
- .padding({left:8})
- .geometryTransition('name', { follow: true }) // 绑定标识符
- .alignItems(isLeft?HorizontalAlign.Start:HorizontalAlign.End)
- .margin({ right: isLeft?22:10 })
- .visibility(isLeft? Visibility.Visible:Visibility.None)
- }
- .padding({ right: 18 })
- .layoutWeight(isLeft?1:0)
- .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
- .onClick(() => {
- this.showPlayerView()
- })
- }
- setShowPlayTrue(){
- this.getUIContext()?.animateTo({
- duration: 500,
- curve: Curve.Friction
- }, () => {
- this.isShowPlay = true;
- });
- }
- setShowPlayFalse(){
- this.getUIContext()?.animateTo({
- duration: 500,
- curve: Curve.Friction
- }, () => {
- this.isShowPlay = false;
- });
- }
- //打开播放页
- showPlayerView() {
- if (ArrayUtil.isNotEmpty(this.songList)) {
- this.setShowPlayTrue()
- let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
- this.initLyric(lyricPath);
- this.startAutoHide();
- } else {
- ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
- }
- }
- @Builder
- playConRigth() {
- Row() {
- SymbolGlyph($r('sys.symbol.backward_end_fill'))
- .fontSize(28)
- .fontColor([this.themeColor])
- .alignSelf(ItemAlign.Center)
- .visibility(this.isShowPrecious? Visibility.Visible:Visibility.None)
- .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
- .margin({ left: 8, right: 14 })
- .displayPriority(2)
- .onClick(() => {
- if (ArrayUtil.isNotEmpty(this.songList)) {
- this.playPrevious()
- } else {
- ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
- }
- })
- //播放进度条
- Stack() {
- Progress({
- value: Math.floor(this.progressValue),
- type: ProgressType.Ring,
- })
- .color(this.themeColor)// 进度条前景色为灰色
- .height(38)
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ? $r('app.media.hm_pause') : $r('app.media.hm_play2'))
- .height(36)
- .width(36)
- .displayPriority(3)
- .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
- .fillColor(this.themeColor)
- .onClick(() => {
- if (ArrayUtil.isNotEmpty(this.songList)) {
- console.info('onecold playOrPause 4642')
- this.playOrPause()
- } else {
- ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
- }
- })
- }
- SymbolGlyph($r('sys.symbol.forward_end_fill'))
- .fontSize(28)
- .fontColor([this.themeColor])
- .alignSelf(ItemAlign.Center)
- .margin({
- right: 14,
- left: 14
- })
- .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
- .displayPriority(2)
- .onClick(() => {
- if (ArrayUtil.isNotEmpty(this.songList)) {
- this.playNext()
- } else {
- ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
- }
- })
- Image($r('app.media.hm_playlist'))
- .height(26)
- .width(26)
- .displayPriority(1)
- .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
- .fillColor(this.themeColor)
- .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
- height: '95%',
- dragBar: true,
- showClose: true,
- blurStyle: BlurStyle.Thin,
- preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
- backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
- 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
- LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
- this.scrollIndex()
- } else {
- ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
- }
- })
- }
- }
- scrollIndex(){
- try {
- setTimeout(() => {
- this.getUIContext()?.animateTo({ duration: 555 }, () => {
- if(this.curIndex>60){
- this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
- }else{
- this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
- }
- })
- }, 123)
- }catch (error) {
- console.error(`onecold scrollIndex出错: ${error}`);
- }
- }
- //播放列表布局
- @Builder
- PlayListSheet() {
- Column() {
- this.PlayList()
- }
- .width('100%')
- .height('100%')
- }
- @State titleStr: string = ''
- @State ablumStr: string = ''
- @State artistStr: string = ''
- @State lyricConStr: string = ''
- @State currentEditItem: string = ''
- @State yearStr: string = ''
- @State trackStr: string = ''
- @State genreStr: string = ''
- @State imagePathStr: string = ''
- @State albumArtistStr: string = ''
- @State composerStr: string = ''
- @State lyricistStr: string = ''
- @State commentStr: string = ''
- @State discStr: string = ''
- doUpdateData() {
- setTimeout(() => {
- if (this.modeType === 0) {
- this.deleteCache(this.currentPath)
- this.getSortedFiles(this.currentPath)
- }else if (this.modeType === 1){
- workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
- }
- }, 500)
- }
- doAllUpdateData() {
- setTimeout(() => {
- if (this.modeType === 0) {
- this.deleteCache(this.currentPath)
- this.getSortedFiles(this.currentPath)
- }
- workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
- workerInstance.postMessage({ code: 3, data: this.context });
- workerInstance.postMessage({ code: 4, data: this.context });
- }, 999)
- }
- //编辑信息
- async doEdit(item: VideoItem) {
- if (!item) {
- return
- }
- if (StrUtil.isEmpty(this.titleStr)) {
- ToastUtil.showToast('标题不能为空')
- return
- }
- //内嵌音乐标签不能开启监听
- // this.deletionWatcher?.stop();
- DialogHelper.showLoadingDialog()
- await PermissionUtil.activatePermission(item.filePath)
- let tempOutPath = ''
- // 如果不是 packName 包下的文件,则直接路径用this.currentPath
- if(!item.filePath.toLowerCase().includes(this.packName)){
- tempOutPath = this.currentPath + '/' + item.fileName
- }
- console.info('onecold tempOutPath ='+tempOutPath)
- //用户更改了封面,那就内嵌下封面
- if(StrUtil.isNotEmpty(this.imagePathStr)){
- const resultCover:boolean = await changeMusicCover(this.context,
- item.filePath,this.imagePathStr,true,tempOutPath);
- this.imagePathStr = ''
- if(resultCover){
- ToastUtil.showToast('内嵌封面成功')
- }
- }
- const metadata:FFMpegTags = {
- title: this.titleStr,
- artist: this.artistStr,
- album: this.ablumStr,
- TYER:this.yearStr,
- genre:this.genreStr,
- track:this.trackStr,
- album_artist:this.albumArtistStr,
- TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
- COMPOSER:this.composerStr,
- lyricist:this.lyricistStr,
- TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
- comment:this.commentStr,
- disc:this.discStr,
- };
- let newInput = item.filePath
- //内嵌标签歌路径如果不是包含包名,输入newInput要赋值tempOutPath,然后tempOutPath为空
- if(!item.filePath.toLowerCase().includes(this.packName)&&FileUtil.accessSync(tempOutPath)){
- newInput = tempOutPath
- tempOutPath = ''
- }
- //内嵌下标签的值,设置overwrite为true会直接修改原文件
- const result:boolean = await repairAudioMetadata(
- newInput,
- this.lyricConStr,
- metadata,
- true,
- tempOutPath
- );
- if (result) {
- if(!item.filePath.includes(this.packName)){
- //内嵌成功的歌路径如果不是包含包名,则要入库
- let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newInput,
- CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
- this.table.insert(newItem, (id: number) => {
- //加入数据库
- if(this.modeType==0){
- this.deleteCache(this.currentPath)
- this.getSortedFiles(this.currentPath)
- }
- });
- }
- const task = new taskpool.Task(
- updateInfoDb,
- this.context,
- item.filePath,
- this.titleStr,
- this.artistStr,
- this.ablumStr,
- this.lyricConStr,
- this.yearStr,this.genreStr,
- this.trackStr,this.albumArtistStr,
- this.composerStr, this.lyricistStr,
- this.commentStr,this.discStr
- );
- taskpool.execute(task, taskpool.Priority.HIGH).then((result) => {
- if (result) {
- console.log(" onecold 编辑信息成功,数据库已同步");
- ToastUtil.showToast('内嵌音乐标签成功')
- this.isShowMoreView = false
- this.name = this.titleStr
- this.syncEditedFields(item)
- if (item.filePath == this.currentSong?.filePath) {
- this.currentSong.name = this.titleStr
- this.artist = this.artistStr
- this.currentSong.artist = this.artistStr
- this.currentSong.album = this.ablumStr
- this.currentSong.year = this.yearStr
- this.currentSong.genre = this.genreStr
- this.currentSong.track = this.trackStr
- this.currentSong.lyricContent = this.lyricConStr
- this.currentSong.ALBUMARTIST = this.albumArtistStr
- this.currentSong.COMPOSER = this.composerStr
- this.currentSong.LYRICIST = this.lyricistStr
- this.currentSong.COMMENT = this.commentStr
- }
- this.syncListsAfterEdit(item.filePath)
- this.doUpateEditedFields(item)
- //this.doUpdateData()
- } else {
- // ToastUtil.showToast('保存失败' + error?.toString())
- console.error(" onecold 编辑信息数据库失败 ");
- }
- // 关闭进度条
- DialogHelper.closeLoading();
- }).catch((error: Error) => {
- // 关闭进度条
- DialogHelper.closeLoading();
- console.error('onecold Subtitle sync failed:', error);
- });
- console.log(' onecold 元数据标签更新成功,');
- } else {
- // 关闭进度条
- DialogHelper.closeLoading();
- ToastUtil.showToast('内嵌音乐标签失败')
- console.log('onecold 内嵌音乐标签失败');
- }
- this.longItemFilePath = ''
- this.tempLyricContent = ''
- this.isShowEdit = false
- }
- // 内嵌标签更新当前内嵌的Item
- async doUpateEditedFields(item: VideoItem) {
- // 找到当前项在 videoLocalList 中的索引
- const index = this.videoLocalList.findIndex(video => video.filePath === item.filePath);
- if (index !== -1) {
- // 使用已初始化的MediaTable实例从数据库查询歌曲信息
- const updatedItem = await this.table.queryVideoByFilePath(item.filePath)
- // 只有当查询结果不为 null 时才更新列表
- if (updatedItem !== null) {
- // 更新 videoLocalList 中的项(通过创建新数组触发响应式更新)
- this.videoLocalList = [
- ...this.videoLocalList.slice(0, index),
- updatedItem,
- ...this.videoLocalList.slice(index + 1)
- ];
- // 同步更新 LazyDataSource
- this.dataSource.pushArrayData(this.videoLocalList)
- } else {
- ToastUtil.showToast('未找到更新的数据');
- }
- }
- DialogHelper.closeLoading();
- }
- @Builder
- editSheet(item: VideoItem) {
- Scroll() {
- Column() {
- this.editDetail(item)
- }
- }
- .width('100%')
- .height('100%')
- }
- @Builder
- editDetail(item: VideoItem) {
- Column() {
- if (item) {
- Row() {
- Stack() {
- Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
- this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
- StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
- item.pixelMapPath)
- .fillColor(this.themeColor)
- .height(88)
- .width(88)
- .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
- .borderRadius(12)
- .clip(true)
- .opacity(this.opacityItem)// 绑定透明度
- .margin({ left: 25 })
- }
- .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
- .onClick(async () => {
- const imagePath:string | undefined = await this.goSelectImage(item);
- if (imagePath) {
- //用户更改过图片
- this.imagePathStr = imagePath
- }
- })
- .width('28%')
- Row() {
- Column() {
- Text(item.name)
- .fontSize(17)
- .maxLines(1)
- .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
- .animation({
- duration: 555,
- curve: 'Linear',
- })
- .fontColor(this.themeColor)
- .margin({ left: 8 })
- Row() {
- Text(item.artist)
- .fontSize(14)
- .maxLines(1)
- .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
- .padding({ top: 8 })
- .fontColor(this.themeColor)
- .margin({ left: 8 })
- }
- }
- .height('100%')
- .width(100)
- .layoutWeight(1)
- .justifyContent(FlexAlign.Center)
- .alignItems(HorizontalAlign.Start)
- Column() {
- Button({ type: ButtonType.Capsule, stateEffect: true }) {
- Row(){
- SymbolGlyph($r('sys.symbol.picture'))
- .fontSize(18)
- .fontColor([Color.White])
- Text('获取封面')
- .margin({ left: 4 })
- .fontSize(11)
- .fontColor(Color.White)
- .fontWeight(480)
- .textAlign(TextAlign.Center)
- }
- .justifyContent(FlexAlign.Center)
- }
- .height(38)
- .width(100)
- .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
- .backgroundColor(this.themeColor)
- .stateEffect(true)
- .margin({ right: 35 })
- .onClick(async () => {
- if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
- this.showTipsDialog();
- return; // Return empty string when no API is configured
- }
- const imagePath:string | undefined = await this.doSearchCover(item,
- this.titleStr,this.artistStr);
- console.info('onecold imagePath = '+imagePath)
- if (StrUtil.isNotEmpty(imagePath)) {
- //用户更改过图片
- this.imagePathStr = imagePath
- ToastUtil.showToast('获取封面成功')
- }else{
- ToastUtil.showToast('获取封面失败,请重试')
- }
- })
- Button({ type: ButtonType.Capsule, stateEffect: true }) {
- Row(){
- SymbolGlyph($r('sys.symbol.input_mode'))
- .fontSize(18)
- .fontColor([Color.White])
- Text('获取歌词')
- .margin({ left: 4 })
- .fontSize(11)
- .fontColor(Color.White)
- .fontWeight(480)
- .textAlign(TextAlign.Center)
- }
- .justifyContent(FlexAlign.Center)
- }
- .height(38)
- .width(100)
- .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
- .backgroundColor(this.themeColor)
- .stateEffect(true)
- .margin({ top: 9, right: 35 })
- .onClick(async () => {
- //判断有没有设置api
- let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
- if (StrUtil.isEmpty(apiUrl)) {
- this.isLyricSetting = false
- this.showTipsDialog()
- return
- }
- let res: string | undefined = await getApiLyric(apiUrl,
- this.titleStr, this.artistStr, false);
- if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
- this.lyricConStr = res;
- ToastUtil.showToast('获取歌词成功')
- }else{
- ToastUtil.showToast('获取歌词失败,请重试')
- }
- })
- }
- .justifyContent(FlexAlign.Start)
- }
- .height('100%')
- .justifyContent(FlexAlign.Start)
- .layoutWeight(1)
- }
- .width('100%')
- .height(98)
- Row() {
- Text('标题:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- TextInput({ text: item.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: item.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: item.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() {
- Column(){
- Column(){
- Text('歌词:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ top:9,left: 22 })
- Button({ type: ButtonType.Capsule, stateEffect: true }) {
- SymbolGlyph($r('sys.symbol.trash_fill'))
- .fontSize(25)
- .alignSelf(ItemAlign.Center)
- .margin({ left: 22,top:25})
- }
- .backgroundColor(Color.Transparent)
- .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
- Visibility.None:Visibility.Visible)
- .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
- .onClick(()=>{
- this.lyricConStr = ''
- this.lyricContent = ''
- this.tempLyricContent = ''
- })
- Button({ type: ButtonType.Capsule, stateEffect: true }) {
- SymbolGlyph($r('sys.symbol.plus'))
- .fontSize(25)
- .alignSelf(ItemAlign.Center)
- .margin({ left: 22,top:25})
- }
- .backgroundColor(Color.Transparent)
- .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
- .onClick( ()=>{
- this.callFilePickerSelectFileForLyric()
- })
- Button({ type: ButtonType.Capsule, stateEffect: true }) {
- SymbolGlyph($r('sys.symbol.traditional_square'))
- .fontSize(25)
- .alignSelf(ItemAlign.Center)
- .margin({ left: 22,top:25})
- }
- .backgroundColor(Color.Transparent)
- .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
- Visibility.None:Visibility.Visible)
- .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
- .onClick( ()=>{
- let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
- this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
- })
- Button({ type: ButtonType.Capsule, stateEffect: true }) {
- Image($r('app.media.jianti'))
- .height(25)
- .fillColor($r('app.color.text_color'))
- .alignSelf(ItemAlign.Center)
- .margin({ left: 22,top:25})
- }
- .backgroundColor(Color.Transparent)
- .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
- Visibility.None:Visibility.Visible)
- .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
- .onClick( ()=>{
- let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
- this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
- })
- }
- .layoutWeight(1)
- }
- TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
- this.tempLyricContent })
- .type(TextAreaType.NORMAL)
- .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
- .fontSize(14)
- .layoutWeight(1)
- .fontColor($r('app.color.text_color'))
- .margin({ right: 20, left: 10 })
- .onChange((val: string) => {
- this.lyricConStr = val
- })
- }
- .width('100%')
- .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('年份:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- TextInput({ text: item.year })
- .height(40)
- .maxLines(1)
- .fontSize(14)
- .type(InputType.Number)
- .layoutWeight(1)
- .fontColor($r('app.color.text_color'))
- .margin({ right: 20, left: 10 })
- .onChange((val: string) => {
- this.yearStr = 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:item.track=='未知'?'': item.track })
- .height(40)
- .maxLines(1)
- .fontSize(14)
- .type(InputType.Number)
- .layoutWeight(1)
- .fontColor($r('app.color.text_color'))
- .margin({ right: 20, left: 10 })
- .onChange((val: string) => {
- this.trackStr = 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:item.disc })
- .height(40)
- .maxLines(1)
- .fontSize(14)
- .type(InputType.Number)
- .layoutWeight(1)
- .fontColor($r('app.color.text_color'))
- .margin({ right: 20, left: 10 })
- .onChange((val: string) => {
- this.discStr = 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: item.genre })
- .height(40)
- .maxLines(1)
- .fontSize(14)
- .layoutWeight(1)
- .fontColor($r('app.color.text_color'))
- .margin({ right: 20, left: 10 })
- .onChange((val: string) => {
- this.genreStr = 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: item.ALBUMARTIST })
- .height(40)
- .maxLines(1)
- .fontSize(14)
- .layoutWeight(1)
- .fontColor($r('app.color.text_color'))
- .margin({ right: 20, left: 10 })
- .onChange((val: string) => {
- this.albumArtistStr = 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: item.COMPOSER })
- .height(40)
- .maxLines(1)
- .fontSize(14)
- .layoutWeight(1)
- .fontColor($r('app.color.text_color'))
- .margin({ right: 20, left: 10 })
- .onChange((val: string) => {
- this.composerStr = 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: item.LYRICIST })
- .height(40)
- .maxLines(1)
- .fontSize(14)
- .layoutWeight(1)
- .fontColor($r('app.color.text_color'))
- .margin({ right: 20, left: 10 })
- .onChange((val: string) => {
- this.lyricistStr = 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: item.COMMENT })
- .height(40)
- .maxLines(1)
- .fontSize(14)
- .layoutWeight(1)
- .fontColor($r('app.color.text_color'))
- .margin({ right: 20, left: 10 })
- .onChange((val: string) => {
- this.commentStr = val
- })
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Button('保存')
- .fontColor(Color.White)
- .layoutWeight(1)
- .height(50)
- .width(100)
- .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
- .backgroundColor(this.themeColor)
- .stateEffect(true)
- .margin({ right: 20, bottom: 20 })
- .onClick(async () => {
- this.doEdit(item)
- })
- Button('取消')
- .fontColor(Color.White)
- .layoutWeight(1)
- .height(50)
- .width(100)
- .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
- .backgroundColor(this.themeColor)
- .stateEffect(true)
- .margin({ left: 20, bottom: 20 })
- .onClick(async () => {
- if(this.isGridMusic){
- this.longItemFilePath =''
- }else{
- this.isShowEdit = false
- }
- this.setEditStrEmpty()
- if(this.isShowPlay){
- this.isShowEdit = false
- }
- })
- }
- .margin({
- left: 38,
- right: 38,
- top: 10,
- bottom: 10
- })
- .width(250)
- .height(60)
- }
- }
- .margin({ bottom: 20 })
- }
- setEditStrEmpty(){
- this.imagePathStr = ''
- this.lyricConStr = ''
- this.artistStr = ''
- this.titleStr = ''
- this.ablumStr = ''
- this.genreStr = ''
- this.yearStr = ''
- this.trackStr = ''
- this.albumArtistStr = ''
- this.composerStr = ''
- this.lyricistStr = ''
- this.commentStr = ''
- this.discStr = ''
- }
- initEditFields(item?: VideoItem) {
- if (!item) {
- this.setEditStrEmpty()
- return
- }
- this.imagePathStr = ''
- this.titleStr = item.name ?? ''
- this.artistStr = item.artist ?? ''
- this.ablumStr = item.album ?? ''
- this.genreStr = item.genre ?? ''
- this.yearStr = item.year ?? ''
- this.trackStr = item.track ?? ''
- this.albumArtistStr = item.ALBUMARTIST ?? ''
- this.composerStr = item.COMPOSER ?? ''
- this.lyricistStr = item.LYRICIST ?? ''
- this.commentStr = item.COMMENT ?? ''
- this.discStr = item.disc ?? ''
- this.lyricConStr = item.lyricContent ?? ''
- }
- private syncEditedFields(target?: VideoItem) {
- if (!target) {
- return
- }
- target.name = this.titleStr
- target.artist = this.artistStr
- target.album = this.ablumStr
- target.lyricContent = this.lyricConStr
- target.year = this.yearStr
- target.genre = this.genreStr
- target.track = this.trackStr
- target.ALBUMARTIST = this.albumArtistStr
- target.COMPOSER = this.composerStr
- target.LYRICIST = this.lyricistStr
- target.COMMENT = this.commentStr
- target.disc = this.discStr
- }
- private replaceItemInList(list: Array<VideoItem> | undefined, filePath: string,
- apply?: (next: Array<VideoItem>) => void) {
- if (!list || ArrayUtil.isEmpty(list)) {
- return
- }
- const index = list.findIndex((video: VideoItem) => video.filePath === filePath)
- if (index < 0) {
- return
- }
- const nextList = [...list]
- this.syncEditedFields(nextList[index])
- apply?.(nextList)
- }
- private syncListsAfterEdit(filePath: string) {
- this.replaceItemInList(this.videoLocalList, filePath, (next: Array<VideoItem>) => {
- this.videoLocalList = next
- this.dataSource.pushArrayData(next)
- })
- this.replaceItemInList(this.songList, filePath, (next: Array<VideoItem>) => {
- this.songList = next
- this.sonDataSource.pushArrayData(next)
- })
- this.replaceItemInList(this.favList, filePath, (next: Array<VideoItem>) => {
- this.favList = next
- })
- this.replaceItemInList(this.historyList, filePath, (next: Array<VideoItem>) => {
- this.historyList = next
- })
- this.replaceItemInList(this.currentSongList, filePath, (next: Array<VideoItem>) => {
- this.currentSongList = next
- })
- this.replaceItemInList(this.mediaKuList, filePath, (next: Array<VideoItem>) => {
- this.mediaKuList = next
- })
- this.replaceItemInList(this.filteredList, filePath, (next: Array<VideoItem>) => {
- this.filteredList = next
- })
- this.replaceItemInList(this.artistList, filePath, (next: Array<VideoItem>) => {
- this.artistList = next
- })
- this.replaceItemInList(this.albumList, filePath, (next: Array<VideoItem>) => {
- this.albumList = next
- })
- this.listRefreshKey++
- }
- @Builder
- detailSheet(item:VideoItem) {
- Scroll() {
- Column() {
- this.songDetail(item)
- }
- }
- .width('100%')
- .height('100%')
- }
- @Builder
- songDetail(currentItem:VideoItem) {
- Column() {
- if (currentItem) {
- Row() {
- Stack() {
- Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.music_red') :
- currentItem.pixelMapPath)
- .fillColor(this.themeColor)
- .height(80)
- .width(80)
- .borderRadius(10)
- .opacity(this.opacityItem)// 绑定透明度
- .margin({ left: 22 })
- }
- Column() {
- Column() {
- Text(currentItem.name)
- .fontSize(16)
- .maxLines(1)
- .animation({
- duration: 555,
- curve: 'Linear',
- })
- .fontColor($r('app.color.text_color'))
- .margin({ left: 15 })
- }
- .height('100%')
- .width('100%')
- .justifyContent(FlexAlign.Center)
- .alignItems(HorizontalAlign.Start)
- }
- .height('100%')
- }
- .width('100%')
- .height(90)
- .justifyContent(FlexAlign.SpaceBetween)
- Row() {
- Text('艺术家:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(currentItem?.artist ? currentItem.artist : '未知歌手')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 10 })
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('专辑名:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(currentItem?.album ?currentItem.album : '未知专辑')
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor($r('app.color.text_color'))
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('时长:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(StrUtil.isEmpty(currentItem.duration)?
- (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor($r('app.color.text_color'))
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('采样率:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(Utility.convertToKHz(currentItem.sampleRate))
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor($r('app.color.text_color'))
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('比特率:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(currentItem.bit_rate)
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor($r('app.color.text_color'))
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('位深:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(`${currentItem.bits_per_raw_sample} bits`)
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor($r('app.color.text_color'))
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('声道:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(`${currentItem.channels}`)
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor($r('app.color.text_color'))
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('声道布局:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(`${currentItem.channel_layout}`)
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor($r('app.color.text_color'))
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('起始播放点:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(`${currentItem.start_time}`)
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor($r('app.color.text_color'))
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('风格:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(currentItem.genre)
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor($r('app.color.text_color'))
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('发行时间:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(currentItem.year)
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor($r('app.color.text_color'))
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('质量评分:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(currentItem.probe_score+"")
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor($r('app.color.text_color'))
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('音轨号:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(currentItem.track)
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor($r('app.color.text_color'))
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('碟号:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(currentItem.disc)
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor($r('app.color.text_color'))
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('专辑艺术家:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(currentItem.ALBUMARTIST)
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor($r('app.color.text_color'))
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('作曲家:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(currentItem.COMPOSER)
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor($r('app.color.text_color'))
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('作词家:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(currentItem.LYRICIST)
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor($r('app.color.text_color'))
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('注释:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(currentItem.COMMENT)
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor($r('app.color.text_color'))
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('格式:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(Utility.formatMimeType(currentItem.mimeType))
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor($r('app.color.text_color'))
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('播放次数:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(currentItem.playCount?.toString())
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor($r('app.color.text_color'))
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('流数量:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(currentItem.nb_streams?.toString())
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor($r('app.color.text_color'))
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('文件大小:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(currentItem.size)
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor($r('app.color.text_color'))
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('文件名:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(currentItem.fileName)
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor($r('app.color.text_color'))
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('修改时间:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(currentItem.cTime)
- .fontSize(14)
- .margin({ left: 10 })
- .fontColor($r('app.color.text_color'))
- .layoutWeight(1)
- }
- .width('100%')
- .margin({ top: 10, bottom: 10 })
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('存放目录:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(currentItem.filePath)
- .fontSize(12)
- .margin({ left: 10 })
- .fontColor($r('app.color.text_color'))
- .layoutWeight(1)
- }
- .margin({ top: 10, bottom: 10 })
- .width('100%')
- .justifyContent(FlexAlign.Start)
- Row() {
- Text('内嵌歌词:')
- .fontSize(14)
- .fontColor($r('app.color.text_color'))
- .margin({ left: 22 })
- Text(currentItem.lyricContent)
- .fontSize(12)
- .copyOption(CopyOptions.InApp)
- .margin({ left: 10 })
- .fontColor($r('app.color.text_color'))
- .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
- // 预设时间选项
- 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, bottom: 8 });
- Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
- ForEach(this.presetTimes, (minutes: number, index: number) => {
- // 单行时间选项容器
- Row() {
- // 文字描述区域
- Text(this.getDisplayText(minutes))
- .fontSize(15)
- .fontColor(minutes === this.selectedMinutes ? this.themeColor :
- $r('app.color.text_color'))// 选中态颜色变化
- .textAlign(TextAlign.Start)
- .layoutWeight(1); // 占据剩余空间
- // 复选框样式的选择器
- Row() {
- if (minutes === this.selectedMinutes) {
- // 选中状态 - 带勾号的圆形复选框
- Row() {
- // 使用系统内置的勾号图标
- Image($r('sys.media.ohos_ic_public_ok'))
- .width(14)
- .height(14)
- .fillColor(Color.White)
- }
- .width(24)
- .height(24)
- .borderRadius(12)
- .backgroundColor(this.themeColor)
- .justifyContent(FlexAlign.Center)
- .alignItems(VerticalAlign.Center)
- } else {
- // 未选中状态的圆形边框
- Row()
- .width(24)
- .height(24)
- .borderRadius(12)
- .border({
- width: 2,
- color: $r('app.color.text_color'),
- style: BorderStyle.Solid
- })
- .backgroundColor(Color.Transparent)
- }
- }
- .width(24)
- .height(24)
- .margin({ left: 20 })
- .justifyContent(FlexAlign.Center)
- .alignItems(VerticalAlign.Center)
- }
- .width('100%')
- .padding({
- top: 18,
- bottom: 18,
- left: 18,
- right: 18
- })
- .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
- $r('app.color.bottom_control_background')) // 选中背景高亮
- .borderRadius(12)
- .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
- .margin({ bottom: 18 })
- .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
- });
- }
- .width('100%')
- .padding(16)
- }
- }
- // 获取显示文本
- 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) {
- const customMinutes = Number(content);
- if (customMinutes > 0) {
- this.handleTimeSelect(customMinutes); // 设置自定义时间
- ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
- }
- }
- }
- });
- } else {
- 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;
- 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)
- .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
- .backgroundColor(this.themeColor)
- .margin(5)
- .onClick(() => {
- this.addToNextPlay(item);
- })
- Button() {
- Image($r('app.media.close'))
- .fillColor(Color.White)
- .width(20)
- }
- .width(40)
- .height(40)
- .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
- .type(ButtonType.Circle)
- .backgroundColor(this.themeColor)
- .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)
- .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
- .type(ButtonType.Circle)
- .backgroundColor(this.themeColor)
- .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)
- if(this.modeType==4&&this.playlistTable){
- updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
- }
- }
- @Builder
- PlayList() {
- List({ scroller: this.playListScroller }) {
- 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' // 可选动画曲线
- })
- .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
- TransitionEffect.scale({ x: 0, y: 0 })))
- .clickEffect({ level: ClickEffectLevel.MIDDLE })
- //拖动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 + '_' + this.listRefreshKey)
- }
- .width('100%')
- .height('100%')
- // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
- // .animation({ duration: 500, curve: Curve.Ease }))
- .cachedCount(10)
- .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
- .gesture(PinchGesture({ fingers: 2 })
- .onActionEnd((event: GestureEvent) => {
- this.setSonListTwoFingers()
- })
- .onActionUpdate(e => {
- this.scaleValue = this.pinchValue * e.scale
- })
- .onActionStart(e => {
- }))
- .padding({
- bottom: 0
- })
- }
- setSonListTwoFingers() {
- this.pinchValue = this.scaleValue;
- Logger.info('this.pinchValue = ' + this.pinchValue);
- if (this.pinchValue >= 1) {
- this.sonTwoFingerType++
- Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
- if (this.sonTwoFingerType > 3) {
- this.sonTwoFingerType = 1
- PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
- }
- } else {
- this.sonTwoFingerType--
- Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
- if (this.sonTwoFingerType < 1) {
- this.sonTwoFingerType = 1
- }
- }
- PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
- this.pinchValue = 1;
- this.scaleValue = 1;
- }
- @State sonTwoFingerType:number = 3
- @Builder
- private MusicItemSon(item: VideoItem, index?: number) {
- Button({ type: ButtonType.Normal, stateEffect: true }) {
- Row() {
- Stack() {
- Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
- .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
- .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
- .alt($r('app.media.music_red'))
- .fillColor(this.themeColor)
- .borderRadius('100%')
- .clip(true)
- .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
- .draggable(false)// 禁止长按手势拖动
- .autoResize(true) // 重采样,可减少内存占用
- .margin({ left: 20 })
- }
- .width('15%')
- Column() {
- Column() {
- Text(this.isShowFileName?item.fileName :item.name)
- .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
- .fontColor(this.curIndex === index ? this.themeColor :
- this.isFrontWhite ? Color.White : $r('app.color.text_color'))
- .maxLines(1)
- .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
- Row() {
- Column(){
- Text(item.md5Str?.includes('Lossless')?
- Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
- .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
- .padding({ top: 3,right:6,left:6,bottom:3 })
- .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
- $r('app.color.text_color'))
- .fontWeight(500)
- .borderRadius(12)
- .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
- .backgroundColor('#FFC107')
- }
- .padding({ top: 8 })
- Text(StrUtil.isEmpty(item.artist) ? item.duration :
- item.artist + ' ' + item?.duration)
- .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
- .padding({ top: 8 })
- .maxLines(1)
- .fontColor(this.curIndex === index ? this.themeColor :
- this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
- .margin({ left: this.sonTwoFingerType == 3 ? 5 : 3 })
- Blank()
- Text(item.size)
- .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
- .padding({ top: 8 })
- .maxLines(1)
- .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%')
- }
- }
- .backgroundColor(Color.Transparent)
- .width('100%')
- .reuseId('son_item')
- .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
- .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()
- }
- .transition(TransitionEffect.asymmetric(
- TransitionEffect.opacity(1),
- TransitionEffect.OPACITY
- ))
- .visualEffect(deviceInfo.sdkApiVersion>=20&&this.bgController?
- new hdsEffect.HdsEffectBuilder()
- .shaderEffect({
- effectType: hdsEffect.EffectType.UV_BACKGROUND_FLOW_LIGHT,
- animation: {
- duration: 10000,
- iterations: -1,
- autoPlay: true,
- onFinish: ()=> {
- console.info('Succeeded in finishing');
- }
- },
- controller: this.bgController,
- })
- .buildEffect():null)
- .height('100%')
- .width('100%')
- .onDisAppear(() => {
- this.translateY = 0;
- })
- .translate({ y: this.translateY })
- .gesture(
- PanGesture(this.panOption)
- .onActionUpdate((event?: GestureEvent) => {
- if (event) {
- // 只允许向下滑动,向上滑动时限制为0
- this.translateY = Math.max(0, event.offsetY);
- this.getUIContext().animateTo({
- duration: 500,
- curve: Curve.Sharp
- }, () => {
- this.scaleValueImage = Math.min(1, Math.max(0.3, 1 - event.offsetY / 350));
- console.info('onecold scaleValueImage:', this.scaleValueImage)
- this.scaleValueText =Math.min(1, Math.max(0.6, 1 - event.offsetY / 400));
- })
- }
- })
- .onActionEnd((event?: GestureEvent) => {
- // 使用更低的阈值和滑动速度判断
- const minDistance = 300; // 最小滑动距离 100vp
- const minVelocity = 500; // 最小滑动速度
- // 获取滑动速度(如果可用)
- const velocity = event?.velocityY || 0;
- // 判断是否应该关闭:距离足够 或者 速度足够快
- const shouldClose = this.translateY > minDistance || velocity > minVelocity;
- if (shouldClose) {
- // 添加关闭动画
- this.getUIContext().animateTo({
- duration: 600,
- curve: Curve.Friction
- }, () => {
- this.isShowPlay = false;
- this.scaleValueImage = 1
- this.scaleValueText = 1
- this.translateY = 0;
- })
- } else {
- // 回弹动画
- this.getUIContext().animateTo({
- duration: 600,
- curve: Curve.Friction
- }, () => {
- this.scaleValueImage = 1
- this.scaleValueText = 1
- 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
- @State barBottomOpacity: number = 1
- private hideDone: boolean = false;
- @State currentYOffset: number = 0;
- @State bottomBarHeight: number = 68;
- private isHiding: boolean = false;
- //是否是Pura X外屏,或者小屏幕
- isPuraWP() {
- return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
- && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
- }
- //是否是Pura X外屏,或者小屏幕,手机横屏
- /**
- * 是否是Pura X外屏,或者小屏幕,手机横屏
- * @returns
- */
- 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() {
- // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
- // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
- LogUtil.info('hicar isPhoneLan width= ' + this.windowWidth);
- LogUtil.info('hicar isPhoneLan height= ' + this.windowHeight);
- LogUtil.info(`twocold hicarWindow size: ${this.windowWidth}x${this.windowHeight}, this.isHiCarStatus: ${this.isHiCarStatus}`);
- LogUtil.info(`twocold hicar Window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall: ${this.isHiCarSmall()}`);
- if (this.isHiCarKuanBianPing()) {
- return true
- }
- if (this.isHiCar()) {
- return false
- }
- if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
- && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
- && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
- return true
- }
- return false
- }
- //是不是1920x720的hicar的屏幕分辨率
- isHiCarKuanBianPing(){
- if(!this.isHiCar()){
- return false
- }
- const hiCarAspectRatios: HiCarAspectRatio[] = [
- { ratio: 1920 / 720, name: "1920x720" },
- ];
- const currentRatio: number = this.windowWidth / this.windowHeight;
- const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
- LogUtil.info('twocold isHiCarKuanBianPing currentRatio = ' + currentRatio)
- for (const hiCarRatio of hiCarAspectRatios) {
- LogUtil.info('twocold isHiCarKuanBianPing hiCarRatio= ' + hiCarRatio.ratio)
- LogUtil.info('twocold isHiCarKuanBianPing Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
- if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
- // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
- //宽扁平的尺寸设置列表展示
- this.twoFingerType ==3
- this.isGridMusic = false
- return true;
- }
- }
- return false;
- }
- //是不是hicar的屏幕分辨率
- isHiCarSmall() {
- if(!this.isHiCar()){
- return false
- }
- if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
- {
- this.columns = 6
- return false
- }
- const hiCarAspectRatios: HiCarAspectRatio[] = [
- { ratio: 800 / 480, name: "800x480" },
- { ratio: 1280 / 720, name: "1280x720" },
- { ratio: 1920 / 1080, name: "1920x1080" },
- ];
- const currentRatio: number = this.windowWidth / this.windowHeight;
- const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
- LogUtil.info('twocold isHiCarSmall currentRatio = ' + currentRatio)
- for (const hiCarRatio of hiCarAspectRatios) {
- LogUtil.info('twocold isHiCarSmall hiCarRatio= ' + hiCarRatio.ratio)
- LogUtil.info('twocold isHiCarSmall Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
- LogUtil.info('twocold isHiCarSmall isHiCarStatus= ' + this.isHiCarStatus);
- if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
- // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
- //宽扁平的尺寸设置列表展示
- return true;
- }
- }
- return false;
- }
- isHiCar() {
- return this.isHiCarStatus&&this.curDisplayIsHiCar;
- }
- //是不是正常的手机竖屏
- isPhonePortrait() {
- // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
- // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
- // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
- if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
- && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
- && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
- return true
- }
- return false
- }
- @State showSpeedDialog: boolean = false
- @State longPressSpeed: number = 3 //长按默认倍数
- @Builder
- SpeedDialog() {
- Stack() {
- Column() {
- Text('已切换至' + this.longPressSpeed + '倍速播放')
- .fontColor(Color.White)
- .visibility(Visibility.Hidden)
- }
- .backgroundColor(Color.Black)
- .borderRadius(20)
- .padding({
- top: 10,
- right: 20,
- left: 15,
- bottom: 20
- })
- .opacity(0.6)
- Text('已切换至' + this.longPressSpeed + '倍速播放')
- .fontColor(Color.White)
- }
- .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
- .zIndex(5)
- .margin({ top: 80 })
- }
- @Builder
- IjkMusicPlayerView() {
- Stack() {
- if(canIUse("SystemCapability.UIDesign.HDSComponent.Core")
- &&deviceInfo.sdkApiVersion>=20&&this.sceneBgController){
- HdsVisualComponent()
- .scene(HdsSceneType.DUAL_EDGE_FLOW_LIGHT_WITH_BACKGROUND_MASK, this.sceneBgController, () => {
- console.info('Succeeded in finishing');
- })
- .width('100%')
- .height('100%')
- .visibility(this.isShowBgLiuGUANG?Visibility.Visible:Visibility.None)
- }
- Column() {
- Column() {
- //播放标题
- Column() {
- this.PlayTitle()
- }
- .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
- .width('100%')
- .margin({ top: 0 })
- .height(PlayConstants.HEIGHT)
- .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
- Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
- if (this.showSpeedDialog) {
- this.SpeedDialog()
- }
- Stack() {
- //手势拖动快进
- Column()
- .width(CommonConstants.FULL_PERCENT)
- .height('100%')
- .gesture(
- GestureGroup(GestureMode.Parallel,
- // 长按屏幕倍数播放
- LongPressGesture({ repeat: true })
- .onAction(() => {
- if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
- this.showSpeedDialog = true;
- this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
- }
- })
- .onActionEnd(() => {
- this.showSpeedDialog = false;
- this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
- }),
- //双击屏幕暂停或者播放
- TapGesture({ count: 2 })
- .onAction((event: GestureEvent) => {
- if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
- ToastUtil.showToast('已暂停')
- }
- console.info('onecold playOrPause 6693')
- this.playOrPause()
- })
- )
- )
- }
- .height('65%')
- Swiper() {
- this.CoverInfo()
- this.PlayerLyrics()
- }
- .onChange((index: number) => {
- this.currentSwiperIndex = index
- })
- .indicator(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(() => {
- console.info('onecold startPlayOrResumePlay 6744')
- this.startPlayOrResumePlay();
- })
- }
- .width(CommonConstants.FULL_PERCENT)
- .height(CommonConstants.FULL_PERCENT)
- .justifyContent(FlexAlign.End)
- }
- .justifyContent(FlexAlign.End)
- .margin({ bottom: 8 })
- }
- .backgroundImage(!this.isMusicBGCover||StrUtil.isEmpty(this.cover)?null: this.cover)
- .backgroundImageSize(this.isPuraWP()||!this.isMusicBGCover ? { width: '100%' } : { height: '150%', width: '100%' })
- .animation({
- duration: 666,
- curve: 'ease-in-out' // 可选动画曲线
- })
- .backgroundBlurStyle((this.isPuraWP() && this.currentSwiperIndex === 0) ||!this.isMusicBGCover
- ? BlurStyle.NONE :
- BlurStyle.BACKGROUND_ULTRA_THICK)
- .hitTestBehavior(HitTestMode.Transparent)
- .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
- .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
- .onClick(() => {
- if(this.isHiCar())
- return
- if(this.is_auto_hide_progress){
- this.is_auto_hide_progress = false
- }
- this.startAutoHide()
- })
- }
- @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;
- @State 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 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 volumeSmall: boolean = false
- @State autoParseMusicName: boolean = true
- @State isShowFileName: boolean = false
- @State isLongNameRoLL: boolean = true//长歌名滚动
- @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
- @State bright: number = PlayConstants.BRIGHT;
- @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
- @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
- @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 rotateAngle2: number = -9
- @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 lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
- private lyricControllerSingle: 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 = false
- @State isHightLightCenter: boolean = true
- /**
- * 初始化歌词加载与展示逻辑
- * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
- * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
- * @param isApi2 是否使用API2获取歌词(可选)
- *
- * 主要流程:
- * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
- * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
- * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
- * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
- * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
- * 6. 解析失败或读取失败时,清空歌词显示。
- *
- * 注意事项:
- * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
- * - 支持加密歌词文件(.lrcc),自动检测并解密。
- * - 歌词内容解析后通过lyricController驱动UI渲染。
- */
- async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
- if (StrUtil.isEmpty(lyricPath)) {
- return
- }
- this.initPipLyricSetting()
- this.lyricControllerSingle
- .setTextSize(15)
- .setCacheSize(4)
- .setTextColor("#FFFFFF")
- .setHighlightColor("#FFFFFF")
- .setHighlightScale(1.2)
- .setEmptyHint("")
- .setAlignMode('center')
- .setAnimationDuration(500)
- .setSingleLine(true)
- this.lyricContent = ''
- this.lyricController
- .setTextSize(this.currentLyricSize)
- .setCacheSize(4)
- .setTextColor("#DDDDDD")
- .setHighlightColor("#FFFFFF")
- .setEmptyHint("")
- .setAnimationDuration(1000)
- this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
- this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
- this.setBlurDegree(this.blurDegree, false)
- this.setLyricAlignMode(this.currentLyricAlignMode, false)
- this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
- this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
- this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
- this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
- this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
- this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
- this.lyricController.setHightLightCenter(this.isHightLightCenter)
- this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
- this.lyricController.setTextWeight(this.lyricTextWeight)
- this.showSingleLyric = false
- this.timeOffset = 0
- this.lyricController.setLyric(null)
- this.lyricControllerSingle.setLyric(null)
- let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
- console.log("onecold lyricPath =" + lyricPath)
- let neiqianLrc = ''
- let lyContent = this.currentSong?.lyricContent
- if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
- neiqianLrc = lyContent
- }
- if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast&&!isLocal&&!isLocal) {
- console.log("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);
- this.lyricControllerXF.setLyric(lyric)
- this.lyricControllerSingle.setLyric(lyric)
- return
- }
- if (isOnLineAndToast || ((!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.lyricControllerXF.setLyric(lyric)
- this.lyricControllerSingle.setLyric(lyric)
- this.showSingleLyric = true
- // 4.保存歌词文件lyric到本地
- //2025年8月28日歌词不再加密下载
- this.saveDataToFile(res, lyricPath, false)
- } else {
- this.lyricController.setLyric(null)
- this.lyricControllerXF.setLyric(null)
- this.lyricControllerSingle.setLyric(null)
- if (isOnLineAndToast) {
- ToastUtil.showShort('未获取到歌词!')
- }
- }
- } else {
- this.lyricController.setLyric(null)
- this.lyricControllerXF.setLyric(null)
- this.lyricControllerSingle.setLyric(null)
- if (isOnLineAndToast) {
- ToastUtil.showShort('未获取到歌词!')
- }
- }
- })
- } else {
- this.lyricController.setLyric(null)
- this.lyricControllerXF.setLyric(null)
- this.lyricControllerSingle.setLyric(null)
- if (isOnLineAndToast) {
- 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_ONLY);
- const stat = await fileIo.stat(file.fd);
- const arrayBuffer = new ArrayBuffer(stat.size);
- 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("onecoldT Detected encoding: " + detectedEncoding);
- let detectedEncoding = this.detect(arrayBuffer)
- console.info("onecoldT Detected encoding: " + detectedEncoding);
- // 使用检测到的编码解码,解决中文乱码问题
- let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
- console.info("onecoldT Detected textDecoder: " + textDecoder);
- let fileContent = textDecoder.decode(buf);
- console.info(`onecoldT The content of file1: ${fileContent}`);
- //解密
- if (isJiaMi) {
- fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
- }
- console.info(`onecold The content of file2: ${fileContent}`);
- this.lyricContent = fileContent
- if(isLocal){//编辑标签选择本地歌词需要赋值给this.lyricConStr
- this.lyricConStr = 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.lyricControllerXF.setLyric(lyric)
- this.lyricControllerSingle.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);
- this.lyricControllerXF.setLyric(null)
- this.lyricControllerSingle.setLyric(null)
- }
- })
- .catch((err: BusinessError) => {
- this.lyricController.setLyric(null)
- this.lyricControllerXF.setLyric(null)
- this.lyricControllerSingle.setLyric(null)
- console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
- })
- .catch((err: Error) => {
- this.lyricController.setLyric(null)
- this.lyricControllerXF.setLyric(null)
- this.lyricControllerSingle.setLyric(null)
- console.error("read file 2 data failed with error message: " + err.message);
- })
- .finally(() => {
- fs.closeSync(file);
- });
- } catch (error) {
- this.lyricController.setLyric(null)
- this.lyricControllerSingle.setLyric(null)
- this.lyricControllerXF.setLyric(null)
- Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
- }
- }
- detect(data: ArrayBuffer): string {
- //创建检测对象
- let detector: UniversalDetector = new UniversalDetector();
- // 传入检测数据并实时判断编码格式
- detector.handleData(data, 0, data.byteLength);
- // 标记检测数据 读取结束
- detector.dataEnd();
- // 获取检测结果
- let detected: string = detector.getDetectedCharset();
- // 释放资源
- detector.reset();
- return detected;
- }
- //初始化悬浮歌词的自定义设置
- initPipLyricSetting() {
- this.lyricControllerXF
- .setTextSize(this.currentLyricSize)
- .setCacheSize(4)
- .setTextColor("#DDDDDD")
- .setHighlightColor("#FFFFFF")// .setLineSpace(18)
- .setEmptyHint("")
- .setAnimationDuration(1000)
- this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
- this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
- this.setBlurDegree(this.blurDegreePip, true)
- this.setLyricAlignMode(this.currentLyricAlignModePip, true)
- this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
- this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
- this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
- this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
- this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
- this.lyricControllerXF.setHightLightCenter(true)
- this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
- this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
- this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
- this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
- if (this.pipBgIndex === 0) {
- if (this.cover) {
- this.pipBg = this.cover
- } else {
- this.pipBg = this.imageColor
- }
- this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
- }
- }
- //根据item返回歌词内容
- async getLyricContent(item: VideoItem): Promise<string> {
- let neiqianLrc = ''
- let lyContent = item?.lyricContent
- if(lyContent&&StrUtil.isNotEmpty(lyContent)){
- neiqianLrc = lyContent
- return neiqianLrc
- }
- try {
- //取数据库里面的歌词lyContent
- const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
- if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
- console.log("onecold Lyrics:", lyricContent);
- neiqianLrc = lyricContent
- return neiqianLrc
- }
- } catch (error) {
- console.error("Error fetching lyrics:", error);
- }
- try {
- let filePath = item.filePath;
- let lyricPath = filePath.substring(0, filePath.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 找到加密本地歌词");
- } else {
- console.info("onecold 找到本地歌词");
- }
- let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
- const stat = await fileIo.stat(file.fd);
- const arrayBuffer = new ArrayBuffer(stat.size);
- const readLen = await fs.read(file.fd, arrayBuffer);
- console.info("read file data succeed");
- let buf = new Uint8Array(arrayBuffer, 0, readLen);
- if (buf.length === 0) {
- throw new Error("Buffer is empty after reading the file");
- }
- // let detectedEncoding = chardet.detect(buf);
- let detectedEncoding = this.detect(arrayBuffer)
- 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}`);
- fs.closeSync(file);
- return fileContent;
- } catch (error) {
- console.error('init Lyric failed with err: ' + JSON.stringify(error));
- return '';
- }
- }
- 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);
- }
- }
- // 定义开始旋转的方法
- // 定时器用于一百毫秒执行一次旋转角度
- @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 = -9
- })
- }
- }
- // 回调,暂停和播放按钮回调,下一首和上一首
- 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
- }
- AppStorage.setOrCreate('animationState', this.animationState);
- }
- // 定义停止旋转的方法
- stopRotation() {
- if (this.isCoverRectangle) {
- this.rotateAngle = 0
- } else {
- //唱针以左上角为点选择逆时针40度
- animateTo({
- duration: 1000,
- curve: Curve.Linear,
- iterations: 1,
- }, () => {
- this.rotateAngle2 = -45;
- });
- }
- }
- @Builder
- private LyricsTopItem() {
- Row() {
- Stack() {
- Image(this.cover)
- .height(58)
- .width(58)
- .alt($r('app.media.alt'))
- .borderRadius(8)
- .clickEffect({ level: ClickEffectLevel.HEAVY })
- .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
- .shadow({
- radius: 22,
- type: ShadowType.BLUR,
- color: 'on_primary'
- })
- }
- .width('18%')
- Column() {
- Column() {
- Text(this.name)
- .fontSize(16)
- .maxLines(1)
- .fontWeight(FontWeight.Bolder)
- .fontColor(this.currentLyricColor)
- .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
- Row() {
- Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
- .fontSize(13)
- .fontWeight(FontWeight.Bold)
- .padding({ top: 8 })
- .fontColor(this.currentLyricColor)
- .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
- Blank()
- }
- }
- .height('100%')
- .width('100%')
- .justifyContent(FlexAlign.Center)
- .alignItems(HorizontalAlign.Start)
- }
- .height('100%')
- .width('65%')
- Column() {
- Image($r('app.media.lyric'))
- .width(28)
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- .margin({ right: 30 })
- .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
- .onClick(() => {
- this.isLyricSetting = !this.isLyricSetting;
- })
- .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
- height: '95%',
- dragBar: true,
- preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
- showClose: true,
- blurStyle: BlurStyle.Thin,
- backgroundColor: Color.Transparent,
- // title: { title: $r('app.string.lyric_setting') }
- })
- }
- .width('18%')
- }
- .width('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定位回调
- if (!this.isPlaying) {
- console.info('onecold startPlayOrResumePlay 7527')
- this.startPlayOrResumePlay()
- }
- else {
- this.isSeekTo = true;
- this.mDestroyPage = false;
- this.showLoadIng();
- this.seekTo(position + "");
- this.isSeekTo = false;
- }
- return true
- }
- })
- .width("100%")
- .layoutWeight(1)
- .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
- if (this.isPhoneLan()) {
- Column() {
- this.playProgressView()
- // this.playCenterView()
- }
- .margin({ bottom: 30, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
- }
- }
- .position({
- top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
- (this.isPuraWP() ? 58 : 99)
- })
- .justifyContent(FlexAlign.Center)
- .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
- }
- }
- @Builder
- SingleLyricView() {
- Column() {
- Column() {
- LyricView2({
- controller: this.lyricControllerSingle,
- enableSeek: false,
- seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
- seekLineColor: "#80ffffff", // 滑动定位线颜色
- seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
- })
- }
- .height(66)
- .margin({ bottom: 20 })
- }
- }
- //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
- @Builder
- BottomControl() {
- Column() {
- this.TopPlayProgressView()
- //播放 暂停,下一首,上一首
- this.playCenterView()
- //播放进度条
- this.BottomView()
- }
- .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
- }
- //播放控制上一首 下一首 暂停和播放
- @Builder
- playCenterView(){
- Row() {
- Button({type:ButtonType.Circle,stateEffect:true}){
- //更多功能
- Image($r('app.media.menu'))
- .width(24)
- .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
- .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
- height: '99%',
- preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
- dragBar: true,
- showClose: true,
- blurStyle: BlurStyle.Thin,
- backgroundColor: Color.Transparent,
- })
- }
- .height(45)
- .width(45)
- .margin({ left: 5 })
- .backgroundColor(Color.Transparent)
- .onClick(() => {
- this.isShowMoreView = !this.isShowMoreView;
- })
- Button({type:ButtonType.Circle,stateEffect:true}){
- Image($r('app.media.ic_previous'))
- .width(33)
- .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- }
- .height(45)
- .width(45)
- .onClick(async () => {
- await this.playPrevious()
- })
- .backgroundColor(Color.Transparent)
- Button({type:ButtonType.Circle,stateEffect:true}){
- Column() {
- Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
- (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
- : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
- .width(this.isPhoneLan()?45:55)
- .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
- .fillColor(Color.White)
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- }
- }
- .onClick(async () => {
- this.playOrPause()
- })
- .backgroundColor(Color.Transparent)
- .layoutWeight(1)
- Button({ type: ButtonType.Circle, stateEffect: true }) {
- Image($r('app.media.ic_next'))
- .width(33)
- .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- }
- .height(45)
- .width(45)
- .backgroundColor(Color.Transparent)
- .onClick(async () => {
- await this.playNext();
- })
- this.fullButton()
- }
- .width('95%')
- .margin({ bottom:this.isCoverOpacity()?0:15 })
- .justifyContent(FlexAlign.SpaceEvenly)
- }
- @Builder
- TopPlayProgressView(){
- Row() {
- Column(){
- Row(){
- Stack(){
- SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
- .fontColor([Color.White])
- .fontSize(21)
- .effectStrategy(1)
- Text(this.fastForwardSeconds)
- .fontColor(Color.White)
- .fontSize(10)
- .fontWeight(FontWeight.Bold)
- }
- .margin({left:12,bottom:6})
- .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
- .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
- .onClick(()=>{
- this.backForward()
- })
- Slider({
- value: this.progressValue,
- min: 0,
- max: this.PROGRESS_MAX_VALUE,
- step: 1,
- style: SliderStyle.InSet
- })
- .height(20)
- .blockColor('rgba(255,255,255,1)')
- .trackColor('rgba(255,255,255,0.3)')
- .selectedColor(Color.White)
- .trackThickness(4)
- .layoutWeight(1)
- .showSteps(false)
- .showTips(true)
- .alignSelf(ItemAlign.Center)
- .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;
- // }
- })
- Stack(){
- SymbolGlyph($r('sys.symbol.arrow_clockwise'))
- .fontColor([Color.White])
- .fontSize(21)
- .effectStrategy(1)
- Text(this.fastForwardSeconds)
- .fontColor(Color.White)
- .fontSize(10)
- .fontWeight(FontWeight.Bold)
- }
- .margin({right:10,bottom:6})
- .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
- .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
- .onClick(()=>{
- this.fastForward()
- })
- }
- .padding({ right: 7,left:22 })
- Row(){
- Text(this.currentTime)
- .fontSize(10)
- .fontColor(Color.White)
- Blank()
- .layoutWeight(1)
- Text(this.totalTime)
- .fontSize(10)
- .fontColor(Color.White)
- }
- .justifyContent(FlexAlign.Start)
- .padding({ right: 18,left:36 })
- }
- }
- //x5的竖屏模式需要99%
- .width(this.isLandscape?'80%':'93%')
- .justifyContent(FlexAlign.Center)
- .margin({bottom:3})
- .animation({
- duration: 666,
- curve: 'ease-in-out' // 可选动画曲线
- })
- }
- //播放进度条
- @Builder
- BottomView(){
- Row() {
- Button({type:ButtonType.Circle,stateEffect:true}){
- Column() {
- if (this.playType === 0) {
- Image($r('app.media.loop'))
- .width(27)
- .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- } else if (this.playType === 1) {
- Image($r('app.media.single'))
- .width(27)
- .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- } else if (this.playType === 2) {
- Image($r('app.media.normal_play'))
- .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
- .width(27)
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- } else if (this.playType === 3) {
- Image($r('app.media.random'))
- .width(27)
- .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- }
- }
- }
- .layoutWeight(1)
- .margin({ left: 5 })
- .height(45)
- .width(45)
- .backgroundColor(Color.Transparent)
- .onClick(async () => {
- this.setLoopMode()
- })
- if(this.currentSong){
- Button({type:ButtonType.Circle,stateEffect:true}){
- Column() {
- Image($r('app.media.rename2'))
- .width(21)
- .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- }
- }
- .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
- height: '99%',
- dragBar: true,
- showClose: true,
- preferType: SheetType.BOTTOM,
- title: { title: '编辑标签' }
- })
- .height(45)
- .width(45)
- .layoutWeight(1)
- .backgroundColor(Color.Transparent)
- .onClick(async () => {
- this.initEditFields(this.currentSong)
- this.tempLyricContent = this.lyricContent
- if (StrUtil.isNotEmpty(this.tempLyricContent)) {
- this.lyricConStr = this.tempLyricContent
- }
- this.isShowEdit = !this.isShowEdit;
- })
- }
- Button({type:ButtonType.Circle,stateEffect:true}){
- Column() {
- Image($r('app.media.lyric'))
- .width(26)
- .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- }
- }
- .height(45)
- .width(45)
- .layoutWeight(1)
- .backgroundColor(Color.Transparent)
- .onClick(async () => {
- this.isLyricSetting = !this.isLyricSetting;
- })
- //播放列表
- Button({type:ButtonType.Circle,stateEffect:true}){
- Image($r('app.media.hm_playlist'))
- .width(24)
- .fillColor(Color.White)
- .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
- .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: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
- title: {
- title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
- + `(${this.songList.length}首)`
- }
- })
- }
- .layoutWeight(1)
- .height(45)
- .width(45)
- .backgroundColor(Color.Transparent)
- .onClick(() => {
- this.isShowSheetView = !this.isShowSheetView;
- if(this.isPlayListBgGrass){
- this.isFrontWhite = true
- }else{
- this.isFrontWhite = false
- }
- this.scrollIndex()
- })
- }
- .width(this.isLandscape?'88%':'95%')
- .justifyContent(FlexAlign.SpaceAround)
- .height(30)
- .animation({
- duration: 666,
- curve: 'ease-in-out' // 可选动画曲线
- })
- }
- @Builder
- fullButton(){
- Button({type:ButtonType.Circle,stateEffect:true}){
- Column() {
- Image($r('app.media.full_4'))
- .width(25)
- .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- }
- }
- .layoutWeight(1)
- .backgroundColor(Color.Transparent)
- .height(45)
- .width(45)
- .onClick(async () => {
- if (this.isLandscape) {
- this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
- } else {
- this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
- }
- })
- }
- //旧版本播放进度条
- @Builder
- playProgressView() {
- Row() {
- Button({ type: ButtonType.Circle, stateEffect: true }) {
- Column() {
- if (this.playType === 0) {
- Image($r('app.media.loop'))
- .width($r('app.float.control_image_width'))
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- } else if (this.playType === 1) {
- Image($r('app.media.single'))
- .width($r('app.float.control_image_width'))
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- } else if (this.playType === 2) {
- Image($r('app.media.normal_play'))
- .width($r('app.float.control_image_width'))
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- } else if (this.playType === 3) {
- Image($r('app.media.random'))
- .width($r('app.float.control_image_width'))
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- }
- }
- }
- .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
- .animation({
- duration: 666,
- curve: 'ease-in-out' // 可选动画曲线
- })
- .backgroundColor(Color.Transparent)
- .margin({ right: 10 })
- .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
- .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('rgba(255,255,255,1)')
- .trackColor('rgba(255,255,255,0.3)')
- .selectedColor(Color.White)
- .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
- .layoutWeight(1)
- .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
- .showSteps(false)
- .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 })
- //播放列表
- Button({ type: ButtonType.Circle, stateEffect: true }) {
- Image($r('app.media.hm_playlist'))
- .width($r('app.float.control_image_width'))
- .fillColor(Color.White)
- .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: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
- title: {
- title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
- + `(${this.songList.length}首)`
- }
- })
- }
- .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
- .animation({
- duration: 666,
- curve: 'ease-in-out' // 可选动画曲线
- })
- .backgroundColor(Color.Transparent)
- .margin({ right: 20, left: 10 })
- .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
- .onClick(() => {
- this.isShowSheetView = !this.isShowSheetView;
- if (this.isPlayListBgGrass) {
- this.isFrontWhite = true
- } else {
- this.isFrontWhite = false
- }
- this.scrollIndex()
- })
- }
- //x5的竖屏模式需要99%
- .width(this.isPhonePortrait() ? '93.4%'
- : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
- .height(this.isPhoneLan() ? 25 : 33)
- .animation({
- duration: 666,
- curve: 'ease-in-out' // 可选动画曲线
- })
- }
- isBigScreen() {
- if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
- return true
- }
- if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
- && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
- && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
- return false
- } else {
- return true
- }
- return false
- }
- @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
- @State isCoverRectangle: boolean = false
- @State isCoverTop: boolean = true
- // 添加控制缩放的状态变量
- @State scaleValueImage: number = 1
- @State scaleValueText: number = 1
- @Builder
- CoverInfo() {
- Column() {
- //如果是方形,判断是不是封面在顶部,如果不是顶部,显示musicNameInfo, 如果是圆形显示musicNameInfo
- if (this.isCoverRectangle) {
- if (!this.isCoverTop) {
- this.musicNameInfo(false)
- }
- } else {
- this.musicNameInfo(false)
- }
- Stack() {
- // 唱片旋转效果
- Image($r('app.media.ic_music_disc'))
- .width(245)
- .height(245)
- .margin({ right: 20, left: 20 ,top:this.isCoverRectangle||this.isLandscape?0:43})
- .aspectRatio(1)
- .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
- .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
- .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: 22,
- type: ShadowType.BLUR,
- color: 'on_primary'
- })
- Column() {
- if (this.isCoverTop && this.isCoverRectangle) {
- Image(this.cover)
- .height(this.isHiCar()?(px2vp(this.windowHeight)*0.46):
- this.isCoverOpacity()?(px2vp(this.windowHeight)*0.6):'auto')
- .width(this.isHiCar()||this.isCoverOpacity()?'auto':this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '88%')
- .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
- .alt($r('app.media.alt'))
- .margin({ right: 8, left: 8, top: 8 })
- .aspectRatio(1)
- .geometryTransition('cover') // 绑定标识符
- .opacity(this.opacityValueImage)
- .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
- // 设置左下角为缩放中心点
- centerX: '0%',
- centerY: '100%' })
- .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
- .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
- .borderRadius(this.isCoverRectangle ? 20 : '100%')
- .clip(true)
- .rotate({
- x: 0,
- y: 0,
- z: 1,
- angle: this.rotateAngle
- })
- .shadow({
- radius: 22,
- type: ShadowType.BLUR,
- color: 'on_primary'
- })
- .onClick(() => {
- })
- // .visualEffect(new hdsEffect.HdsEffectBuilder()
- // .shaderEffect({
- // effectType: hdsEffect.EffectType.DUAL_EDGE_FLOW_LIGHT,
- // animation: {
- // duration: 4000,
- // iterations: -1,
- // autoPlay: true,
- // onFinish: () => {
- // console.info('Succeeded in finishing');
- // }
- // },
- // controller: this.controller,
- // params: {
- // firstEdgeFlowLight: {
- // startPos: 0,
- // endPos: 1.0,
- // color: '#1AD0F1',
- // },
- // secondEdgeFlowLight: {
- // startPos: 0.5,
- // endPos: 1.5,
- // color: '#FFA4E5',
- // }
- // }
- // })
- // .buildEffect())
- this.musicNameInfo(false)
- } else {
- Image(this.cover)
- .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
- (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 162))
- .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
- .alt($r('app.media.alt'))
- .geometryTransition('cover') // 绑定标识符
- .margin({ right: 20, left: 20,top:this.isCoverRectangle||this.isLandscape?0:43 })
- .aspectRatio(1)
- .opacity(this.opacityValueImage)
- .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
- // 设置左下角为缩放中心点
- centerX: '0%',
- centerY: '100%' })
- .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
- .borderRadius(this.isCoverRectangle ? 20 : '100%')
- .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
- .align(Alignment.Center)//
- .clip(true)
- .shadow({
- radius: 22,
- type: ShadowType.BLUR,
- color: 'on_primary'
- })
- .rotate({
- x: 0,
- y: 0,
- z: 1,
- angle: this.rotateAngle
- })
- .onClick(() => {
- })
- }
- if (this.isPhoneLan()) {
- Text(this.name)
- .fontSize(18)
- .fontWeight(FontWeight.Bold)
- .margin({ top: 13 })
- .textOverflow({ overflow: TextOverflow.Ellipsis })
- .maxLines(1)
- .width('99%')
- .textAlign(TextAlign.Center)
- .fontColor(Color.White)
- }
- }
- // 唱针以左上角为点选择逆时针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)
- .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
- Column({ space: 8 }) {
- Text(this.name)
- .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
- .fontWeight(FontWeight.Bold)
- .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
- .maxLines(1)
- .width('48%')
- .textAlign(TextAlign.Center)
- .fontColor(Color.White)
- .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
- Text(this.artist)
- .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
- .fontColor(Color.White)
- .fontWeight(FontWeight.Bold)
- .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
- }
- .justifyContent(FlexAlign.Start)
- .zIndex(1)
- .geometryTransition('name')
- .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
- }
- .margin({
- bottom: this.isCoverOpacity() || this.isCoverRectangle ?
- (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
- top: this.isCoverOpacity() ? 0 : 20
- })
- if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
- this.SingleLyricView()
- }
- if (this.isPhoneLan()) {
- Column() {
- this.playCenterView()
- // this.playProgressView()
- }
- .position({ left: 28, bottom: 38 })
- } else {
- this.BottomControl()
- }
- }
- .width(CommonConstants.FULL_PERCENT)
- .clip(true)
- }
- @Builder
- private musicNameInfo(isHidden: boolean) {
- Row(){
- Column({ space: 8 }) {
- Text(this.name)
- .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 20)
- .fontWeight(FontWeight.Bold)
- .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
- .maxLines(1)
- .width('99%')
- .textAlign(TextAlign.Start)
- .fontColor(Color.White)
- Text(this.artist + ' ' + this.currentSong?.album)
- .fontSize(this.isCoverOpacity() ? 12 : 15)
- .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
- .fontColor(Color.White)
- .textAlign(TextAlign.Start)
- .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
- .width('99%')
- .maxLines(1)
- }
- .zIndex(1)
- .geometryTransition('name') // 绑定标识符
- .layoutWeight(1)
- .margin({ left: 15 })
- Blank()
- Row(){
- Button({type:ButtonType.Circle,stateEffect:true}){
- //添加或取消收藏
- SymbolGlyph(Utility.getIsFav(this.favList,this.currentSong)?
- $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'))
- .fontSize(22)
- .fontColor([Color.White])
- .alignSelf(ItemAlign.Center)
- // .width(24)
- .clickEffect({level:ClickEffectLevel.MIDDLE})
- .aspectRatio(CommonConstants.ASPECT_RATIO)
- .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
- .onClick(async () => {
- if(this.currentSong){
- this.doFav(this.currentSong)
- }
- })
- }
- .margin({ left: 15,right:3 })
- .backgroundColor(Color.Transparent)
- .width(45)
- .height(45)
- }
- }
- .width('90%')
- .scale({ x: this.scaleValueText, y: this.scaleValueText }) // 添加缩放效果
- .margin({ top: this.isCoverOpacity() ? 10 : isHidden ? 20 : 10 })
- .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
- }
- @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)
- 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)
- .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
- .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
- .onClick(() => {
- this.setShowPlayFalse()
- })
- Column() {
- AVCastPicker({
- normalColor: Color.White,
- onStateChange: this.onStateVastChange
- })
- .width(24)
- .height(24)
- }
- .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
- }
- .width(PlayConstants.ROW_WIDTH)
- }
- @Builder
- lyricSettingSheet(isPip: boolean) {
- Scroll() {
- this.lyricSetting(isPip)
- }
- .width('100%')
- .height('100%')
- }
- @Builder
- lyricSetting(isPip: boolean) {
- Column() {
- // 时间调节模块
- if (!isPip) {
- this.BuildTimeControls()
- }
- // 字号控制模块
- this.BuildFontControls(isPip)
- }
- }
- // 歌词时间偏移状态
- @State timeOffset: number = 0.0
- @State currentLyricColor: string = '#FFFFFF'
- @State currentLyricColorPip: string = '#FFFFFF'
- @State currentHighLightLyricColor: string = '#FF4081'
- @State currentHighLightLyricColorPip: string = '#FF4081'
- // 歌词字号状态
- @State currentLyricSize: number = 20
- @State currentLyricSizePip: number = 20
- // 高亮歌词放大倍数
- @State currentHightLyricSize: number = 1.2
- @State currentHightLyricSizePip: number = 1.2
- @State currentLyricLineSpace: number = 10
- @State currentLyricLineSpacePip: number = 10
- @State currentLyricAlignMode: number = 1
- @State currentLyricAlignModePip: number = 1
- @State blurDegree: number = 2
- @State blurDegreePip: number = 2
- @State isShowSelectColor: boolean = false
- @State isShowHLSelectColor: boolean = false
- @State isShowPipBgSelectColor: boolean = false
- @State pipLyWidth: number = 330
- @State pipLyHeight: number = 120
- // 构建颜色选择器
- @Builder
- SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
- Row({ space: 10 }) {
- HSBColorPicker({
- color: '#FFFFFF',
- radius: 8,
- layout: HSBColorPickerLayout.COLUMN,
- predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
- '#fa7105'],
- onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
- this.changeLyricColor(value, isPip, isBGPip)
- })
- .height(250)
- .layoutWeight(1)
- .padding(25)
- }
- .width('66%')
- }
- @State isOpenPip: boolean = false
- @State pipBgIndex: number = 0
- // 构建字号控制器
- @Builder
- BuildFontControls(isPip: boolean) {
- Column() {
- if (isPip) {
- Column() {
- Row() {
- Text('悬浮歌词')
- .margin({ left: 18 })
- .fontSize(15)
- .fontColor(Color.White)
- .fontWeight(480)
- .layoutWeight(1)
- Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
- .selectedColor(this.themeColor)
- .switchPointColor(Color.White)
- .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
- .margin({ right: 18 })
- .onChange((checked: boolean) => {
- this.isOpenPip = checked;
- if (this.isOpenPip) {
- this.startPip()
- } else {
- this.stopPip()
- }
- PreferencesUtil.put('isOpenPip', this.isOpenPip)
- })
- .width(50)
- .height(30);
- }
- .height(55)
- }
- .backgroundColor(Color.Transparent)
- .borderRadius(15)
- .margin({
- left: 30,
- right: 30,
- top: 0,
- bottom: 20
- })
- .padding(0)
- .border({
- color: Color.White,
- width: 1.8
- })
- }else{
- Column() {
- Row() {
- Text('单行歌词')
- .margin({ left: 18 })
- .fontSize(15)
- .fontColor(Color.White)
- .fontWeight(480)
- .layoutWeight(1)
- Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
- .selectedColor(this.themeColor)
- .switchPointColor(Color.White)
- .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
- .margin({ right: 18 })
- .onChange((checked: boolean) => {
- this.isShowSingleLineLyric = checked;
- PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
- })
- .width(50)
- .height(30);
- }
- .height(55)
- }
- .backgroundColor(Color.Transparent)
- .borderRadius(15)
- .margin({
- left: 30,
- right: 30,
- top: 10,
- bottom: 10
- })
- .padding(0)
- .border({
- color: Color.White,
- width: 1.8
- })
- }
- Row() {
- Text(`歌词居中:`)
- .fontSize(14)
- .fontColor(Color.White)
- .margin({ left: 2 })
- Row() {
- ForEach(['居中', '居左'], (size: string, index: number) => {
- Button(size)
- .width(60)
- .height(28)
- .fontSize(12)
- .fontColor('#FFFFFF')
- .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
- (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
- .border({
- color: (!isPip && this.currentLyricAlignMode === index) ||
- (isPip && this.currentLyricAlignModePip === index) ?
- '#007DFF' : '#DDDDDD',
- width: 1.8
- })
- .onClick(() => {
- this.setLyricAlignMode(index, isPip)
- })
- .margin({ left: 10, right: 8 })
- })
- }
- .width('76%')
- Blank()
- }
- .margin({
- top: 10,
- bottom: 10,
- right: 20,
- left: 20
- })
- if (isPip) {
- Row() {
- Text(`悬浮背景:`)
- .fontSize(14)
- .fontColor(Color.White)
- Select([
- { value: CommonConstants.PIP_LYRIC_BG[0] },
- { value: CommonConstants.PIP_LYRIC_BG[1] }])
- .font({ size: 13, weight: FontWeight.Medium })
- .fontColor(Color.White)
- .margin({ left: 10 })
- .selected(this.pipBgIndex)
- .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
- .onSelect(async (_index: number, text?: string | undefined) => {
- this.pipBgIndex = _index
- PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
- if (this.pipBgIndex === 0) {
- if (this.cover) {
- this.pipBg = this.cover
- } else {
- this.pipBg = this.imageColor
- }
- this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
- } else {
- this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
- }
- })
- Column() {
- }
- .backgroundColor(this.pipBg)
- .margin({ left: 10, right: 10 })
- .borderRadius(20)
- .height(28)
- .width(28)
- Button({ type: ButtonType.Capsule, stateEffect: true }) {
- Row() {
- SymbolGlyph($r('sys.symbol.paintbrush'))
- .fontColor([Color.White])
- .effectStrategy(1)
- Text(`选择颜色`)
- .fontSize(13)
- .margin({ left: 10 })
- .fontColor(Color.White)
- }
- }
- .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
- .backgroundColor(Color.Transparent)
- .border({
- color: '#FFFFFF',
- radius: 20,
- width: 1.8
- })
- .height(36)
- .width(110)
- .onClick(() => {
- this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
- })
- .bindPopup(this.isShowPipBgSelectColor, {
- builder: this.SelectColor(false, isPip, true),
- placement: Placement.Top,
- mask: { color: '#33000000' },
- enableArrow: false, //是否显示箭头
- showInSubWindow: false,
- onStateChange: (e) => {
- if (!e.isVisible) {
- this.isShowPipBgSelectColor = false
- }
- }
- })
- }
- .width('76%')
- .margin({ bottom: 5, right: 45, left: 20 })
- }
- if (!isPip) {
- Row() {
- Text(`高亮居中:`)
- .fontSize(14)
- .fontColor(Color.White)
- Column() {
- Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
- .selectedColor(this.themeColor)
- .switchPointColor(Color.White)
- .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
- .onChange((checked: boolean) => {
- this.isHightLightCenter = checked;
- PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
- this.lyricController.setHightLightCenter(this.isHightLightCenter)
- })
- .width(50)
- .height(30)
- .alignSelf(ItemAlign.Start)
- .margin({ left: 12 })
- Blank()
- }
- .width('76%')
- }
- .margin({
- left: 20,
- right: 15,
- top: 10,
- bottom: 10
- })
- }
- Row() {
- Text(`歌词颜色:`)
- .fontSize(14)
- .fontColor(Color.White)
- Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
- .fontSize(15)
- .fontColor(Color.White)
- .margin({ left: 12, right: 12 })
- Column() {
- }
- .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
- .margin({ right: 12 })
- .borderRadius(20)
- .height(28)
- .width(28)
- Button({ type: ButtonType.Capsule, stateEffect: true }) {
- Row() {
- SymbolGlyph($r('sys.symbol.paintbrush'))
- .fontColor([Color.White])
- .effectStrategy(1)
- Text(`选择颜色`)
- .fontSize(13)
- .margin({ left: 10 })
- .fontColor(Color.White)
- }
- }
- .backgroundColor(Color.Transparent)
- .border({
- color: '#FFFFFF',
- radius: 20,
- width: 1.8
- })
- .height(36)
- .width(110)
- .onClick(() => {
- this.isShowSelectColor = !this.isShowSelectColor
- })
- .bindPopup(this.isShowSelectColor, {
- builder: this.SelectColor(false, isPip),
- placement: Placement.Top,
- mask: { color: '#33000000' },
- enableArrow: false, //是否显示箭头
- showInSubWindow: false,
- onStateChange: (e) => {
- if (!e.isVisible) {
- this.isShowSelectColor = false
- }
- }
- })
- }
- .width('76%')
- .margin({
- top: 10,
- bottom: 10,
- right: 45,
- left: 20
- })
- Row() {
- Text(`高亮颜色:`)
- .fontSize(14)
- .fontColor(Color.White)
- Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
- .fontSize(15)
- .fontColor(Color.White)
- .margin({ left: 12, right: 12 })
- Column() {
- }
- .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
- .margin({ right: 12 })
- .borderRadius(20)
- .height(28)
- .width(28)
- Button({ type: ButtonType.Capsule, stateEffect: true }) {
- Row() {
- SymbolGlyph($r('sys.symbol.paintbrush'))
- .fontColor([Color.White])
- .effectStrategy(1)
- Text(`选择颜色`)
- .fontSize(13)
- .margin({ left: 10 })
- .fontColor(Color.White)
- }
- }
- .backgroundColor(Color.Transparent)
- .border({
- color: '#FFFFFF',
- radius: 20,
- width: 1.8
- })
- .height(36)
- .width(110)
- .onClick(() => {
- this.isShowHLSelectColor = !this.isShowHLSelectColor
- })
- .bindPopup(this.isShowHLSelectColor, {
- builder: this.SelectColor(true, isPip),
- placement: Placement.Top,
- mask: { color: '#33000000' },
- enableArrow: false, //是否显示箭头
- showInSubWindow: false,
- onStateChange: (e) => {
- if (!e.isVisible) {
- this.isShowHLSelectColor = false
- }
- }
- })
- }
- .width('76%')
- .margin({
- top: 10,
- bottom: 10,
- right: 45,
- left: 20
- })
- if (isPip) {
- Row() {
- Text(`显示宽度:`)
- .fontSize(14)
- .fontColor(Color.White)
- Slider({
- value: this.pipLyWidth,
- min: 10,
- max: 800,
- step: 1,
- style: SliderStyle.OutSet
- })
- .blockColor(this.themeColor)
- .trackColor($r('app.color.speed_text_color'))
- .selectedColor(Color.White)
- .trackThickness(6)
- .onChange((value: number) => {
- this.pipLyWidth = value
- if (this.pipController) {
- this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
- PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
- }
- })
- .width('76%')
- }
- .margin({
- left: 20,
- right: 15,
- top: 5,
- bottom: 5
- })
- Row() {
- Text(`显示高度:`)
- .fontSize(14)
- .fontColor(Color.White)
- Slider({
- value: this.pipLyHeight,
- min: 10,
- max: 1000,
- step: 1,
- style: SliderStyle.OutSet
- })
- .blockColor(this.themeColor)
- .trackColor($r('app.color.speed_text_color'))
- .selectedColor(Color.White)
- .trackThickness(6)
- .onChange((value: number) => {
- this.pipLyHeight = value
- if (this.pipController) {
- this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
- PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
- }
- })
- .width('76%')
- }
- .margin({
- left: 20,
- right: 15,
- top: 5,
- bottom: 5
- })
- }
- Row() {
- Text(`歌词字号:`)
- .fontSize(14)
- .fontColor(Color.White)
- Slider({
- value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
- min: 12,
- max: 30,
- step: 0.1,
- style: SliderStyle.OutSet
- })
- .blockColor(this.themeColor)
- .trackColor($r('app.color.speed_text_color'))
- .selectedColor(Color.White)
- .trackThickness(6)
- .onChange((value: number) => {
- this.setLyricTextSize(value, isPip)
- })
- .width('76%')
- }
- .margin({
- left: 20,
- right: 15,
- top: 5,
- bottom: 5
- })
- Row() {
- Text(`高亮倍数:`)
- .fontSize(14)
- .fontColor(Color.White)
- Slider({
- value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
- min: 1,
- max: 2,
- step: 0.1,
- style: SliderStyle.OutSet
- })
- .blockColor(this.themeColor)
- .trackColor($r('app.color.speed_text_color'))
- .selectedColor(Color.White)
- .trackThickness(6)
- .onChange((value: number) => {
- this.setHighLyricTextSize(value, isPip)
- })
- .width('76%')
- }
- .margin({
- left: 20,
- right: 15,
- top: 5,
- bottom: 5
- })
- Row() {
- Text(`歌词间隙:`)
- .fontSize(14)
- .fontColor(Color.White)
- Slider({
- value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
- min: 0,
- max: 100,
- step: 1,
- style: SliderStyle.OutSet
- })
- .blockColor(this.themeColor)
- .trackColor($r('app.color.speed_text_color'))
- .selectedColor(Color.White)
- .trackThickness(6)
- .onChange((value: number) => {
- this.setLyricLineSpace(value, isPip)
- })
- .width('76%')
- }
- .margin({
- left: 20,
- right: 15,
- top: 5,
- bottom: 5
- })
- //取值间隔为100,默认为400,取值越大,字体越粗
- Row() {
- Text(`歌词字重:`)
- .fontSize(14)
- .fontColor(Color.White)
- Slider({
- value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
- min: 100,
- max: 900,
- step: 100,
- style: SliderStyle.OutSet
- })
- .blockColor(this.themeColor)
- .trackColor($r('app.color.speed_text_color'))
- .selectedColor(Color.White)
- .trackThickness(6)
- .onChange((value: number) => {
- if (isPip) {
- this.lyricTextWeightPip = value
- this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
- PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
- } else {
- this.lyricTextWeight = value
- this.lyricController.setTextWeight(this.lyricTextWeight)
- PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
- }
- })
- .width('76%')
- }
- .margin({
- left: 20,
- right: 15,
- top: 5,
- bottom: 5
- })
- if (!isPip) {
- Row() {
- Text(`歌词模糊:`)
- .fontSize(14)
- .fontColor(Color.White)
- Slider({
- value: isPip ? this.blurDegreePip : this.blurDegree,
- min: 0,
- max: 5,
- step: 0.1,
- style: SliderStyle.OutSet
- })
- .blockColor(this.themeColor)
- .trackColor($r('app.color.speed_text_color'))
- .selectedColor(Color.White)
- .trackThickness(6)
- .onChange((value: number) => {
- this.setBlurDegree(value, isPip)
- })
- .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'), 1, '繁体转简体')
- }
- .justifyContent(FlexAlign.Center)
- .margin({ top: 3, bottom: 10 })
- }
- }
- private setBlurDegree(index: number, isPip: boolean) {
- if (isPip) {
- this.blurDegreePip = index
- this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
- PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
- } else {
- this.blurDegree = index
- this.lyricController.setBlurDegree(this.blurDegree)
- PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
- }
- }
- private setLyricAlignMode(index: number, isPip: boolean) {
- if (isPip) {
- this.currentLyricAlignModePip = index
- if (this.currentLyricAlignModePip === 1) {
- this.lyricControllerXF.setAlignMode("left")
- } else {
- this.lyricControllerXF.setAlignMode("center")
- }
- PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
- } else {
- this.currentLyricAlignMode = index
- if (this.currentLyricAlignMode === 1) {
- this.lyricController.setAlignMode("left")
- } else {
- this.lyricController.setAlignMode("center")
- }
- PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
- }
- }
- private setLyricTextSize(index: number, isPip: boolean) {
- if (isPip) {
- this.currentLyricSizePip = index
- this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
- PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
- } else {
- this.currentLyricSize = index
- this.lyricController.setTextSize(this.currentLyricSize)
- PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
- }
- }
- private setHighLyricTextSize(scale: number, isPip: boolean) {
- if (isPip) {
- this.currentHightLyricSizePip = scale
- this.lyricControllerXF
- .setHighlightScale(this.currentHightLyricSizePip)
- PreferencesUtil.putSync('HighLyricTextSizePip', scale)
- } else {
- this.currentHightLyricSize = scale
- this.lyricController
- .setHighlightScale(this.currentHightLyricSize)
- PreferencesUtil.putSync('HighLyricTextSize', scale)
- }
- }
- private setLyricLineSpace(index: number, isPip: boolean) {
- if (isPip) {
- this.currentLyricLineSpacePip = index
- this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
- PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
- } else {
- this.currentLyricLineSpace = index
- this.lyricController.setLineSpace(this.currentLyricLineSpace)
- PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
- }
- }
- private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
- LogUtil.info('onecold isBG = ' + isBG)
- if (isBG) { //如果是设置悬浮背景
- this.pipBg = color
- PreferencesUtil.putSync('BGColorPip', this.pipBg)
- this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
- return
- }
- if (isPip) {
- this.currentLyricColorPip = color
- this.lyricControllerXF
- .setTextColor(this.currentLyricColorPip)
- PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
- } else {
- this.currentLyricColor = color
- this.lyricController
- .setTextColor(this.currentLyricColor)
- PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
- }
- }
- private changeLyricHightLightColor(color: string, isPip: boolean) {
- if (isPip) {
- this.currentHighLightLyricColorPip = color
- this.lyricControllerXF
- .setHighlightColor(this.currentHighLightLyricColorPip)
- PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
- } else {
- this.currentHighLightLyricColor = color
- this.lyricController
- .setHighlightColor(this.currentHighLightLyricColor)
- PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
- }
- }
- // 构建时间控制器
- @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, '重置')
- 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) {
- Button({ type: ButtonType.Capsule, stateEffect: true }) {
- Column() {
- Image(icon)
- .width(28)
- .margin({ bottom: 5 })
- .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
- Text(label)
- .fontSize(12)
- .fontColor('#FFFFFF')
- }
- }
- .backgroundColor(Color.Transparent)
- .enabled(!this.isButtonDisabled(step))
- .onClick(() => this.handlePrecisionAdjust(step))
- .padding(5)
- .width(66)
- .height(66)
- .margin({ left: 18, right: 18 })
- .border({
- color: '#FFFFFF',
- 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) {
- Button({ type: ButtonType.Capsule, stateEffect: true }) {
- Row() {
- Image(icon)
- .width(14)
- .margin({ left: 13 })
- Text(label)
- .fontSize(12)
- .margin({ left: 6 })
- .fontColor('#FFFFFF')
- }
- }
- .onClick(() => {
- switch (step) {
- case 0:
- this.callFilePickerSelectFileForLyric()
- break;
- case 1:
- //判断有没有设置api
- if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
- this.isLyricSetting = false
- this.showTipsDialog()
- return
- }
- if (StrUtil.isNotEmpty(this.videoUrl)) {
- ToastUtil.showToast('正在获取')
- this.isLyricSetting = false
- let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
- this.initLyric(lyricPath, true);
- }
- break;
- }
- })
- .padding(5)
- .width(110)
- .backgroundColor(Color.Transparent)
- .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(this.themeColor)//.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(this.themeColor)
- .stateEffect(true)
- .margin({ left: 6 })
- .onClick(() => {
- DialogHelper.closeDialog('vip'); //关闭弹框
- this.isShowPlay = false
- this.mType = 1 //跳转到用户中心
- // router.pushUrl({
- // url: 'pages/VipPage'
- // }, router.RouterMode.Single);
- })
- }
- }
- .width("100%")
- .padding(10)
- }
- showTipsDialog() {
- DialogHelper.showCustomContentDialog({
- dialogId: 'tips',
- title: "友情提示",
- autoCancel: false, //点击遮障层时,不关闭弹窗
- backCancel: true, //点击返回键,不关闭弹窗
- contentBuilder: () => {
- this.customTipsBuilder("请到设置界面配置API服务器地址!")
- },
- buttons: [],
- })
- }
- @Builder
- customTipsBuilder(content: string) {
- Column() {
- Text(content)
- .fontColor(Color.Gray)
- .fontSize(16)
- .alignSelf(ItemAlign.Start)
- .margin({ bottom: 15 })
- .fontSize(16)
- Row() {
- Button('取消')
- .fontColor(Color.White)
- .backgroundColor(this.themeColor)
- .height(50)
- .layoutWeight(1)
- .stateEffect(true)
- .margin({ right: 6 })
- .onClick(() => {
- DialogHelper.closeDialog('tips'); //关闭弹框
- })
- Button('跳转')
- .fontColor(Color.White)//
- .layoutWeight(1)
- .height(50)
- .backgroundColor(this.themeColor)
- .stateEffect(true)
- .margin({ left: 6 })
- .onClick(() => {
- DialogHelper.closeDialog('tips'); //关闭弹框
- this.isShowEdit = false
- this.longItemFilePath = ''
- // if(this.isGridMusic&&!this.isShowPlay){
- // this.longItemFilePath== ''
- // }else{
- // this.isShowEdit = false
- // }
- this.isShowMoreView = false;
- this.isShowPlay = false
- this.mType = 4
- // router.pushUrl({
- // url: 'pages/SettingPage'
- // }, 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, index: number) => {
- Button({ type: ButtonType.Capsule, stateEffect: true }) {
- Row() {
- if (more.id === 3&&this.currentSong) {
- Image(more.image)
- .width(24)
- .height(24)
- .margin({ left: 10, right: 10 })
- Text(more.title)
- .fontSize(16)
- .fontColor(Color.White)
- .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
- height: this.isCoverOpacity() ? '95%' : '95%',
- dragBar: true,
- preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
- showClose: true,
- blurStyle: BlurStyle.Thin,
- backgroundColor: Color.Transparent,
- title: { title: '歌曲信息' }
- })
- } else if (more.id === 15 && this.currentSong) { //编辑标签
- Image(more.image)
- .width(24)
- .height(24)
- .margin({ left: 10, right: 10 })
- Text(more.title)
- .fontSize(16)
- .fontColor(Color.White)
- } else if (more.id === 5) { //定时关闭
- Image(more.image)
- .width(24)
- .height(24)
- .margin({ left: 10, right: 10 })
- Text(more.title)
- .fontSize(16)
- .fontColor(Color.White)
- .onClick(() => {
- this.doMore(more.id)
- })
- .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
- height: this.isCoverOpacity() ? '95%' : '95%',
- preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
- dragBar: true,
- showClose: true,
- title: { title: $r('app.string.time_close') }
- })
- } else if (more.id === 2) { //歌词设置
- Image(more.image)
- .width(24)
- .height(24)
- .margin({ left: 10, right: 10 })
- Text(more.title)
- .fontSize(16)
- .fontColor(Color.White)
- } else if (more.id === 16) { //悬浮歌词设置
- Image(more.image)
- .width(24)
- .height(24)
- .margin({ left: 10, right: 10 })
- Text(more.title)
- .fontSize(16)
- .fontColor(Color.White)
- .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
- height: this.isCoverOpacity() ? '95%' : '95%',
- dragBar: true,
- preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
- showClose: true,
- blurStyle: BlurStyle.Thin,
- backgroundColor: Color.Transparent,
- title: { title: '悬浮歌词' }
- })
- } else if (more.id === 11) {
- Image(more.image)
- .width(24)
- .height(24)
- .margin({ left: 10, right: 10 })
- Text(more.title)
- .fontSize(16)
- .fontColor(Color.White)
- .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
- height: this.isCoverOpacity() ? '95%' : '60%',
- dragBar: true,
- preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
- showClose: true,
- blurStyle: BlurStyle.Thin,
- backgroundColor: Color.Transparent,
- title: { title: '跳过头尾' }
- })
- } 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')
- } else {
- Image(more.image)
- .width(24)
- .height(24)
- .fillColor(Color.White)
- .margin({ left: 10, right: 10 })
- .onClick(() => {
- this.doMore(more.id)
- })
- Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : 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(this.themeColor)
- .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());
- PreferencesUtil.putSync('DefalutVolume',this.volume)
- })
- .layoutWeight(1)
- Blank()
- Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
- .selectedColor(this.themeColor)
- .switchPointColor(Color.White)
- .margin({ right: 15 })
- .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
- .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(this.themeColor)
- .switchPointColor(Color.White)
- .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
- .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(this.themeColor)
- .switchPointColor(Color.White)
- .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
- .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(this.themeColor)
- .switchPointColor(Color.White)
- .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
- .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);
- Toggle({ type: ToggleType.Switch, isOn: this.isShowBgLiuGUANG })
- .selectedColor(this.themeColor)
- .switchPointColor(Color.White)
- .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
- .margin({ right: 15 })
- .visibility(more.id == 21 ? Visibility.Visible : Visibility.None)
- .onChange((checked: boolean) => { // 是否开启背景流光效果
- if (more.id == 21) {
- this.isShowBgLiuGUANG = checked;
- PreferencesUtil.putSync('isShowBgLiuGUANG',this.isShowBgLiuGUANG)
- }
- })
- .width(48)
- .height(24);
- }
- }
- .width('100%')
- .height(45)
- .padding(15)
- .backgroundColor(Color.Transparent)
- .borderRadius(12)
- .margin({ bottom: 6 })
- }
- .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
- .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
- .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
- .backgroundColor(Color.Transparent)
- .onClick(() => {
- this.doMore(more.id)
- })
- });
- }
- .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)
- }
- .width('100%')
- .layoutWeight(1)
- .alignItems(VerticalAlign.Center)
- .justifyContent(FlexAlign.Start)
- }
- private moreItems: MoreItem[] = [
- { id: 1, image: $r('app.media.speed'), title: '倍速' },
- { id: 2, image: $r('app.media.lyric'), title: '歌词' },
- { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
- { id: 16, image: $r('app.media.hua_zhong_hua'), 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:20,image: $r("app.media.a_b"), title: 'AB循环' },
- { id: 12, image: $r('app.media.toubo'), title: '投播' },
- { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
- { id: 4, image: $r('app.media.share2'), 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 : 21, image: $r('app.media.music_red'), title: '开启背景流光' },
- { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
- { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
- ];
- @State isShowBgLiuGUANG: boolean = true;
- @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
- @State showPipLyric: 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 2: //歌词
- this.isLyricSetting = !this.isLyricSetting;
- this.isShowMoreView = false
- break;
- case 3: //详情
- this.isShowDetailMore = !this.isShowDetailMore;
- break;
- case 4: //分享
- if (this.currentSong !== undefined) {
- Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
- }
- this.isShowMoreView = false
- break;
- case 5: //定时关闭
- this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
- break;
- case 10: //设为铃声
- this.setRingTone()
- this.isShowMoreView = false
- break;
- case 11: //跳过头尾
- this.isJumpSetting = !this.isJumpSetting;
- break;
- case 13: //倍速
- break;
- case 14: //搜索封面
- if (this.currentSong !== undefined) {
- this.doSearchCover(this.currentSong)
- }
- this.isShowMoreView = false
- break;
- case 15: //编辑标签
- this.initEditFields(this.currentSong)
- this.tempLyricContent = this.lyricContent
- if (StrUtil.isNotEmpty(this.tempLyricContent)) {
- this.lyricConStr = this.tempLyricContent
- }
- this.isShowEdit = !this.isShowEdit;
- break;
- case 16: //悬浮歌词
- this.showPipLyric = !this.showPipLyric;
- break;
- case 17: //横屏模式
- if (this.isLandscape) {
- this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
- } else {
- this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
- }
- this.isShowMoreView = false
- break;
- case 20://AB循环
- this.isABSheet = !this.isABSheet
- break;
- }
- }
- //AB循环
- @State isOpenAB:boolean = false
- @State jumpATime:number = 0
- @State jumpBTime:number = 0
- @State isABSheet:boolean = false
- @Builder
- ABLoopSheet() {
- ABLoopComptent({
- jumpATime:this.jumpATime,
- jumpBTime:this.jumpBTime,
- onClickAItem: async ()=>{
- if(this.mIjkMediaPlayer){
- this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
- }
- },
- onClickBItem: async ()=>{
- if(this.mIjkMediaPlayer){
- this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
- if(this.jumpBTime<=this.jumpATime){
- ToastUtil.showToast('设置B点时间不能小于A点时间')
- this.jumpBTime = 0
- }
- }
- },
- onCancleButtonClick: async ()=>{
- this.isOpenAB = false
- this.isABSheet = false
- },
- onStartButtonClick: async ()=>{
- if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
- ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
- return
- }
- this.isABSheet = false
- this.startABLoop()
- },
- })
- }
- //开始AB循环
- startABLoop(){
- if(this.mIjkMediaPlayer){
- this.seekTo(this.jumpATime+'')
- this.isOpenAB = true
- }
- }
- /**
- * 切换横竖屏
- *
- */
- setOrientation(orientation: number) {
- this.windowClass.setPreferredOrientation(orientation).then(() => {
- Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
- }).catch((err: BusinessError) => {
- Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
- });
- }
- /**
- * 画中画功能(悬浮歌词功能)
- *
- */
- private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
- pipController?: PiPWindow.PiPController;
- navigationId: string = '';
- @State curState: string = '';
- @State curError: ResourceStr = '';
- @State pipBg: string = '#E8E8E8'
- @State buttonAction: string = '';
- //开启画中画功能
- async startPip() {
- this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
- if (!this.pipController) {
- await this.createPipController();
- }
- if (!this.pipController) {
- Logger.info(`[${TAG}] pipController create error`);
- return;
- }
- await this.pipController.startPiP();
- }
- async stopPip() {
- if (!this.pipController) {
- Logger.info(`[${TAG}] pipController is not exist`);
- return;
- }
- this.isOpenPip = false
- await this.pipController.stopPiP();
- }
- async createPipController() {
- this.pipController = await PiPWindow.create({
- context: getContext(this),
- componentController: this.xcomponentController,
- navigationId: this.navigationId,
- templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
- controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
- customUIController: this.nodeController,
- });
- this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
- this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
- this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
- this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
- this.onStateChange(state, reason);
- });
- this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
- this.onActionEvent(event, status);
- });
- }
- destroyPipController() {
- if (!this.pipController) {
- return;
- }
- this.pipController.off('stateChange');
- this.pipController.off('controlPanelActionEvent');
- this.pipController = undefined;
- }
- onStateChange(state: PiPWindow.PiPState, reason: string) {
- switch (state) {
- case PiPWindow.PiPState.ABOUT_TO_START:
- this.curState = 'ABOUT_TO_START';
- this.curError = $r('app.string.current_error_hint');
- break;
- case PiPWindow.PiPState.STARTED:
- this.curState = 'STARTED';
- this.curError = $r('app.string.current_error_hint');
- break;
- case PiPWindow.PiPState.ABOUT_TO_STOP:
- this.curState = 'ABOUT_TO_STOP';
- this.curError = $r('app.string.current_error_hint');
- break;
- case PiPWindow.PiPState.STOPPED:
- this.curState = 'STOPPED';
- this.curError = $r('app.string.current_error_hint');
- this.stopPip()
- this.destroyPipController()
- break;
- case PiPWindow.PiPState.ABOUT_TO_RESTORE:
- this.curState = 'ABOUT_TO_RESTORE';
- this.curError = $r('app.string.current_error_hint');
- break;
- case PiPWindow.PiPState.ERROR:
- this.curState = 'ERROR';
- this.curError = reason;
- break;
- default:
- break;
- }
- Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
- }
- onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
- LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
- switch (event) {
- case 'playbackStateChanged':
- if (status === 0) {
- this.pause();
- } else {
- console.info('onecold startPlayOrResumePlay 9869')
- this.startPlayOrResumePlay();
- }
- break;
- case 'nextVideo':
- // 切换到下一个视频
- this.playNext().catch(() => {
- Logger.error('heanup onActionEvent playNext', `播放下一首失败`);
- });
- break;
- case 'previousVideo':
- // 切换到上一个视频
- this.playPrevious().catch(() => {
- Logger.error('heanup onActionEvent playPrevious', `播放上一首失败`);
- });
- break;
- case 'previousVideo':
- // 切换到上一个视频
- this.playPrevious().catch(() => {
- Logger.error('heanup onActionEvent playPrevious', `播放上一首失败:`);
- });
- break;
- default:
- }
- this.buttonAction = event + `-status:${status}`;
- Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
- }
- /**
- * 画中画功能(悬浮歌词功能)结束
- *
- */
- async doSearchCover(item: VideoItem,title?:string,artist?:string): Promise<string> {
- if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
- this.isShowMoreView = false;
- this.showTipsDialog();
- return ''; // Return empty string when no API is configured
- }
- if (!item) {
- return ''; // Return empty string if item is undefined
- }
- const titleS = title||item?.name || '';
- const artistS = artist||item?.artist || ''; // Use empty string if artist is missing
- return this.searchCover(item, titleS, artistS); // Await is not needed here as we return the promise directly
- }
- /**
- *api搜索封面
- *item,根据title和artist
- */
- searchCover(item: VideoItem, title: string, artist: string): Promise<string> {
- return 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') {
- if (item.filePath == this.currentSong?.filePath) {
- this.cover = res;
- if (this.currentSong) {
- this.currentSong.pixelMapPath = res;
- }
- }
- // Update pixel map path but always return res regardless of success
- this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
- if (success) {
- this.doUpdateData();
- console.log("onecold 更新音乐封面成功,数据库已同步");
- } else {
- console.error("onecold 更新音乐封面数据库失败原因: " + error);
- }
- // Note: We don't resolve/reject here because we already returned res
- });
- LogUtil.debug("onecold this.cover =" + this.cover);
- }
- return res; // Always return res regardless of updatePixelMapPath result
- });
- }
- @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(this.themeColor)
- .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(this.themeColor)
- .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(this.themeColor)
- .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,false,false,true)
- }
- }
- private initDelayPlay(context: object) {
- this.mContext = context;
- }
- startPipLyric() {
- if (this.pipController) {
- this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
- PiPWindow.PiPControlStatus.PLAY);
- }
- this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
- if (this.isOpenPip) {
- this.startPip()
- } else {
- this.stopPip()
- }
- }
- //startOffset 从cue分轨时间开始播
- private startPlayOrResumePlay(startOffset?:number) {
- //针对dsf文件高采样率,统一转wav播放
- const sampleRate = this.currentSong?.sampleRate||0
- if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
- console.info('onecold 采样率 ='+sampleRate)
- let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
- console.info('onecold newDsfPath ='+newDsfPath)
- if(!FileUtil.accessSync(newDsfPath)){
- const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
- taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
- this.videoUrl = newDsfPath
- this.startPlay(startOffset)
- }).catch((e:object)=>{
- console.info("task1 catch e: " + e);
- })
- }else{
- this.videoUrl = newDsfPath
- this.startPlay(startOffset)
- }
- }else{
- this.startPlay(startOffset)
- }
- }
- startPlay(startOffset?:number) {
- this.startPipLyric()
- this.mDestroyPage = false;
- this.animationState = AnimationStatus.Running
- LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
- if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
- this.stopProgressTask();
- this.startProgressTask();
- this.play(this.videoUrl.toString(),startOffset);
- }
- if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
- this.mIjkMediaPlayer.start();
- this.setProgress()
- this.CONTROL_PlayStatus = PlayStatus.PLAY
- }
- this.setIsPlaying(true)
- this.updateSessionPlayState(true)
- this.watchStatus();
- this.updateLastPlayTimeStr(this.videoUrl)
- }
- updateLastPlayTimeStr(filePath: string) {
- // 检查是否为网络音频(WebDAV),如果是则不更新本地数据库
- if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
- Logger.info(`heanup 检测到网络音频播放,跳过数据库更新: ${filePath}`)
- return;
- }
- let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
- this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
- if (success) {
- this.getHistoryList(false)
- console.log(" onecold 更新最近播放时间成功,数据库已同步");
- } else {
- console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
- }
- });
- }
- 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.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
- this.lyricControllerSingle.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)})`
- //如果是开启AB循环
- if(this.isOpenAB){
- if(position >=this.jumpBTime){
- this.seekTo(this.jumpATime+'')
- return
- }
- }
- // 判断是否播放到结束时间
- if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
- if (position >= duration - this.jumpEndTime * 1000) {
- if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
- this.CONTROL_PlayStatus = PlayStatus.INIT
- this.startPlayOrResumePlay();
- }else if (this.playType == 2) { //2:正常播放,单曲播完
- this.showRePlay();
- this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
- this.progressValue = this.PROGRESS_MAX_VALUE;
- this.slideEnable = false;
- this.stop();
- // ToastUtil.showToast('开始重新播放')
- }else{
- this.playNext().catch(() => {
- Logger.error('heanup setProgress 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,startOffset?:number) {
- this.isShowBgLiuGUANG = PreferencesUtil.getBooleanSync('isShowBgLiuGUANG', true)
- console.info('onecold this.url 1= '+url)
- if(!url.toLowerCase().startsWith('http')){
- let hasPermission = await PermissionUtil.activatePermission(url)
- console.info('onecold this.hasPermission 1= '+hasPermission)
- if(!url.includes(this.packName)){
- const file = fs.openSync(url)
- this.videoUrl = file.path
- url= this.videoUrl
- }
- console.info('onecold this.hasPermission 1= '+hasPermission)
- console.info('onecold this.videoUrl 1= '+this.videoUrl)
- }
- let that = this;
- that.showLoadIng();
- this.isOpenAB = false
- //设置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 针对dsf格式设置最大值1.0
- if(this.volumeSmall){
- if(this.videoUrl.toLowerCase().endsWith('.dsf')){
- this.mIjkMediaPlayer.setVolume('1', '1');
- }else{
- this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
- }
- }else{
- this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
- }
- //设置视频源
- this.mIjkMediaPlayer.setDataSource(url);
- // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
- const headers = new Map<string, string>();
- headers.set("User-Agent", "TTMusic-WebDAV/1.0");
- headers.set("Accept", "*/*");
- if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
- &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
- //如果封面为空,则搜索封面
- this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
- }
- // 如果是WebDAV网络音频,使用webdav_account_id获取认证信息(等待完成后再设置一次性头部)
- if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
- Logger.info(`heanup WebDAV歌曲认证 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
- if (this.currentSong.webdav_account_id) {
- try {
- const webdavManager = RemoteDriveManager.getInstance();
- const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
- if (webDavHeaders && webDavHeaders.size > 0) {
- webDavHeaders.forEach((value, key) => headers.set(key, value));
- Logger.info(`heanup 成功通过webdav_account_id获取并合并WebDAV认证头`);
- } else {
- Logger.warn(`heanup 通过webdav_account_id获取认证头失败,播放可能无法继续`);
- }
- } catch (error) {
- const err = error as Error;
- Logger.error(`heanup 获取WebDAV认证头时出错: ${err.message}`);
- }
- } else {
- Logger.error(`heanup WebDAV歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法进行认证`);
- }
- }
- // 统一设置带认证的请求头
- this.mIjkMediaPlayer.setDataSourceHeader(headers);
- if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
- console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
- // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
- // 缓冲和播放优化设置
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1"); // 预加载启动
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
- // 网络相关设置
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
- // 重连设置
- this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
- console.log(`heanup WebDAV IjkPlayer选项设置完成`);
- }
- // 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 ; // 默认缓冲区大小为1MB
- if (fileSize > 3 * 1024 * 1024 * 1024) { // 文件大于3GB
- bufferSize = 25 * 1024 * 1024; // 设置缓冲区大小为25MB
- }
- // 使用软件解码(通常比硬件解码更节省内存)
- // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", '0');
- // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", '0');
- // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", '1024');
- // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzeduration", '500000');
- //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的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 {
- //保存碰一碰分享的当前的歌曲
- AppStorage.setOrCreate('currentSong',this.currentSong) ;
- let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
- await this.initLyric(lyricPath);
- setTimeout(() => {
- this.avSessionController.initAvSession(false);
- this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
- this.setAvSessionListener();
- this.updateSessionPlayState(true)
- this.setCurrentPlayMode()
- }, 500)
- if(startOffset&&startOffset>0){//cue分轨播放
- this.seekTo(startOffset + "");
- this.saveLastPlayList()
- return
- }
- //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
- 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) {
- let jumpTopTimeMs = this.jumpTopTime*1000;
- if (jumpTopTimeMs <= this.duration) {
- // 调用 seekTo 方法,跳到指定时间
- if(PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY,true)){
- console.log('onecold jumpTopTime = '+jumpTopTimeMs);
- const position:number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
- console.log('onecold position = '+position);
- if (position > jumpTopTimeMs) {
- jumpTopTimeMs = position
- }
- }
- 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
- console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
- console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
- console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
- PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
- //记忆播放(每一首都会记忆播放)
- 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() //读取播放记忆功能
- } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
- console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
- this.restorePlaybackPosition() //读取播放记忆功能
- }
- this.isFirstStartPlay = false
- }, timeoutPlay)
- } else {
- this.isFirstStartPlay = false
- }
- }
- 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:正常播放
- // 异步调用playNext
- this.playNext().catch(() => {
- Logger.error('heanup OnCompletionListener 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:随机播放
- // 异步调用randomPlay
- this.randomPlay().catch(() => {
- Logger.error('heanup OnCompletionListener 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");
- console.info('onecold startPlayOrResumePlay 10643')
- 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("heanup OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
- LogUtils.getInstance().LOGI('heanup 播放错误,歌曲详情:' + JSON.stringify(this.currentSong))
- // 检查是否为WebDAV播放错误
- let isWebDavError = false;
- if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.currentSong.filePath) {
- try {
- const globalContext = GlobalContext.getContext();
- const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
- if (webDavAuthInfo) {
- isWebDavError = true;
- }
- } catch (error) {
- console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
- }
- }
- if (isWebDavError) {
- Logger.error(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
- // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
- // this.currentWebDavAuthInfo = null;
- Logger.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
- // 根据错误代码提供更具体的错误信息
- let errorMessage = "WebDAV播放失败";
- if (what === -1) { // 网络错误
- errorMessage = "网络连接失败,请检查WebDAV服务器连接";
- } else if (what === -1004) { // HTTP 404
- errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
- } else if (what === -1001) { // 超时
- errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
- } else if (what === -1003) { // 无法解析主机
- errorMessage = "无法连接到WebDAV服务器";
- }
- ToastUtil.showToast(errorMessage);
- } else {
- if (StrUtil.isNotEmpty(this.videoUrl) &&
- !this.videoUrl.startsWith('http://') &&
- !this.videoUrl.startsWith('https://') &&
- !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"))
- }
- }
- that.hideLoadIng();
- }
- }
- this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
- this.mIjkMediaPlayer.setMessageListener();
- this.mIjkMediaPlayer.prepareAsync();
- this.mIjkMediaPlayer.start();
- }
- //保存最后播放的那首歌和已经对应的播放列表
- saveLastPlayList() {
- PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
- PreferencesUtil.putSync('LastMusicList', this.songList)
- }
- // 清空播放记录
- clearVideoHistory() {
- this.table.clearPlayHistory((success: boolean, error?: string) => {
- if (success) {
- this.historyList = [];
- this.updateListData(this.historyList)
- // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
- ToastUtil.showToast('清空播放记录成功')
- } else {
- console.error(" onecold 清空播放记录数据库失败原因: " + error);
- }
- });
- }
- 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;
- // 发送播放状态变化事件给歌单详情页面
- try {
- const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
- const currentFilePath = this.currentSong?.filePath || ''
- const eventData: emitter.EventData = {
- data: {
- isPlaying: this.isPlaying,
- curIndex: this.curIndex,
- currentFilePath: currentFilePath
- }
- };
- emitter.emit(eventPlaybackStatus, eventData)
- Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
- } catch (error) {
- Logger.error('heanup 发送播放状态变化事件失败: ' + error)
- }
- }
- 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().catch(() => {
- Logger.error('heanup playNextCallback', `播放下一首失败`);
- });
- };
- public playPreviousCallback = (): void => {
- this.playPrevious().catch(() => {
- Logger.error('heanup playNextCallback', `播放上一首失败`);
- });
- };
- 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.pause()
- };
- private playOrPause() {
- if (!this.debounce()) {
- return;
- }
- if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
- this.pause();
- } else {
- console.info('onecold startPlayOrResumePlay 11064')
- this.startPlayOrResumePlay();
- this.playChange()
- }
- }
- private sessionPlayNextCallback = (): void => {
- this.playNext().catch(() => {
- Logger.error('heanup sessionPlayPreviousCallback', `播放下 一首失败`);
- });
- };
- private sessionPlayPreviousCallback = (): void => {
- this.playPrevious().catch(() => {
- Logger.error('heanup sessionPlayPreviousCallback', `播放上一首失败`);
- });
- };
- 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()
- if (this.pipController) {
- this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
- PiPWindow.PiPControlStatus.PAUSE);
- }
- }
- }
- 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) {
- if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
- ToastUtil.showToast('wma格式不支持拖动快进。')
- return
- }
- this.isSeekTo = true
- this.mIjkMediaPlayer.seekTo(value);
- console.info('onecold startPlayOrResumePlay 11227')
- // this.startPlayOrResumePlay()
- // 在这里恢复计时器状态
- this.setProgress()
- this.isSeekTo = false
- }
- // 添加到下一首播放
- 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('已添加至下一首播放')
- }
- //后退10s,可再设置设置默认几秒
- backForward() {
- if(this.mIjkMediaPlayer){
- let pos = this.mIjkMediaPlayer.getCurrentPosition();
- let value = pos - Number(this.fastForwardSeconds) * 1000;
- this.seekTo(value+"");
- }
- }
- //快进10s,可再设置设置默认几秒
- fastForward() {
- if(this.mIjkMediaPlayer){
- let pos = this.mIjkMediaPlayer.getCurrentPosition();
- let value = pos + Number(this.fastForwardSeconds) * 1000;
- this.seekTo(value+"");
- }
- }
- //下一个
- private async playNext() {
- if (!this.debounce()) {
- return;
- }
- if (this.playType == 3) { //3:随机播放
- await 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();
- // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
- this.currentSong = this.songList[this.curIndex];
- Logger.info('heanup playNext', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
- // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
- this.videoUrl = await setVideoUrlForSong(this.currentSong, {
- context: this.context,
- autoParseMusicName: this.autoParseMusicName
- });
- this.artist = this.songList[this.curIndex].artist
- this.name = this.songList[this.curIndex].name
- //this.cover = this.songList[this.curIndex].pixelMapPath
- this.changeImageAnimation()
- }
- }
- changeImageAnimation() {
- if(this.openSkipSongAnimate){
- // 第一步:淡出动画
- this.getUIContext()?.animateTo({
- duration: 500,
- curve: Curve.EaseOut,
- }, () => {
- this.opacityValueImage = 0.1;
- if(this.isCoverRectangle){
- this.scaleValueImage = 0.88
- }
- });
- // 第二步:切换图片后淡入
- setTimeout(() => {
- this.cover = this.songList[this.curIndex].pixelMapPath
- this.getUIContext()?.animateTo({
- duration: 500,
- curve: Curve.EaseIn,
- }, () => {
- this.opacityValueImage = 1;
- this.scaleValueImage = 1 // 图标恢复到原始大小
- this.startPlayOrResumePlay()
- });
- }, 500);
- }else{
- this.cover = this.songList[this.curIndex].pixelMapPath
- this.startPlayOrResumePlay()
- }
- }
- // 存储已播放的歌曲索引
- private playedIndices: Set<number> = new Set();
- //随机播放
- private async 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;
- // 添加超时机制防止无限循环
- let attempt = 0;
- const maxAttempts = 100; // 根据需求调整
- do {
- newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
- attempt++;
- } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
- if (attempt >= maxAttempts) {
- // 处理无法找到新索引的情况(如随机选择或按顺序播放)
- newIndex = Math.floor(Math.random() * this.songList.length);
- }
- 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];
- // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
- this.videoUrl = await setVideoUrlForSong(this.currentSong, {
- context: this.context,
- autoParseMusicName: this.autoParseMusicName
- });
- this.name = this.songList[this.curIndex].name;
- this.artist = this.songList[this.curIndex].artist
- // this.cover = this.songList[this.curIndex].pixelMapPath
- this.changeImageAnimation()
- }
- }
- private async playIndex(index: number) {
- if (!this.debounce()) {
- return;
- }
- if (ArrayUtil.isNotEmpty(this.songList)) {
- this.CONTROL_PlayStatus = PlayStatus.INIT;
- this.stop();
- this.curIndex = index;
- this.currentSong = this.songList[index];
- // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
- this.videoUrl = await setVideoUrlForSong(this.currentSong, {
- context: this.context,
- autoParseMusicName: this.autoParseMusicName
- });
- this.name = this.currentSong.name
- this.artist = this.currentSong.artist
- this.changeImageAnimation()
- }
- }
- //上一个
- private async playPrevious() {
- if (!this.debounce()) {
- return;
- }
- if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
- this.randomModePlayFromHistory()
- return;
- }
- if (this.curIndex == 0) {
- this.curIndex = this.songList.length - 1;
- } else {
- this.curIndex--;
- }
- this.CONTROL_PlayStatus = PlayStatus.INIT;
- this.stop();
- // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
- this.currentSong = this.songList[this.curIndex];
- Logger.info('heanup playPrevious', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
- // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
- this.videoUrl = await setVideoUrlForSong(this.currentSong, {
- context: this.context,
- autoParseMusicName: this.autoParseMusicName
- });
- this.name = this.songList[this.curIndex].name
- this.artist = this.songList[this.curIndex].artist
- this.changeImageAnimation()
- }
- //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
- private async randomModePlayFromHistory() {
- if (this.historyList.length >= 2) {
- // 播放历史记录的第二首
- const prevSong = this.historyList[1];
- this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
- this.CONTROL_PlayStatus = PlayStatus.INIT;
- this.stop();
- // 直接使用历史记录中的歌曲信息,历史记录中的数据应该是完整的
- this.currentSong = prevSong;
- Logger.info('heanup randomModePlayFromHistory', `直接使用历史歌曲信息: ${prevSong.name}, type: ${prevSong.type}`);
- // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
- this.videoUrl = await setVideoUrlForSong(this.currentSong, {
- context: this.context,
- autoParseMusicName: this.autoParseMusicName
- });
- this.cover = prevSong.pixelMapPath
- this.artist = prevSong.artist
- this.name = prevSong.name;
- console.info('onecold startPlayOrResumePlay 11434')
- this.startPlayOrResumePlay();
- } else {
- // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
- if (this.curIndex === 0) {
- this.curIndex = this.songList.length - 1;
- } else {
- this.curIndex--;
- }
- this.CONTROL_PlayStatus = PlayStatus.INIT;
- this.stop();
- // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
- this.currentSong = this.songList[this.curIndex];
- Logger.info('heanup randomModePlayFromHistory', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
- // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
- this.videoUrl = await setVideoUrlForSong(this.currentSong, {
- context: this.context,
- autoParseMusicName: this.autoParseMusicName
- });
- this.artist = this.songList[this.curIndex].artist
- this.name = this.songList[this.curIndex].name;
- this.changeImageAnimation()
- }
- }
- 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(this.themeColor)
- .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(this.themeColor)
- .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(this.themeColor)
- .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(this.themeColor)
- .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(this.themeColor)
- .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(this.themeColor)
- .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(this.themeColor)
- .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.selectedFiles.push(item)
- this.showWarnIsDelete()
- // this.showWarnIsDeleteFile(item, index + '', filePath)
- })
- Button() {
- Image($r('app.media.share2'))
- .fillColor(Color.White)
- .width(20)
- }
- .width(40)
- .height(40)
- .type(ButtonType.Circle)
- .backgroundColor(this.themeColor)
- .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 = "已展示"
- // }
- /**
- * 穿山甲广告代码结束
- */
- /**
- * 处理歌单播放请求
- */
- private async handlePlaylistPlayRequest(playlistId: string, playlistName:
- string, songFilePaths: string[], startIndex: number) {
- try {
- Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 歌曲数量: ${songFilePaths.length}, 开始索引: ${startIndex}`)
- // 检查是否为WebDAV播放请求
- if (playlistId === 'webdav-playlist') {
- Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
- // 从全局内存读取videoItems数据
- const videoItems = getWebdavVideoItems();
- const currentPlayIndex = getWebdavCurrentPlayIndex();
- Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
- if (videoItems && videoItems.length > 0) {
- // 验证webdav_account_id设置情况
- const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
- Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
- this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName)
- return
- } else {
- return
- }
- }
- // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
- const songMap: Map<number, VideoItem> = new Map()
- let completedQueries = 0
- Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
- // 遍历所有文件路径,使用索引记录位置
- for (let i = 0; i < songFilePaths.length; i++) {
- const filePath = songFilePaths[i]
- const index = i
- // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
- // 使用已初始化的MediaTable实例从数据库查询歌曲信息
- const queryPromise = this.table.queryVideoByFilePath(filePath)
- // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
- queryPromise.then((videoItem) => {
- completedQueries++
- // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
- if (videoItem) {
- // 使用索引作为key保存到Map中,保持原始顺序
- songMap.set(index, videoItem)
- // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
- } else {
- Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
- }
- // 检查是否所有歌曲都已加载完成
- if (completedQueries === songFilePaths.length) {
- // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
- // 按照索引顺序重建歌曲数组
- const songs: VideoItem[] = []
- for (let j = 0; j < songFilePaths.length; j++) {
- const song = songMap.get(j)
- if (song) {
- songs.push(song)
- // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
- }
- }
- Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
- this.finishLoadingPlaylist(songs, startIndex, playlistName)
- }
- }).catch((error: Error) => {
- completedQueries++
- Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
- // 即使出错也要检查是否完成所有查询
- if (completedQueries === songFilePaths.length) {
- Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
- // 按照索引顺序重建歌曲数组
- const songs: VideoItem[] = []
- for (let j = 0; j < songFilePaths.length; j++) {
- const song = songMap.get(j)
- if (song) {
- songs.push(song)
- }
- }
- this.finishLoadingPlaylist(songs, startIndex, playlistName)
- }
- })
- }
- } catch (error) {
- Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
- ToastUtil.showToast('播放失败')
- }
- }
- /**
- * 完成歌单加载并开始播放
- */
- private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string) {
- if (songs.length === 0) {
- Logger.error('heanup 没有找到任何可播放的歌曲')
- ToastUtil.showToast('没有找到可播放的歌曲')
- return
- }
- this.songList = songs
- this.sonDataSource.pushArrayData(songs)
- this.sonDataSource.notifyDataReload()
- this.curIndex = startIndex
- if (songs[startIndex]) {
- // 确保当前播放的歌曲也更新到存储
- AppStorage.setOrCreate('currentSong', songs[startIndex])
- // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
- this.doPlay(songs[startIndex], startIndex, true)
- }
- PreferencesUtil.putSync('LastMusicList', this.songList)
- ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
- }
- }
- //视频气泡窗口的布局
- @Builder
- function customPopupBuilder(dataBu: BubbleBean) {
- List() {
- LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
- ListItem() {
- Button({ type: ButtonType.Capsule, stateEffect: true }) {
- Row() {
- Column() {
- Image(dataBu.imageRes[index])
- .height(28)
- .fillColor(dataBu.color)
- .alignSelf(ItemAlign.Center)
- }
- .width(32)
- Text(item)
- .padding({
- top: 10,
- bottom: 10,
- right: 10,
- left: 10
- })
- .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
- .textAlign(TextAlign.Start)
- .width("100%")
- }
- }
- .backgroundColor($r('app.color.settings_background_main'))
- .margin({ top: 6, bottom: 6 })
- }
- .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
- .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
- TransitionEffect.scale({ x: 0, y: 0 })))
- // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
- // TransitionEffect.scale({ x: 0, y: 0 }) ))
- .onClick(() => {
- dataBu.onItemClick?.(index)
- })
- })
- }
- .scrollBar(BarState.Off)
- .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() {
- Button({ type: ButtonType.Capsule, stateEffect: true }) {
- Row() {
- Column() {
- Image($r('app.media.music_group'))
- .height(28)
- .fillColor(dataBu.color)
- .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)
- }
- }
- .backgroundColor(Color.Transparent)
- .margin({ top: 7, bottom: 7 })
- }
- .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
- .animation({ duration: 500 }),
- TransitionEffect.scale({ x: 0, y: 0 })))
- // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
- // TransitionEffect.scale({ x: 0, y: 0 }) ))
- .onClick(() => {
- dataBu.onItemClick?.(index)
- })
- })
- }
- .scrollBar(BarState.Off)
- .width(150)
- .divider({
- strokeWidth: 1,
- color: "#22FFFFFF"
- })
- }
- .height(300)
- .padding({
- bottom: 30
- })
- }
- function getFileDirName(filePath: string,rootPath:string): string{
- if(filePath===rootPath){
- return '首页'
- }
- let result = FileUtil.getFileName(filePath)
- if(StrUtil.isEmpty(result))
- return ''
- if(result.startsWith('.'))
- result = result.replace(/\./g, '')
- return result
- }
- //只扫描当前目录下文件(不扫描子文件夹)的方法
- @Concurrent
- async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
- const table: MediaTable = new MediaTable(context);
- try {
- // 直接获取当前目录下的文件列表
- const files = FileUtil.listFileSync(dirPath);
- await Promise.all(files.map(async (file) => {
- const fPath = `${dirPath}/${file}`;
- // 跳过目录,只处理文件
- if (FileUtil.isDirectory(fPath)) {
- return;
- }
- // 跳过特定格式文件
- if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
- return;
- }
- // 检查是否为媒体文件
- if (Utility.isMeidaByExtension(fPath)) {
- let mType = CommonConstants.TYPE_LOCAL;
- if (fPath.includes(lockPath)) {
- mType = CommonConstants.TYPE_LOCK;
- }
- const mediaItem = await Utility.uriGetMusicAssetsFromFile(
- context, fPath, mType, true
- );
- table.insert(mediaItem, (id: number) => {
- // 插入回调函数
- }, cover_api);
- }
- }));
- } catch (error) {
- console.error(' 扫描当前目录失败:', error);
- }
- }
- //内嵌标签后更新库
- @Concurrent
- async function updateInfoDb(
- context: Context,
- filePath: string,
- titleStr: string,
- artistStr: string,
- albumStr: string,
- lyricConStr: string,
- yearStr: string,
- genreStr: string,
- trackStr: string,
- albumArtistStr: string,
- composerStr: string,
- lyricistStr: string,
- commentStr: string,
- discStr: string,
- ): Promise<boolean> {
- const table: MediaTable = new MediaTable(context);
- await new Promise<void>((resolve, reject) => {
- table.getRdbStore(context, (err:Error) => {
- err ? reject(err) : resolve();
- });
- });
- return await new Promise<boolean>((resolve) => {
- table.updateMediaInfo(filePath, titleStr, artistStr, albumStr, lyricConStr,
- yearStr, genreStr, trackStr, albumArtistStr, composerStr, lyricistStr, commentStr, discStr,
- (success: boolean, error?: string) => {
- if (success) {
- console.log("onecold 编辑信息成功,数据库已同步");
- } else {
- console.error("onecold 编辑信息数据库失败原因: " + error);
- }
- resolve(success);
- });
- });
- }
|