LocalMusic.ets 494 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249
  1. import TitleBar from './TitleBar'
  2. import { curves, display, MenuModifier,PiPWindow, promptAction, router, SymbolGlyphModifier, window } from '@kit.ArkUI';
  3. import { VideoItem } from '../viewmodel/VideoItem';
  4. import { LengthMetrics, SegmentButton,SegmentButtonOptions } from '@kit.ArkUI';
  5. import { getWebdavVideoItems, getWebdavCurrentPlayIndex } from '../pages/WebDavMainPage';
  6. import {
  7. ButtonFancyModifier,
  8. ImageFancyModifier,
  9. ShadowModifier,
  10. SymbolGlyphFancyModifier } from '../common/util/AttributeModifierUtil'
  11. import {
  12. AppUtil,
  13. ArrayUtil,
  14. Base64Util,
  15. DateUtil,
  16. DeviceUtil,
  17. FileUtil,
  18. GlobalContext,
  19. LogUtil,
  20. MD5,
  21. PreferencesUtil,
  22. RandomUtil,
  23. StrUtil,
  24. ToastUtil
  25. } from '@pura/harmony-utils';
  26. import { imagePathToPixelMap } from '../common/util/CommUtils';
  27. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  28. import { CommonConstants } from '../common/constants/CommonConstants';
  29. import { EventConstants } from '../common/constants/EventConstants';
  30. import Logger from '../common/util/Logger';
  31. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  32. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  33. import { BubbleBean } from '../viewmodel/BubbleBean';
  34. import { PopupPosition, XPopup } from '@chinalike/popup';
  35. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  36. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  37. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  38. import { MessageEvents, util, worker, ErrorEvent } from '@kit.ArkTS';
  39. import { Verify } from './Verify';
  40. import { taskpool } from '@kit.ArkTS';
  41. import { RotatingCover } from './RotatingCover';
  42. import { PlayConstants } from '../common/constants/PlayConstants';
  43. import { effectKit } from '@kit.ArkGraphics2D';
  44. import { ColorConversion } from '../common/util/ColorConversion';
  45. import { LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  46. import { AvSessionController } from '../controller/AvSessionController';
  47. import { repairAudioMetadata, convertDsfToWav, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  48. import { FFMpegTags,Utility } from '../common/util/Utility';
  49. import { TagsContentCover } from '../view/TagsContentCover';
  50. import {
  51. // DeviceChangeReason,
  52. IjkMediaPlayer,
  53. InterruptEvent,
  54. InterruptHintType,
  55. LogUtils,
  56. OnBufferingUpdateListener,
  57. OnCompletionListener,
  58. OnErrorListener,
  59. OnInfoListener,
  60. OnPreparedListener,
  61. OnSeekCompleteListener,
  62. OnTimedTextListener,
  63. OnVideoSizeChangedListener
  64. } from '@ohos/ijkplayer';
  65. import { PlayStatus } from '../common/PlayStatus';
  66. import fs from '@ohos.file.fs';
  67. import { image } from '@kit.ImageKit';
  68. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  69. import { UniversalDetector } from '@ohos/juniversalchardet';
  70. import { SettingPage } from '../pages/SettingPage';
  71. import { secondToTime,getTransverterText } from '../common/util/CommUtils';
  72. import { CommonConstants2 } from '../common/util/CommonConstants2';
  73. import { hilog } from '@kit.PerformanceAnalysisKit';
  74. import { LazyDataSource } from '../common/util/LazyDataSource';
  75. import MediaTable from '../common/util/MediaTable';
  76. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  77. import ImageUtils from '../common/util/ImageUtils';
  78. import { ringtone } from '@kit.RingtoneKit';
  79. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  80. import { resourceManager } from '@kit.LocalizationKit';
  81. import { deviceInfo } from '@kit.BasicServicesKit';
  82. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  83. import app from '@system.app';
  84. import { TextNodeController } from './PipLyricTextBuilder';
  85. import { IndexerView } from './IndexerView';
  86. import { KeyCode } from '@kit.InputKit';
  87. import { KnockController } from '../controller/KnockController';
  88. import { DeleteComptent } from '../view/DeleteComptent';
  89. import { ABLoopComptent } from '../view/ABLoopComptent';
  90. import { FixMessyView } from '../view/FixMessyView';
  91. import { parseCueFile,CueTrack,CueInfo } from '../common/util/CueUtils';
  92. import { CueComptent } from '../view/CueComptent';
  93. import PlaylistTable from '../common/util/PlaylistTable';
  94. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  95. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  96. import { convertPlaylistSongsToVideoItems, emptyView,updateAllSongsSortOrder } from '../pages/PlaylistDetailPage';
  97. import { Playlist, PlaylistSong } from '../viewmodel/Playlist';
  98. import { Song } from '../viewmodel/Song';
  99. import { SongType } from '../common/enums/SongType';
  100. import { WebdavManager, WebDavAuthInfo as WebDavManagerAuthInfo,
  101. buildHttpHeadersWithWebDav,
  102. WebDavAuthItem} from '../common/util/WebdavManager';
  103. import PermissionUtil from '../common/util/PermissionUtil'
  104. import { EditAudio, setRingTone } from './EditAudio';
  105. import { ExtractAccompaniment } from './ExtractAccompaniment';
  106. import { ExtractAudioFromVideo } from './ExtractAudioFromVideo';
  107. import { AudioFormatConverter } from './AudioFormatConverter';
  108. import { MergeAudio } from './MergeAudio';
  109. import { AIVoiceSeparation } from './AIVoiceSeparation';
  110. import { WebDavUrlUtil } from '../common/util/WebDavUrlUtil';
  111. import {
  112. hdsEffect,
  113. HdsVisualComponent,
  114. HdsSceneController,
  115. HdsSceneType,
  116. HdsVisualComponentAttribute,
  117. } from '@kit.UIDesignKit';
  118. const TAG = 'LocalMusic';
  119. /**
  120. * 歌单播放事件数据
  121. */
  122. interface PlaylistEventData {
  123. playlistId: string;
  124. playlistName: string;
  125. songCount: number;
  126. startIndex: number;
  127. songFilePaths: string[];
  128. webDavAuthInfo?: WebDavAuthItem; // 新增WebDAV认证信息
  129. }
  130. const DEFAULT_INDEX =
  131. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  132. 'X', 'Y', 'Z']
  133. //排序类型
  134. function getTypeOrder(type: number) {
  135. switch (type) {
  136. case CommonConstants.TYPE_IS_DIR:
  137. return 1; // First
  138. case CommonConstants.TYPE_IS_CSJAD:
  139. return 2; // Middle
  140. case CommonConstants.TYPE_LOCAL:
  141. return 3; // Last
  142. default:
  143. return 4; // Unknown types, if any, go last
  144. }
  145. }
  146. /**
  147. * 异步设置videoUrl的辅助方法,处理WebDAV URL的构建
  148. * @param song 歌曲对象
  149. * @returns Promise<string> 完整的URL
  150. */
  151. /**
  152. * 设置videoUrl,通过webdav_account_id设置完整的 URL
  153. * @param song 歌曲对象
  154. * @returns Promise<string> 完整的URL
  155. */
  156. async function setVideoUrlForSong(song: VideoItem): Promise<string> {
  157. if (song.type === CommonConstants.TYPE_WEBDAV && song.webdav_account_id) {
  158. try {
  159. Logger.info(TAG, `WebDAV完整URL构建成功remote_rel_path: ${song.remote_rel_path}`);
  160. Logger.info(TAG, `WebDAV完整URL构建成功song.filePath: ${song.filePath}`);
  161. // 优先使用远端相对路径,其次回退到 filePath
  162. const relativePath = song.remote_rel_path || song.filePath;
  163. const fullUrl = await WebDavUrlUtil.buildFullUrlByAccountId(song.webdav_account_id, relativePath);
  164. if (fullUrl) {
  165. Logger.info(TAG, `WebDAV完整URL构建成功: ${fullUrl}`);
  166. return fullUrl.replace(/ /g, '%20');
  167. } else {
  168. Logger.error(TAG, `WebDAV URL构建失败,使用原始路径: ${relativePath}`);
  169. return relativePath.replace(/ /g, '%20');
  170. }
  171. } catch (error) {
  172. Logger.error(TAG, `WebDAV URL构建出错: ${(error as Error).message}`);
  173. const fallbackPath = song.remote_rel_path || song.filePath;
  174. return fallbackPath.replace(/ /g, '%20');
  175. }
  176. } else {
  177. // 非WebDAV文件或缺少webdav_account_id,直接使用原始路径
  178. if (song.type === CommonConstants.TYPE_WEBDAV) {
  179. Logger.warn(TAG, `WebDAV歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
  180. }
  181. return song.type === CommonConstants.TYPE_WEBDAV ?
  182. song.filePath.replace(/ /g, '%20') :
  183. song.filePath;
  184. }
  185. }
  186. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  187. // 定义接口
  188. interface HiCarAspectRatio {
  189. ratio: number;
  190. name: string;
  191. }
  192. interface GeneratedObjectLiteralInterface_1 {
  193. assetId: string;
  194. title: string;
  195. artist: string;
  196. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  197. mediaUri: string;
  198. // 该字段大写,音频'AUDIO',视频'VIDEO'
  199. mediaType: string;
  200. mediaSize: number;
  201. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  202. startPosition: number;
  203. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  204. duration: number;
  205. albumCoverUri: string;
  206. albumTitle: string;
  207. appName: string;
  208. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  209. drmScheme: string;
  210. }
  211. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  212. const ITEM_HEIGHT: number = 65; // 列表项中高度
  213. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  214. //功能强大的音乐播放器
  215. @Preview
  216. @Component
  217. export struct LocalMusic {
  218. @State isShowPrecious: boolean = false //播控条显示上一首按钮
  219. //背景两侧流光控制器
  220. @State sceneBgController: HdsSceneController|undefined = deviceInfo.sdkApiVersion>=20
  221. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  222. new HdsSceneController()
  223. .setSceneParams({
  224. backgroundMaskColors: [Color.Green, Color.Red],
  225. firstEdgeFlowLight: {
  226. startPos: 0,
  227. endPos: 0.5,
  228. color: Color.Red
  229. },
  230. secondEdgeFlowLight: {
  231. startPos: 0,
  232. endPos: -0.5,
  233. color: Color.Green
  234. }
  235. }) : undefined;
  236. //背景流光控制器
  237. @State bgController: hdsEffect.ShaderEffectController|undefined = deviceInfo.sdkApiVersion>=20
  238. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  239. new hdsEffect.ShaderEffectController():undefined;
  240. @State showAddSheet:boolean = false
  241. searchController: SearchController = new SearchController()
  242. @State rightTopImage:Resource = $r('sys.symbol.sort')
  243. @State isEditAudio:boolean = false
  244. @State isExtractAcc:boolean = false
  245. @State isConverter:boolean = false
  246. @State isAIVoiceSeparation:boolean = false
  247. @State isExtractAudio:boolean = false
  248. @State isMergeAudio:boolean = false
  249. @State isCopyFileToDownLoad: boolean = false
  250. @State offHeight: number = 75
  251. @State currentSongList: Array<VideoItem> = []//当前歌单
  252. @Consume currentSongListName:string //当前歌单名称
  253. @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
  254. @State isRefreshing: boolean = false;
  255. @State maxRefreshingHeight: number = 100.0;
  256. private contentNode?: ComponentContent<Object> = undefined;
  257. // WebDAV相关实例变量(现在改为从内存读取,不再需要存储)
  258. @State ratioL: number = 1;
  259. @State mediaKuCount: number = 0;
  260. @State albumCount: number = 0;
  261. @State artistCount: number = 0;
  262. @State fastForwardSeconds: string = '10'
  263. @State isShowBackFast: boolean = true//快进快退按钮
  264. @State isCanAuto:boolean = true
  265. @State opacityValueImage: number = 1;
  266. @State tipPopup:boolean = false
  267. @Consume mType: number;
  268. @StorageProp('themeColor') themeColor: string =
  269. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  270. themeMode: number = 0;
  271. @State titleName: string = '首页'
  272. @State textStr: string = ''
  273. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  274. // private download_path: string = '';
  275. @Consume rootPath: string //音频根目录
  276. @Consume currentPath: string
  277. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  278. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  279. @State lockPath: string = ''
  280. @State favPath: string = ''
  281. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  282. @State historyPath: string = ''
  283. @State historyList: Array<VideoItem> = []
  284. @Consume isHistory: boolean
  285. static readonly HISTORY_MUSIC: string = 'music_historyList';
  286. private table: MediaTable = new MediaTable(getContext(this))
  287. private playlistTable: PlaylistTable | null = null
  288. @State allPlaylists: Playlist[] = []
  289. @State isZero: boolean = false
  290. @State fileList: Array<string> = []
  291. @State dirList: Array<VideoItem> = []
  292. @Consume videoLocalList:VideoItem[]
  293. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  294. // @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  295. @StorageProp('mediaKuList') mediaKuList: Array<VideoItem> = []; //媒体库文件
  296. @State artistList: Array<VideoItem> = []; //艺术家文件
  297. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  298. @State albumList: Array<VideoItem> = []; //专辑文件
  299. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  300. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  301. @State imageOpacities: number[] = [];
  302. @Consume isCanBack: boolean
  303. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  304. @State showSingleLyric: boolean = false
  305. @State sortType: number = 4 //默认排序方式
  306. @State isShowSimi: boolean = false //是否显示私密音频
  307. @State isShowFAV: boolean = true //是否显示我的收藏
  308. @State @Watch('onTopBarhange')isShowTitleBar: boolean = true //是否显示分类导航条
  309. @State isShowAllBar: boolean = true //是否显示播放全部条
  310. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  311. @State isShowHistory: boolean = true //是否显示最近播放
  312. @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
  313. @State isGridMusic: boolean = false //是否网格布局
  314. @State isCircleBtn: boolean = false //是否圆形播放按钮
  315. @State twoFingerType: number = 3 //双支放大缩小的类型
  316. @State isScrollHide: boolean = false //是否滚动隐藏
  317. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  318. @State isStartAutoPlay: boolean = false //启动后自动播放
  319. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  320. @State isShowHeader: boolean = true
  321. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  322. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  323. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  324. @State isSwipe: boolean = false //listItem的左滑开关
  325. @State openSkipSongAnimate: boolean = true//切歌动画效果
  326. @State customizeBgPath: string | undefined = '';
  327. @State isDarkMode: boolean = false
  328. @State lyricTextWeight: number = 400
  329. @State lyricTextWeightPip: number = 400
  330. @State currentSwiperIndex: number = 0
  331. @State blurValue: number = 0 //背景模糊
  332. @State bgBrightness: number = 0 //背景亮度
  333. private listScroller: ListScroller = new ListScroller()
  334. private playListScroller: Scroller = new Scroller()
  335. @State isOneKeyTags:boolean = false
  336. @State isFixMessy:boolean = false
  337. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  338. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  339. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  340. @StorageProp('windowWidth') windowWidth: number = 0;
  341. @StorageProp('windowHeight') windowHeight: number = 0;
  342. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  343. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  344. private UNKONWN:string = '';
  345. private listArea: Area = {
  346. width: 0,
  347. height: 0,
  348. position: {},
  349. globalPosition: {}
  350. }
  351. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  352. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  353. // WebDAV认证信息缓存(作为实例变量,比全局上下文更可靠)
  354. private currentWebDavAuthInfo: WebDavAuthItem | null = null;
  355. //瀑布流的列数横竖屏动态切换
  356. onIsLandscapeChange() {
  357. if(this.isLandscape){
  358. this.columns = 4
  359. }else{
  360. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  361. }
  362. }
  363. onColorModeChange() {
  364. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  365. }
  366. //bar导航条显示状态变化,不显示的话把topBarHeight=0
  367. onTopBarhange(){
  368. if(this.isShowTitleBar){
  369. console.log('onecold 导航条显示')
  370. this.topBarHeight = 50
  371. this.offHeight = 75
  372. }else{
  373. console.log('onecold 导航条隐藏')
  374. this.topBarHeight = 0
  375. if(this.twoFingerType!=4){
  376. this.offHeight = 30
  377. }
  378. }
  379. }
  380. //点击某个歌单id发生变化的时候回调
  381. onIDChange(){
  382. console.log('onecold 歌单id发生变化this.currentSongListID='+this.currentSongListID)
  383. console.log('onecold 歌单id发生变化this.currentSongListName='+this.currentSongListName)
  384. if(this.modeType==4){
  385. this.isShowTitleBar = false
  386. this.titleName = this.currentSongListName
  387. this.rightTopImage = $r('sys.symbol.sort')
  388. //获取缓存
  389. const cacheSongs:string =PreferencesUtil.getStringSync(this.currentSongListID+'currentSongList', '')
  390. console.log('onecold 歌单id发生变化获取缓存2 cacheSongs = '+cacheSongs)
  391. if(StrUtil.isNotEmpty(cacheSongs)){
  392. this.currentSongList = JSON.parse(cacheSongs) as VideoItem[]
  393. this.updateListData(this.currentSongList, true)
  394. }
  395. this.doSongListTask()//获取歌单信息
  396. }
  397. }
  398. async doSongListTask() {
  399. // 初始化歌单数据库
  400. const playlistTable = new PlaylistTable(this.context);
  401. // 查询歌单中的所有歌曲
  402. const playlistSongs: PlaylistSong[] = await playlistTable.queryPlaylistSongs(this.currentSongListID);
  403. console.log('onecold 歌单id发生变化获取缓存7 playlistSongs='+playlistSongs.length)
  404. if (ArrayUtil.isEmpty(playlistSongs)) {
  405. this.updateListData([], true)
  406. } else {
  407. this.currentSongList = await convertPlaylistSongsToVideoItems(this.context, playlistSongs);
  408. console.log('onecold 从数据库读取的歌曲为 playlistSongs='+this.currentSongList.length)
  409. this.updateListData(this.currentSongList, true)
  410. if (ArrayUtil.isNotEmpty(this.currentSongList)&&this.currentSongList.length > 100) {
  411. // 只保存前100条记录到缓存中
  412. let canceList = this.currentSongList.slice(0, 100);
  413. PreferencesUtil.putSync(this.currentSongListID+'currentSongList',
  414. JSON.stringify(canceList))
  415. } else {
  416. PreferencesUtil.putSync(this.currentSongListID+'currentSongList', JSON.stringify(this.currentSongList));
  417. }
  418. }
  419. this.isRefreshing = false
  420. }
  421. onModeChange() {
  422. this.isFavMusic = false
  423. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, false)
  424. switch (this.modeType) {
  425. case 0:
  426. this.getSortedFiles(this.currentPath)
  427. break
  428. case 1:
  429. this.rightTopImage = $r('sys.symbol.sort')
  430. this.updateListData(this.mediaKuList)
  431. this.titleName = Utility.resourceToString(this.context,$r('app.string.media_ku'))
  432. break
  433. case 2:
  434. this.rightTopImage = $r('sys.symbol.sort')
  435. this.updateListData(this.artistList)
  436. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  437. break
  438. case 3:
  439. this.rightTopImage = $r('sys.symbol.sort')
  440. this.updateListData(this.albumList)
  441. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  442. break
  443. }
  444. }
  445. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  446. // @StorageLink('isPlay') isPlay: boolean = false;
  447. @StorageLink('isShowPlay') isShowPlay: boolean = false;
  448. @StorageLink('songList') songList: Array<VideoItem> = [];
  449. @State translateY: number = 0;
  450. @State isShowSheet: boolean = false;
  451. @State isShowSheetView: boolean = false;
  452. @State isShowTimeCloseView: boolean = false;
  453. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  454. @StorageLink('currIndex') curIndex: number = 0;
  455. @Consume isShowDrawer: boolean;
  456. @Consume offsetX: number;
  457. @State isFac: boolean = false;
  458. @State favList: Array<VideoItem> = []
  459. @Consume isFavMusic: boolean
  460. @State isClickedPLayAll: boolean = false;
  461. private scrollerForlist: ListScroller = new ListScroller();
  462. private knockController: KnockController | undefined = undefined;
  463. imagesF: ImageFrameInfo[] = [
  464. { src: $r("app.media.app_loading0") },
  465. { src: $r("app.media.app_loading1") },
  466. { src: $r("app.media.app_loading2") },
  467. { src: $r("app.media.app_loading3") },
  468. ]
  469. @State animationState: AnimationStatus = AnimationStatus.Initial
  470. // 缓存机制
  471. private cache: Map<string, Array<VideoItem>> = new Map();
  472. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  473. // 持久化缓存
  474. private async saveCacheToStorage() {
  475. const cacheArray = Array.from(this.cache.entries());
  476. const stringCacheArray = Array.from(this.stringCache.entries());
  477. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  478. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  479. }
  480. // 载入缓存
  481. private async loadCacheFromStorage() {
  482. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  483. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  484. if (cacheString) {
  485. const cacheArray: [string, Array<VideoItem>][] = JSON.parse(cacheString);
  486. this.cache = new Map(cacheArray);
  487. }
  488. if (stringCacheString) {
  489. const stringCacheArray: [string, string][] = JSON.parse(stringCacheString);
  490. this.stringCache = new Map(stringCacheArray);
  491. }
  492. }
  493. // 查找缓存
  494. private findCache(key: string): Array<VideoItem> | undefined {
  495. return this.cache.get(key);
  496. }
  497. // 查找字符串缓存
  498. private findStringCache(key: string): string | undefined {
  499. return this.stringCache.get(key);
  500. }
  501. // 添加缓存
  502. private addCache(key: string, value: Array<VideoItem>) {
  503. this.cache.set(key, value);
  504. }
  505. // 添加字符串缓存
  506. private addStringCache(key: string, value: string) {
  507. this.stringCache.set(key, value);
  508. }
  509. // 删除缓存
  510. private deleteCache(key: string) {
  511. this.cache.delete(key);
  512. this.saveCacheToStorage()
  513. }
  514. // 删除字符串缓存
  515. private deleteStringCache(key: string) {
  516. this.stringCache.delete(key);
  517. }
  518. // 多选机制
  519. @State selectedFiles: Array<VideoItem> = [];
  520. @State isMultiSelect: boolean = false;
  521. @State isAllSelected: boolean = false;
  522. @State appName: string = ''
  523. @State isHasDir: boolean = false
  524. @State packName: string = ''
  525. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  526. doSwipBack() {
  527. if(this.isSearchMode){
  528. console.info('onecold doSwipBack = ' +this.isSearchMode)
  529. this.isSearchMode = false
  530. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  531. this.searchText = ''
  532. this.getSortedFiles(this.currentPath)
  533. return
  534. }
  535. this.onSearchInput('')
  536. return
  537. }
  538. this.isZero = false
  539. if (this.modeType !== 0 && this.isCanBack) {
  540. this.onModeChange()
  541. this.isCanBack = false
  542. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  543. setTimeout(() => {
  544. if (this.modeType == 2) {
  545. if (this.isGridMusic||this.twoFingerType==4) {
  546. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  547. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  548. if(this.twoFingerType==4){
  549. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  550. }else{
  551. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  552. }
  553. } else {
  554. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  555. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  556. }
  557. } else if (this.modeType == 3) {
  558. if (this.isGridMusic||this.twoFingerType==4) {
  559. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  560. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 0
  561. if(this.twoFingerType==4){
  562. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  563. }else{
  564. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  565. }
  566. } else {
  567. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  568. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  569. }
  570. }
  571. }, 200)
  572. return
  573. }
  574. if (this.isHistory || this.isFavMusic) {
  575. this.isHistory = false
  576. this.getSortedFiles(this.currentPath)
  577. return
  578. }
  579. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  580. animateTo({ duration: 555 }, () => {
  581. // 动画闭包内控制Image组件的出现和消失
  582. this.isShowDrawer = !this.isShowDrawer
  583. this.offsetX = 0
  584. })
  585. return
  586. }
  587. //返回上一级歌单的滚动位置
  588. setTimeout(() => {
  589. if (this.modeType == 0) {
  590. if (this.isGridMusic||this.twoFingerType==4) {
  591. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  592. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
  593. if(this.twoFingerType==4){
  594. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  595. }else{
  596. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  597. }
  598. } else {
  599. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  600. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  601. }
  602. }
  603. }, 300)
  604. this.currentPath = Utility.getParentDirectory(this.currentPath)
  605. Logger.info('this.currentPath2 = ' + this.currentPath)
  606. this.getSortedFiles(this.currentPath)
  607. }
  608. // 组件生命周期
  609. aboutToAppear() {
  610. console.info('onecold aboutToAppear sdkApiVersion = '+deviceInfo.sdkApiVersion)
  611. if(ArrayUtil.isNotEmpty(this.videoLocalList)&&this.modeType==0){
  612. this.updateListData(this.videoLocalList)
  613. }
  614. // 初始化 PlaylistTable
  615. this.playlistTable = new PlaylistTable(getContext(this))
  616. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  617. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  618. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  619. this.tipPopup = !this.tipPopup
  620. PreferencesUtil.putSync('isFirstTiped',false)
  621. }
  622. this.initSetting()
  623. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  624. Utility.getAppName(getContext(this)).then((appName: string) => {
  625. this.appName = appName
  626. })
  627. this.packName = AppUtil.getBundleName()
  628. this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
  629. this.loadCacheFromStorage(); // 加载文件夹缓存
  630. // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
  631. this.initLoadCache()
  632. this.mkDownLoadDir()
  633. let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
  634. // 监听广播事件(打开其他应用处理)
  635. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  636. this.saveVideoDatas([eventData.data?.message], true)
  637. });
  638. //侧滑广播接收时间
  639. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
  640. // 监听广播事件(打开其他应用处理)
  641. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  642. animateTo({ duration: 555 }, () => {
  643. this.doSwipBack()
  644. })
  645. });
  646. //ScanFilePage广播接收时间
  647. let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
  648. // 监听ScanFilePage广播事件(更新数据库)
  649. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  650. this.doUpdateData()
  651. });
  652. // 监听歌单播放请求事件
  653. let eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY }
  654. emitter.on(eventPlaylistPlay, async (eventData: emitter.EventData) => {
  655. const data = eventData.data as Record<string, Object>
  656. if (!data) {
  657. Logger.error('heanup eventPlaylistPlay: eventData.data is undefined or null')
  658. return
  659. }
  660. // 检查歌单播放数据结构
  661. if (data.playlistId && data.songFilePaths && data.startIndex !== undefined) {
  662. const playlistData: PlaylistEventData = {
  663. playlistId: data.playlistId as string,
  664. playlistName: data.playlistName as string,
  665. songCount: data.songCount as number,
  666. startIndex: data.startIndex as number,
  667. songFilePaths: data.songFilePaths as string[]
  668. }
  669. await this.handlePlaylistPlayRequest(
  670. playlistData.playlistId,
  671. playlistData.playlistName,
  672. playlistData.songFilePaths,
  673. playlistData.startIndex
  674. )
  675. return
  676. }
  677. Logger.error('heanup eventPlaylistPlay: 接收到无效的数据结构')
  678. });
  679. let eventRefreshSort: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_REFRESH_SORT }
  680. // 监听广播事件(通用设置配置更新)
  681. emitter.on(eventRefreshSort, (eventData: emitter.EventData) => {
  682. if(this.modeType ==4){
  683. this.doSongListTask()//获取歌单信息
  684. }
  685. });
  686. let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
  687. // 监听广播事件(通用设置配置更新)
  688. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  689. this.doChangeSetting()
  690. });
  691. let event: Callback<InterruptEvent> = (event) => {
  692. // LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  693. console.info(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  694. this.savePlaybackPosition()
  695. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  696. this.pause();
  697. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  698. console.info(`onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  699. console.info('onecold startPlayOrResumePlay 514')
  700. this.startPlayOrResumePlay();
  701. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  702. this.stop();
  703. }
  704. }
  705. this.mIjkMediaPlayer.on('audioInterrupt', event);
  706. // 音频设备断连回调处理
  707. // let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  708. // LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  709. // if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  710. // this.pause();
  711. // }
  712. // }
  713. // this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  714. this.makeWorker()
  715. //折叠屏的屏幕显示模式变化
  716. display.on('foldDisplayModeChange', (data) => {
  717. this.doChangeBarHeight()
  718. });
  719. display.on('foldStatusChange', (data) => {
  720. Logger.info('onecold foldStatusChange ')
  721. });
  722. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  723. // 读取 themeMode 并同步 currentColorMode
  724. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  725. this.applyThemeMode(this.themeMode)
  726. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  727. AppStorage.setOrCreate('themeColor', themeColor);
  728. this.themeColor = themeColor;
  729. this.doChangeSetting()
  730. this.windowClass.on('windowSizeChange', (size) => {
  731. LogUtil.info('onecold windowSizeChange')
  732. this.doChangeBarHeight()
  733. let viewWidth = px2vp(size.width);
  734. let viewHeight = px2vp(size.height);
  735. if(this.isPhoneLan()){
  736. this.is_auto_hide_progress = false
  737. if(this.isHiCar()){
  738. return
  739. }
  740. setTimeout(() => {
  741. this.is_auto_hide_progress = true
  742. }, 6000)
  743. }else{
  744. this.startAutoHide()
  745. }
  746. });
  747. this.eventHub.on('onStateChange', (fg: boolean) => {
  748. if (fg && this.curState === 'STARTED') {
  749. this.stopPip();
  750. }
  751. });
  752. }
  753. //载入媒体库,艺术家,专辑等缓存
  754. initLoadCache(){
  755. this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
  756. this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
  757. this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
  758. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  759. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  760. if(ArrayUtil.isNotEmpty(cachedList)){
  761. this.mediaKuList = cachedList
  762. if(this.modeType==1){
  763. this.updateListData(this.mediaKuList)
  764. }
  765. }
  766. let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
  767. let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
  768. if(ArrayUtil.isNotEmpty(artistCachedList)){
  769. this.artistList = artistCachedList
  770. let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
  771. const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
  772. this.artistMap = new Map(parsedArray);
  773. // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
  774. if(this.modeType==2){
  775. this.updateListData(this.artistList)
  776. }
  777. }
  778. let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
  779. let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
  780. if(ArrayUtil.isNotEmpty(albumCachedList)){
  781. this.albumList = albumCachedList
  782. let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
  783. const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
  784. this.albumMap = new Map(parsedArray);
  785. if(this.modeType==3){
  786. this.updateListData(this.albumList)
  787. }
  788. }
  789. }
  790. startAutoHide() {
  791. if(this.isHiCar()){
  792. return
  793. }
  794. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  795. console.info('onecold startAutoHide')
  796. this.is_auto_hide_progress = false
  797. setTimeout(() => {
  798. this.is_auto_hide_progress = true
  799. }, 6000)
  800. }
  801. }
  802. applyThemeMode(mode: number) {
  803. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  804. if (mode === 1) {
  805. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  806. } else if (mode === 2) {
  807. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  808. }
  809. AppStorage.setOrCreate('currentColorMode', colorMode)
  810. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  811. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  812. AppStorage.setOrCreate('themeMode', mode)
  813. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  814. // 只有强制浅色/深色时才主动设置
  815. const context = getContext(this) as common.UIAbilityContext
  816. context.getApplicationContext().setColorMode(colorMode)
  817. }
  818. initSetting() {
  819. this.isShowPrecious = PreferencesUtil.getBooleanSync('isShowPrecious', false)
  820. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  821. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  822. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  823. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, false)
  824. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  825. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  826. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  827. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  828. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  829. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  830. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  831. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, false)
  832. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  833. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 2)
  834. this.isCoverTop = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP, true)
  835. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  836. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  837. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  838. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  839. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  840. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  841. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  842. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  843. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  844. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  845. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  846. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  847. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  848. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  849. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  850. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  851. this.isCopyFileToDownLoad = PreferencesUtil.getBooleanSync(SettingPage.IS_COPYFILE_TO_DOWNLOAD, false)
  852. if(this.volumeSmall){
  853. this.volume = 0.5
  854. }else{
  855. this.volume = 1
  856. }
  857. //如果是hicar连接状态,这些都是false
  858. if(this.isHiCar()){
  859. this.isShowTitleBar = false//不显示导航栏
  860. this.columns=4
  861. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  862. {
  863. this.isShowHeader = false//二级菜单不显示头部
  864. this.isGridMusic= false//用list不用网格
  865. this.isCoverTopBig = false
  866. }
  867. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  868. }
  869. if (this.isSavePlayMode) {
  870. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  871. }
  872. }
  873. doChangeSetting() {
  874. this.initSetting()
  875. this.deleteCache(this.currentPath)
  876. if (this.modeType === 0) {
  877. this.getSortedFiles(this.currentPath)
  878. }
  879. }
  880. doChangeBarHeight() {
  881. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  882. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  883. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  884. this.setBarHeightNormal()
  885. }
  886. }
  887. onPageShow() {
  888. this.knockController?.immersiveListening();
  889. app.setImageCacheCount(100);
  890. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  891. app.setImageRawDataCacheSize(104857600);
  892. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  893. }
  894. //开启线程查看各个数据库
  895. makeWorker() {
  896. setTimeout(() => {
  897. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  898. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  899. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  900. // workerInstance.postMessage({
  901. // code: 1,
  902. // data1: this.context,
  903. // data2: this.rootPath,
  904. // data3: this.lockPath,
  905. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  906. // data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  907. // });
  908. PreferencesUtil.putSync('isFirstApp', false)
  909. } else {
  910. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  911. workerInstance.postMessage({ code: 3, data: this.context });
  912. workerInstance.postMessage({ code: 4, data: this.context });
  913. this.getHistoryList(false)
  914. }
  915. }, 1000)
  916. workerInstance.onmessage = (e: MessageEvents): void => {
  917. switch (e.data.code) {
  918. case 101: //第一次扫描文件夹入库
  919. ToastUtil.showToast('刷新同步数据库成功!')
  920. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  921. this.doUpdateData()
  922. break;
  923. case 102: //查询媒体库列表
  924. this.isRefreshing = false
  925. this.mediaKuList = e.data.data
  926. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  927. Utility.doSortListAscending(this.mediaKuList)
  928. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  929. if (this.modeType === 1) {
  930. this.updateListData(this.mediaKuList)
  931. }
  932. PreferencesUtil.putSync('mediaKuCount', this.mediaKuList.length)
  933. // 处理媒体库前100条记录,列表长度并存储到PreferencesUtil
  934. if (ArrayUtil.isNotEmpty(this.mediaKuList)&&this.mediaKuList.length > 100) {
  935. // 只保存前100条记录到缓存中
  936. let truncatedList = this.mediaKuList.slice(0, 100);
  937. PreferencesUtil.putSync('mediaKuList', JSON.stringify(truncatedList));
  938. } else {
  939. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  940. }
  941. break;
  942. case 103: //收到查询艺术家列表
  943. this.isRefreshing = false
  944. this.artistMap = e.data.data1;
  945. this.artistList = e.data.data2;
  946. PreferencesUtil.putSync('artistCount', this.artistList.length)
  947. // 处理艺术家前100条记录,列表长度并存储到PreferencesUtil
  948. if (ArrayUtil.isNotEmpty(this.artistList)&&this.artistList.length > 100) {
  949. // 只保存前100条记录到缓存中
  950. let truncatedList = this.artistList.slice(0, 100);
  951. PreferencesUtil.putSync('artistList', JSON.stringify(truncatedList));
  952. } else {
  953. PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
  954. }
  955. // 处理并缓存前60条艺术家数据
  956. const sortedEntries = Array.from(this.artistMap.entries())
  957. .sort((a, b) => b[1].length - a[1].length)
  958. .slice(0, 60);
  959. PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
  960. break;
  961. case 104: //收到查询专辑列表
  962. this.isRefreshing = false
  963. this.albumMap = e.data.data1;
  964. this.albumList = e.data.data2
  965. //查询完毕在启动是否自动播放
  966. if (this.isStartAutoPlay&&this.isCanAuto) {
  967. this.isCanAuto = false
  968. console.info('onecold startPlayOrResumePlay 757')
  969. this.startPlayOrResumePlay()
  970. }
  971. PreferencesUtil.putSync('albumCount', this.albumList.length)
  972. // 处理专辑前100条记录,列表长度并存储到PreferencesUtil
  973. if (ArrayUtil.isNotEmpty(this.albumList)&&this.albumList.length > 100) {
  974. // 只保存前100条记录到缓存中
  975. let truncatedList = this.albumList.slice(0, 100);
  976. PreferencesUtil.putSync('albumList', JSON.stringify(truncatedList));
  977. } else {
  978. PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
  979. }
  980. const mapArrayAlbum = Array.from(this.albumMap.entries())
  981. .sort((a, b) => b[1].length - a[1].length)
  982. .slice(0, 60);
  983. PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
  984. break;
  985. }
  986. };
  987. // 在调用terminate后,执行onexit
  988. workerInstance.onexit = (code) => {
  989. console.log("main thread terminate");
  990. }
  991. //若Worker处于已销毁或正在销毁等非运行状态时,调用其功能接口,会抛出相应的错误。
  992. // 使用Worker模块时,需要在主线程中注册onerror接口,否则当worker线程出现异常时会发生jscrash问题。
  993. workerInstance.onerror = (err: ErrorEvent) => {
  994. console.log("onerror" + err.message);
  995. }
  996. // let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
  997. //碰一碰分享的监听
  998. this.knockController = KnockController.getInstance(this.context);
  999. this.knockController?.immersiveListening();
  1000. }
  1001. onPageHide(): void {
  1002. this.knockController?.immersiveDisableListening();
  1003. }
  1004. @State isFirstStartPlay: boolean = false
  1005. //获取download_path
  1006. async mkDownLoadDir() {
  1007. const documentViewPicker = new picker.DocumentViewPicker()
  1008. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  1009. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  1010. PreferencesUtil.putSync('download_path', this.rootPath+'/')
  1011. this.currentPath = this.rootPath
  1012. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  1013. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  1014. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  1015. Logger.info('onecold rootPath = ' + this.rootPath)
  1016. Logger.info('onecold lockPath = ' + this.lockPath)
  1017. if (!FileUtil.accessSync(this.lockPath)) {
  1018. FileUtil.mkdirSync(this.lockPath)
  1019. }
  1020. if (!FileUtil.accessSync(this.favPath)) {
  1021. FileUtil.mkdirSync(this.favPath)
  1022. }
  1023. if (!FileUtil.accessSync(this.historyPath)) {
  1024. FileUtil.mkdirSync(this.historyPath)
  1025. }
  1026. this.getSortedFiles(this.rootPath).then(async () => {
  1027. this.isFavMusic = false
  1028. //穿山甲
  1029. // this.loadBannerAd(CSJUtil.getBannerID())
  1030. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  1031. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  1032. if (ArrayUtil.isEmpty(this.songList)) {
  1033. this.songList = this.getCurFileList()
  1034. } else {
  1035. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  1036. }
  1037. if (ArrayUtil.isNotEmpty(this.songList)) {
  1038. this.isFirstStartPlay = true
  1039. this.sonDataSource.pushArrayData(this.songList)
  1040. if (this.currentSong === undefined) {
  1041. this.isFirstStartPlay = false
  1042. this.currentSong = this.songList[0]
  1043. }
  1044. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  1045. this.videoUrl = await setVideoUrlForSong(this.currentSong);
  1046. Logger.info(TAG, `WebDAV URL同步构建完成: ${this.videoUrl}`);
  1047. this.name = this.currentSong.name
  1048. this.cover = this.currentSong.pixelMapPath
  1049. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  1050. } else {
  1051. this.name = '空空如也'
  1052. }
  1053. })
  1054. this.getFavList(false)
  1055. }
  1056. getFavList(isFavRefresh: boolean) {
  1057. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  1058. this.favList = result
  1059. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  1060. this.videoLocalList = this.favList
  1061. this.updateListData(this.videoLocalList)
  1062. }
  1063. })
  1064. }
  1065. getHistoryList(isRefresh: boolean) {
  1066. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  1067. this.historyList = result
  1068. // for (let i = 0; i < this.historyList.length; i++) {
  1069. //
  1070. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  1071. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  1072. // }
  1073. if (isRefresh) {
  1074. this.videoLocalList = this.historyList
  1075. this.updateListData(this.videoLocalList, true)
  1076. }
  1077. })
  1078. }
  1079. // 组件消失生命周期
  1080. aboutToDisappear() {
  1081. console.info('LifeCycleComponent aboutToDisappear');
  1082. this.knockController?.immersiveDisableListening();
  1083. this.curIndex = 0
  1084. emitter.off(EventConstants.EVENT_AUDIO_OPEN);
  1085. emitter.off(EventConstants.EVENT_SCAN_UPDATE);
  1086. emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
  1087. emitter.off(EventConstants.EVENT_SETTING_UPDATE);
  1088. this.mDestroyPage = true;
  1089. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  1090. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  1091. this.stop();
  1092. }
  1093. this.mIjkMediaPlayer.off('audioInterrupt');
  1094. if (workerInstance) {
  1095. workerInstance.terminate();
  1096. }
  1097. this.stopPip();
  1098. this.destroyPipController()
  1099. }
  1100. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean,openItem?:VideoItem) {
  1101. this.isFavMusic = false
  1102. console.info('onecold getSortedFiles 1 curPath '+curPath)
  1103. if (isWorkerPost) {
  1104. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1105. }
  1106. if (this.modeType !== 0) {
  1107. return
  1108. }
  1109. console.info('onecold getSortedFiles 2')
  1110. this.isCanBack = false
  1111. this.currentPath = curPath
  1112. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  1113. this.titleName = getFileDirName(this.currentPath,this.rootPath)
  1114. if (curPath === this.rootPath) {
  1115. this.rightTopImage = $r('sys.symbol.sort')
  1116. } else {
  1117. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  1118. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  1119. this.rightTopImage = $r('sys.symbol.chevron_left')
  1120. }
  1121. }
  1122. // Get the current file list and calculate its hash
  1123. this.fileList = FileUtil.listFileSync(curPath);
  1124. const currentHash = simpleHash(this.fileList);
  1125. // Check cache
  1126. const cachedValue = this.findCache(curPath);
  1127. Logger.info('onecold cachedValue = ' + cachedValue)
  1128. const cachedHash = this.findStringCache(curPath + '_hash');
  1129. const cachedDirList = this.findCache(curPath + "_dirList");
  1130. if (cachedValue !== undefined&&!this.isRefreshing) {
  1131. // this.videoLocalList = cachedValue;
  1132. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  1133. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  1134. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  1135. }
  1136. this.isRefreshing = false
  1137. this.updateListData(cachedValue)
  1138. }
  1139. if (cachedDirList !== undefined) {
  1140. this.dirList = cachedDirList
  1141. }
  1142. //通过当前hash值和缓存hash判断list有没有变化
  1143. if (cachedValue && cachedHash === currentHash) {
  1144. return;
  1145. }
  1146. this.fileList = FileUtil.listFileSync(curPath)
  1147. let directories: Array<VideoItem> = [];
  1148. let files: Array<VideoItem> = [];
  1149. for (let i = 0; i < this.fileList.length; i++) {
  1150. console.info(`The name of file: ${this.fileList[i]}`);
  1151. let path = curPath + '/' + this.fileList[i]
  1152. if (FileUtil.isDirectory(path)) {
  1153. let item: VideoItem =
  1154. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  1155. '')
  1156. if (this.isShowDir(item.name)) {
  1157. directories.push(item);
  1158. }
  1159. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1160. // Utility.doSortListAscending(directories)
  1161. } else {
  1162. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  1163. let item: VideoItem =
  1164. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  1165. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  1166. files.push(item);
  1167. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1168. // this.doSortListAscending(files)
  1169. }
  1170. }
  1171. }
  1172. }
  1173. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  1174. if (this.currentPath !== this.lockPath) {
  1175. files = result;
  1176. }
  1177. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1178. Utility.doSortListAscending(files)
  1179. if (this.currentPath === this.rootPath) {
  1180. this.dirList = directories
  1181. this.addCache(curPath + "_dirList", this.dirList);
  1182. }
  1183. //插入广告先注释掉
  1184. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  1185. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  1186. // directories.push(adItem)
  1187. // }
  1188. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  1189. this.videoLocalList = directories.concat(files);
  1190. this.updateListData(this.videoLocalList)
  1191. if (ArrayUtil.isNotEmpty(files)) {
  1192. if (this.currentPath != this.rootPath) {
  1193. if (files) {
  1194. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  1195. }
  1196. }
  1197. // 缓存结果
  1198. this.addCache(curPath, this.videoLocalList);
  1199. await this.saveCacheToStorage(); // 保存缓存至本地存储
  1200. this.addStringCache(curPath + '_hash', currentHash);
  1201. }
  1202. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  1203. // for (let i = 0; i < this.videoLocalList.length; i++) {
  1204. //
  1205. // console.info(`onecold gengxin 1: ${this.videoLocalList[i].pixelMapPath}`);
  1206. //
  1207. // }
  1208. // this.setButtonStatus()
  1209. this.openMusic(isOpen, destPath,openItem)
  1210. this.isRefreshing = false
  1211. });
  1212. }
  1213. //第三方app打开天天静听导入音乐后播放
  1214. openMusic(isOpen?: boolean, destPath?: string,openItem?:VideoItem){
  1215. if (isOpen&&destPath) {
  1216. if (destPath === undefined) {
  1217. // 处理 destPath 为 undefined 的情况
  1218. return
  1219. }
  1220. if (destPath.endsWith('.lrc')) {
  1221. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  1222. if (StrUtil.isNotEmpty(this.videoUrl)) {
  1223. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  1224. this.initLyric(lyricPath);
  1225. }
  1226. return
  1227. }
  1228. if(openItem){
  1229. this.doPlay(openItem,0,false,true)
  1230. this.isShowPlay = true
  1231. }
  1232. }
  1233. }
  1234. //扫描文件夹入库
  1235. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  1236. const files = FileUtil.listFileSync(curPath);
  1237. let mediaItems: VideoItem[] = [];
  1238. Logger.info('onecold scanDirectory start ')
  1239. for (const file of files) {
  1240. const fPath = `${curPath}/${file}`;
  1241. if (fPath === this.lockPath) {
  1242. Logger.info(`Skipping locked path: ${fPath}`);
  1243. continue;
  1244. }
  1245. if (FileUtil.isDirectory(fPath)) {
  1246. // Recursively scan subdirectories
  1247. const subDirItems = await this.scanDirectory(fPath);
  1248. mediaItems = mediaItems.concat(subDirItems);
  1249. } else {
  1250. Logger.info('onecold scanDirectory filePath = ' + fPath)
  1251. // Process media files
  1252. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  1253. let mediaItem: VideoItem =
  1254. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1255. mediaItems.push(mediaItem);
  1256. this.table.insert(mediaItem, (id: number) => {
  1257. });
  1258. }
  1259. }
  1260. }
  1261. return mediaItems;
  1262. }
  1263. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  1264. animateTo({ duration: 666 }, () => {
  1265. this.opacityItem = 0.5;
  1266. });
  1267. setTimeout(() => {
  1268. this.videoLocalList = mList;
  1269. if (!noSort) {
  1270. if (this.modeType === 0 || this.modeType === 1) {
  1271. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1272. this.doSortType(this.sortType)
  1273. }
  1274. }
  1275. this.dataSource.pushArrayData(this.videoLocalList)
  1276. animateTo({ duration: 666 }, () => {
  1277. this.opacityItem = 1;
  1278. });
  1279. this.setButtonStatus()
  1280. }, 200);
  1281. }
  1282. getCurFileList(): Array<VideoItem> {
  1283. if(this.isSearchMode){
  1284. return this.filteredList
  1285. }
  1286. let files: Array<VideoItem> = [];
  1287. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1288. for (let i = 0; i < this.videoLocalList.length; i++) {
  1289. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  1290. files.push(this.videoLocalList[i]);
  1291. }
  1292. }
  1293. }
  1294. return files
  1295. }
  1296. setButtonStatus() {
  1297. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1298. this.isZero = false
  1299. } else {
  1300. this.isZero = true
  1301. }
  1302. if (this.currentPath !== this.rootPath &&
  1303. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  1304. this.isHasDir = true //不为空,说明有子文件夹
  1305. } else {
  1306. this.isHasDir = false
  1307. }
  1308. }
  1309. @Builder
  1310. SortMenuBuilder() {
  1311. Menu() {
  1312. MenuItem({
  1313. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  1314. content: "按艺术家升序"
  1315. })
  1316. .onClick(async () => {
  1317. this.doSortType(0)
  1318. PreferencesUtil.put(SettingPage.SORT_TYPE, 0)
  1319. this.updateListData(this.videoLocalList, true)
  1320. })
  1321. MenuItem({
  1322. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  1323. content: "按艺术家降序"
  1324. })
  1325. .onClick(async () => {
  1326. this.doSortType(1)
  1327. PreferencesUtil.put(SettingPage.SORT_TYPE, 1)
  1328. this.updateListData(this.videoLocalList, true)
  1329. })
  1330. MenuItem({
  1331. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat_size_square')),
  1332. content: "按专辑升序"
  1333. })
  1334. .onClick(async () => {
  1335. this.doSortType(2)
  1336. PreferencesUtil.put(SettingPage.SORT_TYPE, 2)
  1337. this.updateListData(this.videoLocalList, true)
  1338. })
  1339. MenuItem({
  1340. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.character_arrow_clockwise')),
  1341. content: "按专辑降序"
  1342. })
  1343. .onClick(async () => {
  1344. this.doSortType(3)
  1345. PreferencesUtil.put(SettingPage.SORT_TYPE, 3)
  1346. this.updateListData(this.videoLocalList, true)
  1347. })
  1348. MenuItem({
  1349. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  1350. content: $r('app.string.sort_by_name')
  1351. })
  1352. .onClick(async () => {
  1353. this.doSortType(4)
  1354. PreferencesUtil.put(SettingPage.SORT_TYPE, 4)
  1355. this.updateListData(this.videoLocalList, true)
  1356. })
  1357. MenuItem({
  1358. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  1359. content: '按名称降序'
  1360. })
  1361. .onClick(async () => {
  1362. this.doSortType(5)
  1363. PreferencesUtil.put(SettingPage.SORT_TYPE, 5)
  1364. this.updateListData(this.videoLocalList, true)
  1365. })
  1366. MenuItem({
  1367. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  1368. content: $r('app.string.sort_by_time')
  1369. })
  1370. .onClick(async () => {
  1371. this.doSortType(6)
  1372. PreferencesUtil.put(SettingPage.SORT_TYPE, 6)
  1373. this.updateListData(this.videoLocalList, true)
  1374. })
  1375. MenuItem({
  1376. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  1377. content: '按添加时间降序'
  1378. })
  1379. .onClick(async () => {
  1380. this.doSortType(7)
  1381. PreferencesUtil.put(SettingPage.SORT_TYPE, 7)
  1382. this.updateListData(this.videoLocalList, true)
  1383. })
  1384. }.attributeModifier(new MenuModifier())
  1385. }
  1386. @Builder
  1387. SortMenuForArtistAblumBuilder() {
  1388. Menu() {
  1389. MenuItem({
  1390. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  1391. content: $r('app.string.sort_by_name')
  1392. })
  1393. .onClick(async () => {
  1394. this.doSortType(4)
  1395. // PreferencesUtil.put(SettingPage.SORT_TYPE, 2)
  1396. this.updateListData(this.videoLocalList, true)
  1397. })
  1398. MenuItem({
  1399. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  1400. content: '按名称降序'
  1401. })
  1402. .onClick(async () => {
  1403. this.doSortType(5)
  1404. this.updateListData(this.videoLocalList, true)
  1405. })
  1406. MenuItem({
  1407. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  1408. content: '按数量升序'
  1409. })
  1410. .onClick(async () => {
  1411. this.doSortType(8)
  1412. this.updateListData(this.videoLocalList, true)
  1413. })
  1414. MenuItem({
  1415. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  1416. content: '按数量降序'
  1417. })
  1418. .onClick(async () => {
  1419. this.doSortType(9)
  1420. this.updateListData(this.videoLocalList, true)
  1421. })
  1422. }.attributeModifier(new MenuModifier())
  1423. }
  1424. doSortType(index: number) {
  1425. switch (index) {
  1426. case 0:
  1427. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1428. // 类型排序优先级
  1429. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1430. if (typeOrder !== 0) {
  1431. return typeOrder;
  1432. }
  1433. // 处理艺术家可能为undefined的字符串比较
  1434. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1435. const artistB = b.artist?.trim() || '';
  1436. return artistA.localeCompare(artistB);
  1437. });
  1438. break;
  1439. case 1:
  1440. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1441. // 类型排序优先级
  1442. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1443. if (typeOrder !== 0) {
  1444. return typeOrder;
  1445. }
  1446. // 处理艺术家可能为undefined的字符串比较
  1447. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1448. const artistB = b.artist?.trim() || '';
  1449. return artistB.localeCompare(artistA);
  1450. });
  1451. break;
  1452. case 2:
  1453. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1454. // 类型排序优先级
  1455. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1456. if (typeOrder !== 0) {
  1457. return typeOrder;
  1458. }
  1459. // 处理专辑可能为undefined的字符串比较
  1460. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1461. const albumB = b.album?.trim() || '';
  1462. return albumA.localeCompare(albumB);
  1463. });
  1464. break;
  1465. case 3:
  1466. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1467. // 类型排序优先级
  1468. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1469. if (typeOrder !== 0) {
  1470. return typeOrder;
  1471. }
  1472. // 处理专辑可能为undefined的字符串比较
  1473. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1474. const albumB = b.album?.trim() || '';
  1475. return albumB.localeCompare(albumA);
  1476. });
  1477. break;
  1478. case 4:
  1479. Utility.doSortListAscending(this.videoLocalList,this.isShowFileName)
  1480. break;
  1481. case 5:
  1482. Utility.doSortListDescending(this.videoLocalList,this.isShowFileName)
  1483. break;
  1484. case 6:
  1485. this.videoLocalList.sort((a, b) => {
  1486. // First, sort by type
  1487. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1488. if (typeOrder !== 0) {
  1489. return typeOrder;
  1490. }
  1491. // If types are the same, sort by cTime in ascending order
  1492. return a.cTime.localeCompare(b.cTime);
  1493. });
  1494. break;
  1495. case 7:
  1496. this.videoLocalList.sort((a, b) => {
  1497. // First, sort by type
  1498. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1499. if (typeOrder !== 0) {
  1500. return typeOrder;
  1501. }
  1502. // If types are the same, sort by cTime in descending order
  1503. return b.cTime.localeCompare(a.cTime);
  1504. });
  1505. break;
  1506. case 8:
  1507. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  1508. // 1. Sort by type first
  1509. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  1510. if (typeOrder !== 0) {
  1511. return typeOrder;
  1512. }
  1513. // 2. Then sort by artist count (numeric comparison)
  1514. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  1515. if(this.modeType === 2){
  1516. sortMap = this.artistMap
  1517. }else{
  1518. sortMap = this.albumMap
  1519. }
  1520. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  1521. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  1522. return aArtistCount - bArtistCount;
  1523. });
  1524. break;
  1525. case 9:
  1526. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  1527. // 1. Sort by type first
  1528. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  1529. if (typeOrder !== 0) {
  1530. return typeOrder;
  1531. }
  1532. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  1533. if(this.modeType === 2){
  1534. sortMap = this.artistMap
  1535. }else{
  1536. sortMap = this.albumMap
  1537. }
  1538. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  1539. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  1540. return bArtistCount - aArtistCount;
  1541. });
  1542. break;
  1543. }
  1544. }
  1545. showSheelDialog() {
  1546. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  1547. // this.showTips()
  1548. // return
  1549. // }
  1550. this.showAddDialog()
  1551. }
  1552. showAddDialog() {
  1553. if (this.modeType === 2 || this.modeType === 3) {
  1554. return
  1555. }
  1556. DialogHelper.showActionSheetDialog({
  1557. title: "请选择添加方式(建议歌词文件一起导入)",
  1558. sheets: [
  1559. { value: "新建文件夹", fontColor: $r('app.color.text_color') },
  1560. { value: "手动导入", fontColor: $r('app.color.text_color') },
  1561. { value: "自动导入", fontColor: $r('app.color.text_color') },
  1562. { value: "全选导入", fontColor: $r('app.color.text_color') },
  1563. ],
  1564. maskColor: Color.Transparent,
  1565. backgroundColor: $r('app.color.bg_card'),
  1566. transition: AnimationHelper.transitionInDown(555),
  1567. onAction: (index) => {
  1568. switch (index) {
  1569. case 0:
  1570. if (this.modeType === 0) {
  1571. this.showMkDialog()
  1572. } else {
  1573. ToastUtil.showToast('请切换到首页才能新建文件夹!')
  1574. }
  1575. break;
  1576. case 1:
  1577. this.callFilePickerSelectFile()
  1578. break;
  1579. case 2:
  1580. this.showTips()
  1581. break;
  1582. case 3:
  1583. this.goSelectMusic()
  1584. break;
  1585. }
  1586. }
  1587. })
  1588. }
  1589. //拉起音频
  1590. goSelectMusic() {
  1591. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  1592. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  1593. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  1594. ) {
  1595. ToastUtil.showToast('暂时不支持该设备')
  1596. return
  1597. }
  1598. try {
  1599. let documentSelectOptions = new picker.DocumentSelectOptions();
  1600. documentSelectOptions.authMode = true
  1601. documentSelectOptions.multiAuthMode = true
  1602. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  1603. let documentPicker = new picker.DocumentViewPicker(this.context);
  1604. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  1605. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  1606. this.saveVideoDatas(documentSelectResult)
  1607. }
  1608. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  1609. JSON.stringify(documentSelectResult));
  1610. }).catch((err: BusinessError) => {
  1611. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  1612. });
  1613. } catch (error) {
  1614. let err: BusinessError = error as BusinessError;
  1615. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1616. }
  1617. }
  1618. async showTips() {
  1619. try {
  1620. this.getUIContext().getPromptAction().showDialog({
  1621. title: '导入指南',
  1622. message:'用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  1623. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  1624. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  1625. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  1626. buttons: [
  1627. {
  1628. text: '知道了',
  1629. color: '#000000'
  1630. },
  1631. ]
  1632. }, (err, data) => {
  1633. if (err) {
  1634. console.error('showDialog err: ' + err);
  1635. return;
  1636. }
  1637. console.info('showDialog success callback, click button: ' + data.index);
  1638. });
  1639. } catch (error) {
  1640. let message = (error as BusinessError).message;
  1641. let code = (error as BusinessError).code;
  1642. console.error(`showDialog args error code is ${code}, message is ${message}`);
  1643. };
  1644. // DialogHelper.showTipsDialog({
  1645. // title: '使用提示:自动导入教程',
  1646. //
  1647. // content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  1648. // + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  1649. // '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  1650. // '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  1651. // onAction: (action) => {
  1652. // if (action == DialogAction.TWO) {
  1653. // PreferencesUtil.putSync('isFirstMusic', false)
  1654. // router.pushUrl({
  1655. // url: 'pages/ScanFilePage'
  1656. // });
  1657. // }
  1658. // }
  1659. // })
  1660. }
  1661. showMkDialog() {
  1662. DialogHelper.showTextInputDialog({
  1663. title: '新建歌单',
  1664. maskColor: Color.Transparent,
  1665. text: '',
  1666. transition: AnimationHelper.transitionInDown(666),
  1667. onChange: (text) => {
  1668. console.error("onChange: " + text);
  1669. },
  1670. onAction: (action, dialogId, content) => {
  1671. // ToastUtil.showToast('content = ' +content)
  1672. if (action == DialogAction.TWO) {
  1673. const newName = content
  1674. const newPath = this.currentPath + '/' + newName
  1675. FileUtil.mkdir(newPath, true).then(() => {
  1676. this.cache.delete(this.currentPath); // 删除目标路径缓存
  1677. this.getSortedFiles(this.currentPath)
  1678. }).catch((error: BusinessError) => {
  1679. console.error(error.message);
  1680. });
  1681. }
  1682. }
  1683. })
  1684. }
  1685. @State progress: number = 0;
  1686. async saveVideoDatas(uris:string[],isOpen?:boolean){
  1687. if (ArrayUtil.isEmpty(uris)) {
  1688. return;
  1689. }
  1690. console.info('onecold this.isCopyFileToDownLoad = ' + this.isCopyFileToDownLoad);
  1691. if(this.isCopyFileToDownLoad||this.currentPath==this.lockPath||isOpen){
  1692. this.saveVideoDatasToDownLoad(uris,isOpen)
  1693. return
  1694. }
  1695. // 初始化进度条
  1696. this.progress = 0;
  1697. DialogHelper.showLoadingProgress({
  1698. progress: this.progress,
  1699. backCancel: false,
  1700. autoCancel: false,
  1701. loadColor: $r('app.color.title_bar_bg'),
  1702. fontColor: $r('app.color.title_bar_bg')
  1703. });
  1704. // 计算处理总数用于进度计算
  1705. const totalItems = uris.length;
  1706. let processedItems = 0;
  1707. for (let i = 0; i < uris.length; i++) {
  1708. let filePath = uris[i];
  1709. try {
  1710. if (this.currentPath !== this.lockPath) { // 判断不是私密音乐,才入库
  1711. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  1712. let mediaItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context,
  1713. filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1714. console.info('onecold saveVideoDatas filePath = ' + filePath)
  1715. if (!filePath.includes(this.rootPath)) {
  1716. console.info('onecold saveVideoDatas mediaItem.parentPath111 = ' + mediaItem.parentPath)
  1717. mediaItem.parentPath = this.currentPath;
  1718. }
  1719. console.info('onecold saveVideoDatas mediaItem.parentPath = ' + mediaItem.parentPath)
  1720. this.table.insert(mediaItem, (id: number) => {
  1721. // 插入完成回调
  1722. });
  1723. }
  1724. }
  1725. // 更新进度
  1726. processedItems++;
  1727. this.progress = Math.floor((processedItems / totalItems) * 100);
  1728. DialogHelper.updateLoading(' 正在处理', this.progress);
  1729. } catch (error) {
  1730. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  1731. // 即使出错也更新进度
  1732. processedItems++;
  1733. this.progress = Math.floor((processedItems / totalItems) * 100);
  1734. DialogHelper.updateLoading(' 正在处理', this.progress);
  1735. }
  1736. }
  1737. // 关闭进度条
  1738. DialogHelper.closeLoading();
  1739. this.isZero = false
  1740. // 删除目标路径缓存
  1741. setTimeout(() => {
  1742. this.cache.delete(this.currentPath);
  1743. this.getSortedFiles(this.currentPath,false,uris[0],isOpen)
  1744. this.setButtonStatus()
  1745. }, 500);
  1746. }
  1747. async saveVideoDatasToDownLoad(uris: string[], isOpen?: boolean) {
  1748. if (ArrayUtil.isEmpty(uris)) {
  1749. return;
  1750. }
  1751. let newUris: string[] = [];
  1752. this.progress = 0
  1753. DialogHelper.showLoadingProgress({
  1754. progress: this.progress,
  1755. backCancel: false,
  1756. autoCancel: false,
  1757. loadColor: this.themeColor,
  1758. fontColor: this.themeColor
  1759. });
  1760. // 计算所有文件的总大小
  1761. let totalSize = 0;
  1762. for (let uri of uris) {
  1763. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  1764. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  1765. await fileIo.close(sourceFile.fd);
  1766. }
  1767. let totalRead = 0;
  1768. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  1769. Logger.info(TAG, 'destPath uri: ' + destPath);
  1770. for (let i = 0; i < uris.length; i++) {
  1771. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  1772. Logger.info(TAG, 'filePath uri: ' + filePath);
  1773. newUris.push(filePath);
  1774. try {
  1775. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  1776. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  1777. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  1778. const buffer = new ArrayBuffer(buffSize);
  1779. let len = await fileIo.read(sourceFile.fd, buffer);
  1780. while (len > 0) {
  1781. await fileIo.write(destFile.fd, buffer.slice(0, len));
  1782. totalRead += len;
  1783. // 计算总进度
  1784. this.progress = Math.floor((totalRead / totalSize) * 100);
  1785. DialogHelper.updateLoading('正在导入', this.progress);
  1786. len = await fileIo.read(sourceFile.fd, buffer);
  1787. }
  1788. await fileIo.close(sourceFile.fd);
  1789. await fileIo.close(destFile.fd);
  1790. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  1791. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  1792. let mediaItem: VideoItem =
  1793. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1794. this.table.insert(mediaItem, (id: number) => {
  1795. // 删除目标路径缓存
  1796. this.cache.delete(this.currentPath);
  1797. this.getSortedFiles(this.currentPath, true, destPath, isOpen,mediaItem)
  1798. });
  1799. }
  1800. }
  1801. } catch (error) {
  1802. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  1803. }
  1804. }
  1805. DialogHelper.closeLoading()
  1806. this.isZero = false
  1807. // setTimeout(() => {
  1808. // // 删除目标路径缓存
  1809. // this.cache.delete(this.currentPath);
  1810. // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
  1811. // }, 500);
  1812. Logger.info(TAG, 'scan select video result:' + newUris)
  1813. }
  1814. //拉起音频
  1815. // goSelectMusic(){
  1816. //
  1817. // try {
  1818. // let audioSelectOptions = new picker.AudioSelectOptions();
  1819. // let audioPicker = new picker.AudioViewPicker(this.context);
  1820. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  1821. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  1822. // this.saveVideoDatas(audioSelectResult)
  1823. // }
  1824. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  1825. // }).catch((err: BusinessError) => {
  1826. //
  1827. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  1828. // });
  1829. // } catch (error) {
  1830. // let err: BusinessError = error as BusinessError;
  1831. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1832. // }
  1833. //
  1834. //
  1835. //
  1836. // }
  1837. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  1838. if (!item) {
  1839. return undefined;
  1840. }
  1841. try {
  1842. let selectUris: Array<string> = [];
  1843. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  1844. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  1845. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  1846. photoSelectOptions.maxSelectNumber = 1;
  1847. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  1848. selectUris = photoSelectResult.photoUris;
  1849. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  1850. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  1851. console.info('file fd: ' + file.fd);
  1852. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  1853. let imagePath = this.context.filesDir + FileUtil.separator + name
  1854. imagePath = fileUri.getUriFromPath(imagePath)
  1855. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  1856. fileIo.copyFileSync(file.fd, file2.fd)
  1857. fileIo.closeSync(file);
  1858. fileIo.closeSync(file2);
  1859. if (item.filePath == this.currentSong?.filePath) {
  1860. this.cover = imagePath
  1861. }
  1862. if (item) {
  1863. item.pixelMapPath = imagePath
  1864. }
  1865. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  1866. if (success) {
  1867. this.doUpdateData()
  1868. console.log("onecold 更新音乐封面成功,数据库已同步");
  1869. } else {
  1870. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  1871. }
  1872. });
  1873. LogUtil.debug("onecold this.cover =" + this.cover)
  1874. return FileUtil.getFilePath(imagePath); // Return the image path here
  1875. } catch (err) {
  1876. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  1877. return undefined;
  1878. }
  1879. }
  1880. // 拉起picker选择文件管理器
  1881. async callFilePickerSelectFile(): Promise<void> {
  1882. try {
  1883. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  1884. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  1885. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  1886. } else {
  1887. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  1888. }
  1889. let documentPicker = new picker.DocumentViewPicker();
  1890. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  1891. Logger.info(TAG,
  1892. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  1893. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  1894. this.saveVideoDatas(DocumentSelectResult)
  1895. }
  1896. }).catch((err: BusinessError) => {
  1897. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  1898. });
  1899. } catch (err) {
  1900. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  1901. }
  1902. }
  1903. //重命名的对话框
  1904. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  1905. if(!item.filePath.includes(this.packName)){
  1906. ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限重命名')
  1907. return
  1908. }
  1909. DialogHelper.showTextInputDialog({
  1910. title: '重命名',
  1911. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  1912. maskColor: Color.Transparent,
  1913. backgroundColor: Color.Grey,
  1914. transition: AnimationHelper.transitionInDown(666),
  1915. onChange: (text) => {
  1916. console.error("onChange: " + text);
  1917. },
  1918. onAction: (action, dialogId, content) => {
  1919. // ToastUtil.showToast('content = ' +content)
  1920. if (action == DialogAction.TWO) {
  1921. const newName = content
  1922. const newPath = this.currentPath + '/' + newName
  1923. console.log("onecold item = " + item.type);
  1924. this.doReName(index, newName, filePath, newPath, item)
  1925. }
  1926. }
  1927. })
  1928. }
  1929. //剪切 移动到另个文件夹的对话框
  1930. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1931. Logger.info('onecold showCutDialog')
  1932. let mList: Array<string> = []
  1933. let rPath = this.rootPath
  1934. if (isCurrent) {
  1935. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1936. rPath = this.currentPath
  1937. } else {
  1938. mList = Utility.getNameList(this.dirList);
  1939. rPath = this.rootPath
  1940. }
  1941. let dataBean = new BubbleBean()
  1942. dataBean.data = mList
  1943. dataBean.color = this.themeColor
  1944. dataBean.onItemClick = (i) => {
  1945. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1946. Logger.info('newPath = ' + newPath)
  1947. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  1948. ToastUtil.showToast('移动成功')
  1949. this.table.deleteData(item, () => {
  1950. });
  1951. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1952. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1953. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1954. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1955. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1956. this.table.insert(newItem, (id: number) => {
  1957. //加入数据库
  1958. });
  1959. }
  1960. this.cache.delete(this.currentPath); // 删除原路径缓存
  1961. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1962. this.getSortedFiles(this.currentPath, true)
  1963. }).catch((error: BusinessError) => {
  1964. console.error(error.message);
  1965. });
  1966. XPopup.dismissTop()
  1967. }
  1968. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1969. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1970. popupPosition = PopupPosition.TOP
  1971. }
  1972. if (index <= 3) {
  1973. popupPosition = PopupPosition.BOTTOM
  1974. }
  1975. let pup: XPopup
  1976. if (this.isDarkMode) {
  1977. pup = XPopup.Builder()
  1978. .setPopupPosition(popupPosition)
  1979. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  1980. .setBackgroundColor(Color.Black)
  1981. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1982. .show()
  1983. } else {
  1984. pup = XPopup.Builder()
  1985. .setPopupPosition(popupPosition)
  1986. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  1987. .setBackgroundColor(Color.White)
  1988. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1989. .show()
  1990. }
  1991. }
  1992. //复制 到另个文件夹的对话框
  1993. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1994. Logger.info('onecoldv showCopyDialog')
  1995. let mList: Array<string> = []
  1996. let rPath = this.rootPath
  1997. if (isCurrent) {
  1998. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1999. rPath = this.currentPath
  2000. } else {
  2001. mList = Utility.getNameList(this.dirList);
  2002. rPath = this.rootPath
  2003. }
  2004. let dataBean = new BubbleBean()
  2005. dataBean.data = mList
  2006. dataBean.isCopy = true
  2007. dataBean.color = this.themeColor
  2008. dataBean.onItemClick = (i) => {
  2009. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2010. Logger.info('newPath = ' + newPath)
  2011. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2012. ToastUtil.showToast('复制成功')
  2013. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2014. this.getSortedFiles(this.currentPath)
  2015. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2016. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2017. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2018. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2019. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2020. this.table.insert(newItem, (id: number) => {
  2021. //加入数据库
  2022. });
  2023. }
  2024. }).catch((error: BusinessError) => {
  2025. console.error(error.message);
  2026. });
  2027. XPopup.dismissTop()
  2028. }
  2029. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2030. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2031. popupPosition = PopupPosition.TOP
  2032. }
  2033. if (index <= 3) {
  2034. popupPosition = PopupPosition.BOTTOM
  2035. }
  2036. let pup: XPopup
  2037. if (this.isDarkMode) {
  2038. pup = XPopup.Builder()
  2039. .setPopupPosition(popupPosition)
  2040. .atView(id)
  2041. .setMaxHeight('60%')
  2042. .setBackgroundColor(Color.Black)
  2043. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2044. .show();
  2045. } else {
  2046. pup = XPopup.Builder()
  2047. .setPopupPosition(popupPosition)
  2048. .atView(id)
  2049. .setMaxHeight('60%')
  2050. .setBackgroundColor(Color.White)
  2051. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2052. .show();
  2053. }
  2054. }
  2055. //重命名索引index的视频
  2056. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  2057. FileUtil.rename(oldPath, newPath).then(async () => {
  2058. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2059. if (info.type === CommonConstants.TYPE_IS_DIR) {
  2060. //如果是文件夹先删除源数据,再添加新数据
  2061. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  2062. if (success) {
  2063. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  2064. } else {
  2065. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  2066. }
  2067. });
  2068. this.scanDirectory(newPath)
  2069. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  2070. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  2071. if (success) {
  2072. console.log(" onecold 重命名成功,数据库已同步");
  2073. } else {
  2074. console.error(" onecold 重命名数据库失败原因: " + error);
  2075. }
  2076. });
  2077. }
  2078. let mediaItem: VideoItem =
  2079. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2080. this.videoLocalList[index] = mediaItem;
  2081. }
  2082. this.cache.delete(this.currentPath)
  2083. this.getSortedFiles(this.currentPath, true)
  2084. }).catch((error: BusinessError) => {
  2085. console.error(error.message);
  2086. });
  2087. }
  2088. build() {
  2089. Stack() {
  2090. this.ContentBuild()
  2091. Stack() {
  2092. this.PlayController()
  2093. }
  2094. .hitTestBehavior(HitTestMode.Transparent)
  2095. .opacity(this.barBottomOpacity)
  2096. .width('90%')
  2097. .borderRadius(20)
  2098. .margin({ bottom:DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_2IN1
  2099. ? 30 :this.bottomSafeHeight })
  2100. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  2101. .backgroundImage( this.cover)
  2102. .visibility(this.isMultiSelect ? Visibility.None : Visibility.Visible)
  2103. .backgroundImageSize( { width: '100%' })
  2104. .opacity(0.9)
  2105. .clickEffect({ level: ClickEffectLevel.HEAVY })
  2106. }
  2107. .alignContent(Alignment.Bottom)
  2108. .width('100%')
  2109. .height('100%')
  2110. }
  2111. @Builder
  2112. ContentBuild() {
  2113. Scroll() {
  2114. Column() {
  2115. Stack() {
  2116. //libraryname加上去后onKeyEvent监听不了,因为目前的解决方案是上面的XComponent,去掉libraryname
  2117. XComponent({ id: 'for_onKeyEvent',type: XComponentType.SURFACE,
  2118. controller: this.xcomponentController })
  2119. .onLoad(async (event?: object) => {
  2120. })
  2121. .focusable(true)
  2122. .height(0)
  2123. .focusOnTouch(true)
  2124. .defaultFocus(true) // 自动获取键盘焦点
  2125. .onKeyEvent((event?: KeyEvent) => {
  2126. console.info('onecold点击 onKeyEvent')
  2127. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  2128. if (!event || event.type !== KeyType.Down) {
  2129. return;
  2130. }
  2131. console.info('onecold点击 onKeyEvent event.keyCode: ' + event.keyCode)
  2132. //空格键 Space key controls pause/play
  2133. if (event.keyCode === KeyCode.KEYCODE_SPACE|| event.keyCode === KeyCode.KEYCODE_MEDIA_PLAY_PAUSE) {
  2134. this.playOrPause()
  2135. }
  2136. if (event.keyCode === KeyCode.KEYCODE_DPAD_UP) {
  2137. this.playPrevious()
  2138. }
  2139. if (event.keyCode === KeyCode.KEYCODE_DPAD_DOWN) {
  2140. this.playNext()
  2141. }
  2142. // Right-click to fast forward
  2143. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  2144. this.fastForward()
  2145. }
  2146. // Left-click to rewind
  2147. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  2148. this.backForward()
  2149. }
  2150. })
  2151. Column() {
  2152. XComponent({
  2153. id: 'xcomponentId',
  2154. type: 'surface',
  2155. libraryname: 'ijkplayer_napi',
  2156. controller: this.xcomponentController
  2157. })
  2158. .onLoad((event?: object) => {
  2159. if (!!event) {
  2160. this.initDelayPlay(event);
  2161. }
  2162. })
  2163. .onDestroy(() => {
  2164. })
  2165. .width('100%')// .width(this.videoWidth)
  2166. .aspectRatio(this.videoAspectRatio)
  2167. }
  2168. .aspectRatio(this.videoAspectRatio)
  2169. .justifyContent(FlexAlign.Center)
  2170. .backgroundColor(Color.Transparent)
  2171. .visibility(Visibility.Hidden)
  2172. .height(CommonConstants.FULL_PERCENT)
  2173. .width(CommonConstants.FULL_PERCENT)
  2174. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  2175. height:this.isLandscape?'80%': '43%',
  2176. dragBar: true,
  2177. showClose: true,
  2178. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  2179. blurStyle:BlurStyle.Thin,
  2180. backgroundColor:Color.Transparent,
  2181. title: { title: 'AB循环' }
  2182. })
  2183. Stack() {
  2184. Row() {
  2185. Blank()
  2186. .layoutWeight(1)
  2187. IndexerView(
  2188. {
  2189. indexArray: DEFAULT_INDEX,
  2190. selectedIndex: this.selectedIndex,
  2191. textSize: 12,
  2192. selectedColor: "#ff419ee5",
  2193. normalColor: "#ffa0a0a0",
  2194. floatSelectedTextColor: "#ffffff",
  2195. floatSelectedViewColor: "#ff419ee5",
  2196. onIndexChanged: (index) => {
  2197. this.listScroller.scrollToIndex(index)
  2198. }
  2199. })
  2200. .width(24)
  2201. .height("50%")
  2202. }.visibility(Visibility.None)
  2203. Column() {
  2204. // if (!this.isShowCoverHeader()) {
  2205. // this.tabTitle()
  2206. // }
  2207. if(this.twoFingerType==4){
  2208. this.getWaterView()
  2209. }else{
  2210. if(this.isGridMusic){
  2211. this.getGridView()
  2212. }else {
  2213. this.getList()
  2214. }
  2215. }
  2216. if (this.modeType ==0||this.modeType==4) {
  2217. Column() {
  2218. emptyView(this.themeColor)
  2219. }
  2220. .position({ top: 200 })
  2221. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  2222. .animation({ duration: 500 }),
  2223. TransitionEffect.scale({ x: 0, y: 0 })))
  2224. .justifyContent(FlexAlign.Center)
  2225. .opacity(this.isZero ? 1 : 0)
  2226. .visibility(this.isZero && !this.isFavMusic && !this.isHistory
  2227. ? Visibility.Visible : Visibility.None)
  2228. .animation({
  2229. duration: 500,
  2230. curve: 'ease-in-out' // 可选动画曲线
  2231. })
  2232. .width('100%')
  2233. }
  2234. }
  2235. .layoutWeight(1)
  2236. .height('100%')
  2237. this.topTitleBar()
  2238. }
  2239. .alignContent(Alignment.Top)
  2240. .layoutWeight(1)
  2241. .height('100%')
  2242. Row() {
  2243. Button(this.isAllSelected ? '反选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  2244. .width(45)
  2245. .height(45)
  2246. .fontSize(10)
  2247. .margin({ top: 10, bottom: 10, right: 6 })
  2248. .backgroundColor(this.themeColor)
  2249. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2250. .onClick(() => {
  2251. if (this.isAllSelected) {
  2252. // 全不选
  2253. this.selectedFiles = [];
  2254. } else {
  2255. // 全选
  2256. this.selectedFiles = [...this.getCurFileList()];
  2257. }
  2258. this.isAllSelected = !this.isAllSelected;
  2259. })
  2260. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  2261. .width(72)
  2262. .height(45)
  2263. .fontSize(10)
  2264. .margin({ top: 10, bottom: 10, right: 6 })
  2265. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2266. .backgroundColor(this.themeColor)
  2267. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  2268. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2269. })
  2270. .onClick(() => {
  2271. // if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  2272. this.isOneKeyTags = !this.isOneKeyTags
  2273. // }else{
  2274. // ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限批量内嵌')
  2275. // }
  2276. })
  2277. Button('合并', { type: ButtonType.Circle, stateEffect: true })
  2278. .width(45)
  2279. .height(45)
  2280. .fontSize(10)
  2281. .margin({ top: 10, bottom: 10, right: 6 })
  2282. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2283. .backgroundColor(this.themeColor)
  2284. .bindContentCover($$this.isMergeAudio, this.MergeAudioBuilder(), {
  2285. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2286. })
  2287. .onClick(() => {
  2288. if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  2289. this.isMergeAudio = !this.isMergeAudio
  2290. }else{
  2291. ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限合并')
  2292. }
  2293. })
  2294. Button('+歌单', { type: ButtonType.Circle, stateEffect: true })
  2295. .width(45)
  2296. .height(45)
  2297. .fontSize(10)
  2298. .margin({ top: 10, bottom: 10, right: 6 })
  2299. .backgroundColor(this.themeColor)
  2300. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2301. .onClick(async () => {
  2302. this.longItemFilePath = ''
  2303. await this.openAddToPlaylistDialog(this.selectedFiles)
  2304. })
  2305. // Button('乱码', { type: ButtonType.Circle, stateEffect: true })
  2306. // .width(45)
  2307. // .height(45)
  2308. // .fontSize(10)
  2309. // .margin({ top: 10, bottom: 10, right: 6 })
  2310. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2311. // .backgroundColor(this.themeColor)
  2312. // .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  2313. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2314. // })
  2315. // .onClick(() => {
  2316. // this.isFixMessy = !this.isFixMessy
  2317. // })
  2318. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  2319. // .width('35%')
  2320. // .height(60)
  2321. // .id('music_cut')
  2322. // .margin({ top: 10, bottom: 10, right: 6 })
  2323. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2324. // .backgroundColor(this.themeColor)
  2325. // .onClick(() => {
  2326. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  2327. // })
  2328. //
  2329. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  2330. // .width('35%')
  2331. // .height(60)
  2332. // .id('music_cut_current')
  2333. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  2334. // .margin({ top: 10, bottom: 10, right: 6 })
  2335. // .backgroundColor(this.themeColor)
  2336. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2337. // .onClick(() => {
  2338. //
  2339. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  2340. // })
  2341. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  2342. // .width('35%')
  2343. // .height(60)
  2344. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  2345. // .margin({ top: 10, bottom: 10, right: 6 })
  2346. // .backgroundColor(this.themeColor)
  2347. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2348. // .onClick(() => {
  2349. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  2350. // })
  2351. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  2352. .width(45)
  2353. .height(45)
  2354. .fontSize(10)
  2355. .margin({ top: 10, bottom: 10, right: 6 })
  2356. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  2357. .backgroundColor(this.themeColor)
  2358. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2359. .onClick(() => {
  2360. this.showWarnIsDelete()
  2361. })
  2362. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  2363. .width(45)
  2364. .height(45)
  2365. .fontSize(10)
  2366. .margin({ top: 10, bottom: 10, right: 6 })
  2367. .backgroundColor(this.themeColor)
  2368. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2369. .onClick(() => {
  2370. this.selectedFiles = [];
  2371. this.isAllSelected = false
  2372. this.isMultiSelect = false
  2373. })
  2374. }
  2375. .width('100%')
  2376. .justifyContent(FlexAlign.Center)
  2377. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2378. .opacity(this.isMultiSelect ? 1 : 0)
  2379. .animation({
  2380. duration: 666,
  2381. curve: 'ease-in-out' // 可选动画曲线
  2382. })
  2383. .position({ bottom: 20 }) // 将 Row 固定在底部
  2384. }
  2385. .width('100%')
  2386. .height('100%')
  2387. .alignContent(Alignment.Top)
  2388. }
  2389. .width('100%')
  2390. .height('100%')
  2391. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  2392. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  2393. .backgroundImagePosition(Alignment.Center)
  2394. .backdropBlur(this.blurValue)
  2395. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  2396. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  2397. }
  2398. }
  2399. @Builder
  2400. topTitleBar(){
  2401. Column() {
  2402. Row({ space: 15 }) {
  2403. if (!this.isSearchMode ) {
  2404. //左侧滑动按钮
  2405. Button({ type: ButtonType.Circle, stateEffect: true }) {
  2406. SymbolGlyph(this.rightTopImage)
  2407. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  2408. }
  2409. .attributeModifier(new ButtonFancyModifier(40, 40))
  2410. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  2411. .animation({ duration: 300, curve: Curve.Ease })
  2412. .onClick(() => {
  2413. this.doSwipBack()
  2414. })
  2415. .attributeModifier(new ShadowModifier())
  2416. .zIndex(0)
  2417. }else{
  2418. //左侧搜索返回按钮
  2419. Button({ type: ButtonType.Circle, stateEffect: true }) {
  2420. SymbolGlyph($r('sys.symbol.chevron_left'))
  2421. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  2422. }
  2423. .attributeModifier(new ButtonFancyModifier(40, 40))
  2424. .margin({bottom:5})
  2425. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  2426. .animation({ duration: 300, curve: Curve.Ease })
  2427. .onClick(() => {
  2428. this.isSearchMode = false
  2429. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  2430. this.searchText = ''
  2431. this.getSortedFiles(this.currentPath)
  2432. return
  2433. }
  2434. this.onSearchInput('')
  2435. })
  2436. .attributeModifier(new ShadowModifier())
  2437. .zIndex(0)
  2438. }
  2439. if (!this.isSearchMode) {
  2440. Text(this.titleName)
  2441. .margin({left:3,right:10})
  2442. .fontColor($r('app.color.text_color'))
  2443. .fontSize(this.twoFingerType==3?19:this.twoFingerType==2?17:15)
  2444. .maxLines(1)
  2445. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  2446. .layoutWeight(1)
  2447. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  2448. }
  2449. //搜索框
  2450. Search({ controller: this.searchController,value: this.searchText, placeholder: '搜索标题、艺术家...' })
  2451. .searchButton('搜索',{fontColor:this.themeColor})
  2452. .searchIcon({
  2453. src: $r('sys.media.ohos_ic_public_search_filled')
  2454. })
  2455. .cancelButton({
  2456. style: CancelButtonStyle.CONSTANT,
  2457. icon: {
  2458. src: $r('sys.media.ohos_ic_public_cancel_filled')
  2459. }
  2460. })
  2461. .layoutWeight(1)
  2462. .height(40)
  2463. .maxLength(20)
  2464. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  2465. .placeholderColor(Color.Grey)
  2466. .placeholderFont({ size: 14, weight: 400 })
  2467. .textFont({ size: 14, weight: 400 })
  2468. .onSubmit((value: string) => {
  2469. console.log('onecold onSubmit ='+value)
  2470. this.searchController.stopEditing()
  2471. this.onSearchInput(this.searchText);
  2472. })
  2473. .onChange((value: string) => {
  2474. console.log('onecold onChange ='+value)
  2475. this.onSearchInput(value);
  2476. })
  2477. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  2478. .animation({ duration: 300, curve: Curve.Ease })
  2479. //搜索按钮
  2480. if (!this.isSearchMode) {
  2481. Button({ type: ButtonType.Circle, stateEffect: true }) {
  2482. SymbolGlyph($r('sys.symbol.magnifyingglass'))
  2483. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  2484. }
  2485. .attributeModifier(new ButtonFancyModifier(40, 40))
  2486. .animation({ duration: 300, curve: Curve.Ease })
  2487. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  2488. .attributeModifier(new ShadowModifier())
  2489. .zIndex(0)
  2490. .onClick(()=>{
  2491. this.isSearchMode = true
  2492. })
  2493. //排序按钮
  2494. Button({ type: ButtonType.Circle, stateEffect: true }) {
  2495. SymbolGlyph($r('sys.symbol.list_number'))
  2496. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  2497. }
  2498. .attributeModifier(new ButtonFancyModifier(40, 40))
  2499. .animation({ duration: 300, curve: Curve.Ease })
  2500. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  2501. .bindMenu((this.modeType==2&&!this.isCanBack)||(this.modeType==3&&!this.isCanBack)
  2502. ?this.SortMenuForArtistAblumBuilder:this.SortMenuBuilder)
  2503. .attributeModifier(new ShadowModifier())
  2504. .zIndex(0)
  2505. //添加按钮
  2506. Button({ type: ButtonType.Circle, stateEffect: true }) {
  2507. SymbolGlyph($r('sys.symbol.plus'))
  2508. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  2509. }
  2510. .attributeModifier(new ButtonFancyModifier(40, 40))
  2511. .animation({ duration: 300, curve: Curve.Ease })
  2512. .visibility(this.modeType==0||this.modeType==1?Visibility.Visible:Visibility.None)
  2513. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  2514. .bindSheet($$this.showAddSheet, this.addSheet(), {
  2515. height: SheetSize.FIT_CONTENT,
  2516. dragBar: true,
  2517. showClose: true,
  2518. preferType: SheetType.CENTER ,
  2519. title: {
  2520. title: '导入音乐'
  2521. }
  2522. })
  2523. .onClick(() => {
  2524. this.showAddSheet = !this.showAddSheet;
  2525. })
  2526. .attributeModifier(new ShadowModifier())
  2527. .zIndex(0)
  2528. }
  2529. }
  2530. }
  2531. .padding({ top: this.topSafeHeight+10, left: 10, right: 10 })
  2532. .width('100%')
  2533. }
  2534. @Builder
  2535. addSheet() {
  2536. Scroll() {
  2537. Column() {
  2538. Column() {
  2539. Row() {
  2540. Text('导入音乐复制到DownLoad目录')
  2541. .margin({ left: 18 })
  2542. .fontSize(14)
  2543. .fontColor($r('app.color.text_color'))
  2544. .fontWeight(480)
  2545. .layoutWeight(1)
  2546. Toggle({ type: ToggleType.Switch, isOn: this.isCopyFileToDownLoad })
  2547. .selectedColor(this.themeColor)
  2548. .switchPointColor(Color.White)
  2549. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2550. .margin({ right: 18 })
  2551. .onChange((checked: boolean) => {
  2552. this.isCopyFileToDownLoad = checked;
  2553. PreferencesUtil.put(SettingPage.IS_COPYFILE_TO_DOWNLOAD, this.isCopyFileToDownLoad)
  2554. })
  2555. .width(50)
  2556. .height(30);
  2557. }
  2558. .height(88)
  2559. }
  2560. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  2561. .backgroundColor($r('app.color.start_window_background'))
  2562. .borderRadius(15)
  2563. .margin({
  2564. left: 30,
  2565. right: 30,
  2566. top: 10,
  2567. bottom: 10
  2568. })
  2569. .padding(0)
  2570. .border({
  2571. color: Color.White,
  2572. width: 1.8
  2573. })
  2574. Menu() {
  2575. MenuItem({
  2576. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder_badge_plus')),
  2577. content: "新建文件夹"
  2578. })
  2579. .backgroundColor($r('app.color.silvery'))
  2580. .border({
  2581. width: { bottom: 1 },
  2582. color: '#12ec5c87'
  2583. })
  2584. .margin(10)
  2585. .padding({left:15,right:15})
  2586. .onClick(async () => {
  2587. this.showMkDialog()
  2588. this.showAddSheet = !this.showAddSheet
  2589. })
  2590. MenuItem({
  2591. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder')),
  2592. content: $r('app.string.import_from_files')
  2593. })
  2594. .padding({left:15,right:15})
  2595. .backgroundColor($r('app.color.silvery'))
  2596. .border({
  2597. width: { bottom: 1 },
  2598. color: '#12ec5c87'
  2599. })
  2600. .margin(10)
  2601. .onClick(async () => {
  2602. this.callFilePickerSelectFile()
  2603. this.showAddSheet = !this.showAddSheet
  2604. })
  2605. MenuItem({
  2606. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square')),
  2607. content: '全选导入'
  2608. // content: '从下载文件夹导入(路径:Download/' +
  2609. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  2610. })
  2611. .padding({left:15,right:15})
  2612. .backgroundColor($r('app.color.silvery'))
  2613. .border({
  2614. width: { bottom: 1 },
  2615. color: '#12ec5c87'
  2616. })
  2617. .margin(10)
  2618. .onClick(async () => {
  2619. this.goSelectMusic()
  2620. this.showAddSheet = !this.showAddSheet
  2621. })
  2622. MenuItem({
  2623. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.save')),
  2624. content: '自动导入教程'
  2625. // content: '从下载文件夹导入(路径:Download/' +
  2626. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  2627. })
  2628. .padding({left:15,right:15})
  2629. .backgroundColor($r('app.color.silvery'))
  2630. .border({
  2631. width: { bottom: 1 },
  2632. color: '#12ec5c87'
  2633. })
  2634. .margin(10)
  2635. .onClick(async () => {
  2636. this.showTips()
  2637. this.showAddSheet = !this.showAddSheet
  2638. })
  2639. }.attributeModifier(new MenuModifier())
  2640. .margin({bottom:30})
  2641. }
  2642. .layoutWeight(1)
  2643. }
  2644. }
  2645. @Builder
  2646. TagsContentCoverBuilder() {
  2647. Scroll() {
  2648. Column() {
  2649. TagsContentCover(
  2650. {
  2651. selectedFiles:this.selectedFiles,
  2652. isOneKeyTags:this.isOneKeyTags,
  2653. table:this.table,
  2654. onTagsResult:(result: boolean)=>{
  2655. this.isMultiSelect = false
  2656. if(result){//如果嵌入成功,更新数据
  2657. setTimeout(()=>{
  2658. this.doUpdateData()
  2659. },500)
  2660. }
  2661. }
  2662. }
  2663. )
  2664. }
  2665. }
  2666. .width('100%')
  2667. .height('100%')
  2668. }
  2669. @Builder
  2670. FixMessyViewBuilder() {
  2671. Scroll() {
  2672. Column() {
  2673. FixMessyView(
  2674. {
  2675. selectedFiles:this.selectedFiles,
  2676. isFixMessy:this.isFixMessy,
  2677. onFixResult:(result: boolean)=>{
  2678. this.isMultiSelect = false
  2679. if(result){//如果嵌入成功,更新数据
  2680. this.deleteCache(this.currentPath)
  2681. this.doUpdateData()
  2682. }
  2683. }
  2684. }
  2685. )
  2686. }
  2687. }
  2688. .width('100%')
  2689. .height('100%')
  2690. }
  2691. //剪辑音频
  2692. @Builder
  2693. EditAudioBuilder(item:VideoItem) {
  2694. Scroll() {
  2695. Column() {
  2696. EditAudio(
  2697. {
  2698. mVideoItem:item,
  2699. currentPath:this.currentPath,
  2700. videoUrl:this.videoUrl,
  2701. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  2702. currentTime:this.currentTime,
  2703. progressValue:this.progressValue,
  2704. onBack:()=>{
  2705. this.isEditAudio = !this.isEditAudio
  2706. },
  2707. onSeeOutputPath:(outPutPath:string)=>{
  2708. this.isEditAudio = !this.isEditAudio
  2709. this.longItemFilePath = ''
  2710. this.modeType = 0
  2711. this.isShowFileName = true
  2712. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  2713. },
  2714. onPlayOrPause:()=>{
  2715. if(this.videoUrl==item.filePath){
  2716. this.playOrPause()
  2717. }else{//如果不是当前播放的,则播放该文件
  2718. this.videoUrl==item.filePath
  2719. this.doPlay(item,0,false,true)
  2720. }
  2721. },
  2722. onSliderChange:(value:number)=>{
  2723. if(this.videoUrl!=item.filePath){
  2724. this.videoUrl==item.filePath
  2725. return
  2726. }
  2727. this.isSeekTo = true;
  2728. this.mDestroyPage = false;
  2729. this.showLoadIng();
  2730. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  2731. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  2732. this.seekTo(seekValue + "");
  2733. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  2734. this.isSeekTo = false;
  2735. },
  2736. onResult:(result: boolean,outPath:string)=>{
  2737. if(result){//如果剪辑成功,更新数据
  2738. this.doUpdateData()
  2739. }else{
  2740. ToastUtil.showToast('剪辑失败')
  2741. }
  2742. }
  2743. }
  2744. )
  2745. }
  2746. }
  2747. .width('100%')
  2748. .height('100%')
  2749. }
  2750. //提取伴奏
  2751. @Builder
  2752. ConverterBuilder(item:VideoItem) {
  2753. Scroll() {
  2754. Column() {
  2755. AudioFormatConverter(
  2756. {
  2757. mVideoItem:item,
  2758. videoUrl:this.videoUrl,
  2759. currentPath:this.currentPath,
  2760. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  2761. currentTime:this.currentTime,
  2762. progressValue:this.progressValue,
  2763. onBack:()=>{
  2764. this.isConverter = !this.isConverter
  2765. this.longItemFilePath = ''
  2766. },
  2767. onPlayOrPause:()=>{
  2768. if(this.videoUrl==item.filePath){
  2769. this.playOrPause()
  2770. }else{//如果不是当前播放的,则播放该文件
  2771. this.videoUrl==item.filePath
  2772. this.doPlay(item,0,false,true)
  2773. }
  2774. },
  2775. onSeeOutputPath:(outPutPath:string)=>{
  2776. this.isConverter = !this.isConverter
  2777. this.longItemFilePath = ''
  2778. this.modeType = 0
  2779. this.isShowFileName = true
  2780. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  2781. },
  2782. onSliderChange:(value:number)=>{
  2783. if(this.videoUrl!=item.filePath){
  2784. this.videoUrl==item.filePath
  2785. return
  2786. }
  2787. this.isSeekTo = true;
  2788. this.mDestroyPage = false;
  2789. this.showLoadIng();
  2790. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  2791. this.seekTo(seekValue + "");
  2792. this.isSeekTo = false;
  2793. },
  2794. onResult:(result: boolean,outPath:string)=>{
  2795. if(result){//如果成功,更新数据
  2796. this.doUpdateData()
  2797. }else{
  2798. ToastUtil.showToast('格式转化失败')
  2799. }
  2800. }
  2801. }
  2802. )
  2803. }
  2804. }
  2805. .width('100%')
  2806. .height('100%')
  2807. }
  2808. //提取伴奏
  2809. @Builder
  2810. ExtractAccBuilder(item:VideoItem) {
  2811. Scroll() {
  2812. Column() {
  2813. ExtractAccompaniment(
  2814. {
  2815. mVideoItem:item,
  2816. currentPath:this.currentPath,
  2817. videoUrl:this.videoUrl,
  2818. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  2819. currentTime:this.currentTime,
  2820. progressValue:this.progressValue,
  2821. onBack:()=>{
  2822. this.isExtractAcc = !this.isExtractAcc
  2823. this.longItemFilePath = ''
  2824. },
  2825. onPlayOrPause:()=>{
  2826. if(this.videoUrl==item.filePath){
  2827. this.playOrPause()
  2828. }else{//如果不是当前播放的,则播放该文件
  2829. this.videoUrl==item.filePath
  2830. this.doPlay(item,0,false,true)
  2831. }
  2832. },
  2833. onSeeOutputPath:(outPutPath:string)=>{
  2834. this.isExtractAcc = !this.isExtractAcc
  2835. this.longItemFilePath = ''
  2836. this.modeType = 0
  2837. this.isShowFileName = true
  2838. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  2839. },
  2840. onSliderChange:(value:number)=>{
  2841. if(this.videoUrl!=item.filePath){
  2842. this.videoUrl==item.filePath
  2843. return
  2844. }
  2845. this.isSeekTo = true;
  2846. this.mDestroyPage = false;
  2847. this.showLoadIng();
  2848. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  2849. this.seekTo(seekValue + "");
  2850. this.isSeekTo = false;
  2851. },
  2852. onResult:(result: boolean,outPath:string)=>{
  2853. if(result){//如果成功,更新数据
  2854. this.doUpdateData()
  2855. }else{
  2856. ToastUtil.showToast('提取伴奏失败')
  2857. }
  2858. }
  2859. }
  2860. )
  2861. }
  2862. }
  2863. .width('100%')
  2864. .height('100%')
  2865. }
  2866. //AI人声分离
  2867. @Builder
  2868. AiBuilder(item:VideoItem) {
  2869. Scroll() {
  2870. Column() {
  2871. AIVoiceSeparation(
  2872. {
  2873. mVideoItem:item,
  2874. videoUrl:this.videoUrl,
  2875. currentPath:this.currentPath,
  2876. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  2877. currentTime:this.currentTime,
  2878. progressValue:this.progressValue,
  2879. onBack:()=>{
  2880. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  2881. this.longItemFilePath = ''
  2882. },
  2883. onPlayOrPause:()=>{
  2884. if(this.videoUrl==item.filePath||this.isPlaying){
  2885. this.playOrPause()
  2886. }else{//如果不是当前播放的,则播放该文件
  2887. this.videoUrl==item.filePath
  2888. this.doPlay(item,0,false,true)
  2889. }
  2890. },
  2891. onPlayPath:(path:string)=>{
  2892. this.videoUrl==path
  2893. const itemP = Utility.getItemByFilePath(this.videoLocalList,path)
  2894. if(itemP)
  2895. this.doPlay(itemP,0,false,true)
  2896. },
  2897. onSeeOutputPath:(outPutPath:string)=>{
  2898. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  2899. this.longItemFilePath = ''
  2900. this.modeType = 0
  2901. this.isShowFileName = true
  2902. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  2903. },
  2904. onSliderChange:(value:number)=>{
  2905. if(this.videoUrl!=item.filePath){
  2906. this.videoUrl==item.filePath
  2907. return
  2908. }
  2909. this.isSeekTo = true;
  2910. this.mDestroyPage = false;
  2911. this.showLoadIng();
  2912. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  2913. this.seekTo(seekValue + "");
  2914. this.isSeekTo = false;
  2915. },
  2916. onResult:(result: boolean,outPath:string)=>{
  2917. if(result){//如果成功,更新数据
  2918. this.doUpdateData()
  2919. }else{
  2920. ToastUtil.showToast('Ai人声分离失败')
  2921. }
  2922. }
  2923. }
  2924. )
  2925. }
  2926. }
  2927. .width('100%')
  2928. .height('100%')
  2929. }
  2930. //提取视频中的音频
  2931. @Builder
  2932. extractAudioFromVideoBuilder(item:VideoItem) {
  2933. Scroll() {
  2934. Column() {
  2935. ExtractAudioFromVideo(
  2936. {
  2937. mVideoItem:item,
  2938. currentPath:this.currentPath,
  2939. videoUrl:this.videoUrl,
  2940. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  2941. currentTime:this.currentTime,
  2942. progressValue:this.progressValue,
  2943. onBack:()=>{
  2944. this.isExtractAudio = !this.isExtractAudio
  2945. this.longItemFilePath = ''
  2946. },
  2947. onPlayOrPause:()=>{
  2948. if(this.videoUrl==item.filePath){
  2949. this.playOrPause()
  2950. }else{//如果不是当前播放的,则播放该文件
  2951. this.videoUrl==item.filePath
  2952. this.doPlay(item,0,false,true)
  2953. }
  2954. },
  2955. onSeeOutputPath:(outPutPath:string)=>{
  2956. this.isExtractAudio = !this.isExtractAudio
  2957. this.longItemFilePath = ''
  2958. this.modeType = 0
  2959. this.isShowFileName = true
  2960. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  2961. },
  2962. onSliderChange:(value:number)=>{
  2963. if(this.videoUrl!=item.filePath){
  2964. this.videoUrl==item.filePath
  2965. return
  2966. }
  2967. this.isSeekTo = true;
  2968. this.mDestroyPage = false;
  2969. this.showLoadIng();
  2970. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  2971. this.seekTo(seekValue + "");
  2972. this.isSeekTo = false;
  2973. },
  2974. onResult:(result: boolean,outPath:string)=>{
  2975. if(result){//如果成功,更新数据
  2976. this.doUpdateData()
  2977. }else{
  2978. ToastUtil.showToast('提取音频失败')
  2979. }
  2980. }
  2981. }
  2982. )
  2983. }
  2984. }
  2985. .width('100%')
  2986. .height('100%')
  2987. }
  2988. //合并音频
  2989. @Builder
  2990. MergeAudioBuilder() {
  2991. Scroll() {
  2992. Column() {
  2993. MergeAudio(
  2994. {
  2995. videoUrl:this.videoUrl,
  2996. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  2997. currentPath:this.currentPath,
  2998. selectedFiles:this.selectedFiles,
  2999. currentTime:this.currentTime,
  3000. progressValue:this.progressValue,
  3001. onBack:()=>{
  3002. this.isMergeAudio = !this.isMergeAudio
  3003. this.longItemFilePath = ''
  3004. },
  3005. // onPlayPath:(path:string)=>{
  3006. // if(this.videoUrl==item.filePath){
  3007. // this.playOrPause()
  3008. // }else{//如果不是当前播放的,则播放该文件
  3009. // this.videoUrl==item.filePath
  3010. // this.doPlay(item,0,false,true)
  3011. // }
  3012. //
  3013. // },
  3014. onSeeOutputPath:(outPutPath:string)=>{
  3015. this.isMergeAudio = !this.isMergeAudio
  3016. this.longItemFilePath = ''
  3017. this.modeType = 0
  3018. this.isShowFileName = true
  3019. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3020. },
  3021. onResult:(result: boolean,outPath:string)=>{
  3022. if(result){//如果成功,更新数据
  3023. this.doUpdateData()
  3024. }else{
  3025. if(this.selectedFiles.length>=3){
  3026. ToastUtil.showToast('合并数量太多导致失败')
  3027. }else{
  3028. ToastUtil.showToast('合并失败')
  3029. }
  3030. }
  3031. }
  3032. }
  3033. )
  3034. }
  3035. }
  3036. .width('100%')
  3037. .height('100%')
  3038. }
  3039. asyncCurrentPathData() {
  3040. if (this.modeType == 0) {
  3041. workerInstance.postMessage({
  3042. code: 1,
  3043. data1: this.context,
  3044. data2: this.currentPath,
  3045. data3: this.lockPath,
  3046. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  3047. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  3048. });
  3049. }
  3050. }
  3051. // 处理文件选择的函数
  3052. handleFileSelection(item: VideoItem, checked: boolean) {
  3053. if (checked) {
  3054. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  3055. this.selectedFiles.push(item);
  3056. }
  3057. } else {
  3058. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  3059. if (index > -1) {
  3060. this.selectedFiles.splice(index, 1);
  3061. }
  3062. }
  3063. }
  3064. private deleteComponentId: number = 0
  3065. //多选删除文件
  3066. showWarnIsDelete(){
  3067. this.getUIContext().getPromptAction().openCustomDialog({
  3068. builder: () => {
  3069. this.deleteComptentBuilder()
  3070. },
  3071. isModal:true,
  3072. showInSubWindow:false,
  3073. maskColor: Color.Transparent,
  3074. dialogTransition: // 设置弹窗内容显示的过渡效果
  3075. TransitionEffect.translate({ x: 0, y: 290, z: 0 })
  3076. .animation({ duration: 600, curve: Curve.Smooth }),
  3077. maskTransition: // 设置蒙层显示的过渡效果
  3078. TransitionEffect.opacity(0)
  3079. .animation({ duration: 600, curve: Curve.Smooth })
  3080. }).then((dialogId: number) => {
  3081. this.deleteComponentId = dialogId
  3082. })
  3083. .catch((error: BusinessError) => {
  3084. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  3085. })
  3086. }
  3087. @Builder
  3088. deleteComptentBuilder(){
  3089. DeleteComptent({
  3090. selectedFiles:this.selectedFiles,
  3091. onCancel:()=>{
  3092. this.isMultiSelect = false
  3093. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  3094. },
  3095. onDeleteResult:(result: boolean)=>{
  3096. this.isMultiSelect = false
  3097. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  3098. if(result){//如果删除成功,更新数据
  3099. this.selectedFiles = [];
  3100. this.isAllSelected = false
  3101. this.cache.delete(this.currentPath);
  3102. this.getSortedFiles(this.currentPath, true);
  3103. }
  3104. }
  3105. })
  3106. }
  3107. //多选移动文件
  3108. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  3109. Logger.info('onecold showCutDialogForMultipleFiles')
  3110. let mList: Array<string> = []
  3111. let rPath = this.rootPath
  3112. if (isCurrent) {
  3113. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  3114. rPath = this.currentPath
  3115. } else {
  3116. mList = Utility.getNameList(this.dirList);
  3117. rPath = this.rootPath
  3118. }
  3119. let dataBean = new BubbleBean();
  3120. dataBean.data = mList;
  3121. dataBean.color = this.themeColor
  3122. dataBean.onItemClick = (i) => {
  3123. const newDirPath = rPath + '/' + mList[i];
  3124. // Logger.info('newDirPath = ' + newDirPath)
  3125. this.selectedFiles.forEach((item) => {
  3126. const newPath = newDirPath + '/' + item.fileName;
  3127. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  3128. ToastUtil.showToast('移动成功');
  3129. this.table.deleteData(item, () => {
  3130. this.cache.delete(this.currentPath); // 删除原路径缓存
  3131. this.cache.delete(newDirPath); // 删除目标路径缓存
  3132. this.getSortedFiles(this.currentPath, true);
  3133. });
  3134. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  3135. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  3136. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  3137. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3138. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  3139. this.table.insert(newItem, (id: number) => {
  3140. //加入数据库
  3141. });
  3142. }
  3143. }).catch((error: Error) => {
  3144. console.error(error.message);
  3145. });
  3146. });
  3147. this.isMultiSelect = false
  3148. this.selectedFiles = [];
  3149. this.isAllSelected = false
  3150. XPopup.dismissTop();
  3151. };
  3152. let pup: XPopup
  3153. if (this.isDarkMode) {
  3154. pup = XPopup.Builder()
  3155. .setPopupPosition(PopupPosition.TOP)
  3156. .atView(viewId)
  3157. .setBackgroundColor(Color.Black)
  3158. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3159. .show();
  3160. } else {
  3161. pup = XPopup.Builder()
  3162. .setPopupPosition(PopupPosition.TOP)
  3163. .atView(viewId)
  3164. .setBackgroundColor(Color.White)
  3165. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3166. .show();
  3167. }
  3168. }
  3169. /**
  3170. * 加载所有歌单
  3171. */
  3172. async loadAllPlaylists() {
  3173. try {
  3174. this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
  3175. LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
  3176. } catch (error) {
  3177. LogUtil.error('heaunp Failed to load playlists: ' + error.message)
  3178. }
  3179. }
  3180. /**
  3181. * 显示添加到歌单对话框
  3182. */
  3183. async openAddToPlaylistDialog(items: VideoItem | VideoItem[]) {
  3184. const songs = Array.isArray(items) ? items : [items]
  3185. const musicItems = songs.filter(song => song.type !== CommonConstants.TYPE_IS_DIR)
  3186. if (musicItems.length === 0) {
  3187. ToastUtil.showToast('请选择要添加的歌曲')
  3188. return
  3189. }
  3190. // 加载最新的歌单列表
  3191. await this.loadAllPlaylists()
  3192. showAddToPlaylistDialog(
  3193. musicItems,
  3194. this.allPlaylists,
  3195. async (playlistId: string) => {
  3196. // 添加歌曲到歌单
  3197. const success = await this.playlistTable?.addSongsToPlaylist(playlistId,
  3198. musicItems.map(song => song.filePath))
  3199. if (success) {
  3200. const count = musicItems.length
  3201. ToastUtil.showToast(count > 1 ? `已添加 ${count} 首歌曲` : '已添加到歌单')
  3202. // 重新加载歌单列表
  3203. await this.loadAllPlaylists()
  3204. } else {
  3205. ToastUtil.showToast(musicItems.length > 1 ? '选中的歌曲已在该歌单中' : '歌曲已在该歌单中')
  3206. }
  3207. this.longItemFilePath = ''
  3208. if (this.isMultiSelect) {
  3209. this.isMultiSelect = false
  3210. this.isAllSelected = false
  3211. this.selectedFiles = []
  3212. }
  3213. },
  3214. () => {
  3215. LogUtil.info('取消添加到歌单')
  3216. },
  3217. () => {
  3218. // 创建新歌单
  3219. showCreatePlaylistDialog(
  3220. async (name: string, description: string, coverPath?: string) => {
  3221. const success = await this.playlistTable?.createPlaylist(name, description, coverPath)
  3222. if (success) {
  3223. ToastUtil.showToast('歌单创建成功')
  3224. // 重新加载歌单列表并打开添加对话框
  3225. await this.loadAllPlaylists()
  3226. await this.openAddToPlaylistDialog(musicItems)
  3227. } else {
  3228. ToastUtil.showToast('歌单创建失败')
  3229. }
  3230. },
  3231. () => {
  3232. // 取消创建歌单
  3233. }
  3234. )
  3235. }
  3236. )
  3237. }
  3238. doFav(item: VideoItem) {
  3239. LogUtil.info('onecold doFav isFav=' + item.isFav)
  3240. let isFav = 0
  3241. if (Utility.getIsFav(this.favList, item)) {
  3242. isFav = 0
  3243. } else {
  3244. isFav = 1
  3245. }
  3246. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  3247. if (result) {
  3248. if (isFav === 1) {
  3249. ToastUtil.showToast('收藏成功');
  3250. } else {
  3251. ToastUtil.showToast('取消收藏成功');
  3252. }
  3253. this.deleteCache(this.currentPath)
  3254. this.getFavList(false)
  3255. if (this.modeType === 0 && !this.isFavMusic) {
  3256. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  3257. this.getSortedFiles(this.currentPath)
  3258. }
  3259. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  3260. workerInstance.postMessage({ code: 3, data: this.context });
  3261. workerInstance.postMessage({ code: 4, data: this.context });
  3262. }
  3263. })
  3264. }
  3265. //多选复制文件
  3266. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  3267. console.log('onecold showCopyDialogForMultipleFiles');
  3268. let mList: Array<string> = []
  3269. let rPath = this.rootPath
  3270. if (isCurrent) {
  3271. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  3272. rPath = this.currentPath
  3273. } else {
  3274. mList = Utility.getNameList(this.dirList);
  3275. rPath = this.rootPath
  3276. }
  3277. let dataBean = new BubbleBean();
  3278. dataBean.data = mList;
  3279. dataBean.isCopy = true
  3280. dataBean.color = this.themeColor
  3281. dataBean.onItemClick = (i) => {
  3282. const newDirPath = rPath + '/' + mList[i];
  3283. // Logger.info('newDirPath = ' + newDirPath)
  3284. this.selectedFiles.forEach((item) => {
  3285. const newPath = newDirPath + '/' + item.fileName;
  3286. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  3287. ToastUtil.showToast('复制成功');
  3288. this.cache.delete(newDirPath); // 删除目标路径缓存
  3289. this.getSortedFiles(this.currentPath);
  3290. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  3291. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  3292. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  3293. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3294. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  3295. this.table.insert(newItem, (id: number) => {
  3296. //加入数据库
  3297. });
  3298. }
  3299. }).catch((error: Error) => {
  3300. console.error(error.message);
  3301. });
  3302. });
  3303. this.isMultiSelect = false
  3304. this.selectedFiles = [];
  3305. this.isAllSelected = false
  3306. XPopup.dismissTop();
  3307. };
  3308. let pup: XPopup
  3309. if (this.isDarkMode) {
  3310. pup = XPopup.Builder()
  3311. .setPopupPosition(PopupPosition.TOP)
  3312. .atView(viewId)
  3313. .setBackgroundColor(Color.Black)
  3314. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3315. .show();
  3316. } else {
  3317. pup = XPopup.Builder()
  3318. .setPopupPosition(PopupPosition.TOP)
  3319. .atView(viewId)
  3320. .setBackgroundColor(Color.White)
  3321. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3322. .show();
  3323. }
  3324. }
  3325. @Builder
  3326. private DirItem(item: VideoItem, index?: number) {
  3327. Button({ type: ButtonType.Normal, stateEffect: true }) {
  3328. Row() {
  3329. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  3330. $r('app.media.music_group'))
  3331. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  3332. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  3333. .fillColor(this.themeColor)// .fontSize(33)
  3334. .alt($r('app.media.music_group'))
  3335. .borderRadius('100%')
  3336. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  3337. // .autoResize(true) // 重采样,可减少内存占用
  3338. .clip(true)
  3339. .sourceSize({width:38, height:38})
  3340. .margin({ left: 20, top: 8, bottom: 8 })
  3341. Column() {
  3342. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  3343. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  3344. .maxLines(1)// .width('88%')
  3345. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  3346. .animation({
  3347. duration: 555,
  3348. curve: 'ease-in-out',
  3349. })
  3350. .transition({
  3351. type: TransitionType.Insert,
  3352. opacity: 0,
  3353. translate: { x: 160 }
  3354. })
  3355. .margin({ left: 10, right: 20 })
  3356. .fontColor($r('app.color.text_color'))
  3357. Row() {
  3358. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  3359. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  3360. .padding({ top: 8 })
  3361. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  3362. .fontColor($r('app.color.text_color'))
  3363. .margin({ left: 10 })
  3364. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  3365. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  3366. .padding({ top: 8 })
  3367. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  3368. .fontColor($r('app.color.text_color'))
  3369. .margin({ left: 10 })
  3370. Blank()
  3371. }
  3372. }
  3373. .height('100%')
  3374. .layoutWeight(1)
  3375. .justifyContent(FlexAlign.Center)
  3376. .alignItems(HorizontalAlign.Start)
  3377. Blank()
  3378. Image($r('app.media.arrow_right'))
  3379. .height(25)
  3380. .margin({ right: 10 })
  3381. .alignSelf(ItemAlign.Center)
  3382. .id(item.filePath)
  3383. }
  3384. }
  3385. .backgroundColor(Color.Transparent)
  3386. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  3387. .width('100%')
  3388. .reuseId('dir_item')
  3389. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  3390. .opacity(this.opacityItem) // 绑定透明度
  3391. }
  3392. isShowDir(dirName: string) {
  3393. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  3394. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  3395. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  3396. if (dirName === undefined) {
  3397. return true
  3398. }
  3399. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  3400. return this.isShowSimi
  3401. }
  3402. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  3403. return this.isShowFAV
  3404. }
  3405. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  3406. return this.isShowHistory
  3407. }
  3408. return true
  3409. }
  3410. @State opacityItem: number = 1; // 控制透明度的状态变量
  3411. @Builder
  3412. private MusicItem(item: VideoItem, index?: number) {
  3413. Button({ type: ButtonType.Normal, stateEffect: true }) {
  3414. Row() {
  3415. Stack() {
  3416. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  3417. .fillColor(this.themeColor)
  3418. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  3419. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  3420. .alt($r('app.media.music_red'))
  3421. .borderRadius(this.isCoverRectangle?13:'100%')
  3422. .clip(true)
  3423. .draggable(false)
  3424. .sourceSize({width:38, height:38})
  3425. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  3426. // .autoResize(true) // 重采样,可减少内存占用
  3427. .opacity(this.opacityItem)// 绑定透明度
  3428. .margin({ left: 20 })
  3429. .gesture(LongPressGesture()
  3430. .onAction(async () => {
  3431. //如果是专辑和艺术家的首页,不能长按
  3432. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  3433. return
  3434. //如果是我的收藏 最近播放等也不能长按
  3435. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3436. item.name === LocalMusic.STR_HISTORY_MUSIC
  3437. )
  3438. return
  3439. this.longItemFilePath = item.filePath
  3440. this.tempLyricContent = await this.getLyricContent(item)
  3441. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  3442. })
  3443. .onActionEnd((event: GestureEvent) => {
  3444. }))
  3445. .onClick(()=>{
  3446. if (this.isMultiSelect) {
  3447. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3448. this.handleFileSelection(item, !isChecked);
  3449. } else {
  3450. this.doPlay(item,index)
  3451. this.setShowPLayTrue()
  3452. }
  3453. })
  3454. }
  3455. Column() {
  3456. Column() {
  3457. Text(this.isShowFileName?item.fileName :item.name)
  3458. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  3459. .maxLines(1)
  3460. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  3461. .animation({
  3462. duration: 555,
  3463. curve: 'Linear',
  3464. })
  3465. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3466. $r('app.color.text_color'))
  3467. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  3468. .padding({right:25})
  3469. .bindPopup(this.longItemFilePath === item.filePath, {
  3470. builder: this.MenuBuilder(item,index,item.filePath),
  3471. placement: Placement.Top,
  3472. // autoCancel: true,
  3473. mask: {color:'#33000000'},
  3474. // popupColor: Color.Yellow,
  3475. enableArrow: false,//是否显示箭头
  3476. showInSubWindow: false,
  3477. onStateChange: (e) => {
  3478. if (!e.isVisible) {
  3479. this.longItemFilePath = ''
  3480. this.tempLyricContent = ''
  3481. }
  3482. }
  3483. })
  3484. .gesture(LongPressGesture()
  3485. .onAction(async () => {
  3486. //如果是专辑和艺术家的首页,不能长按
  3487. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  3488. return
  3489. //如果是我的收藏 最近播放等也不能长按
  3490. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3491. item.name === LocalMusic.STR_HISTORY_MUSIC
  3492. )
  3493. return
  3494. this.longItemFilePath = item.filePath
  3495. this.tempLyricContent = await this.getLyricContent(item)
  3496. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  3497. })
  3498. .onActionEnd((event: GestureEvent) => {
  3499. })
  3500. )
  3501. Row() {
  3502. Column(){
  3503. Text(item.md5Str?.includes('Lossless')?
  3504. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  3505. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  3506. .padding({ top: 3,right:6,left:6,bottom:3 })
  3507. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3508. $r('app.color.text_color'))
  3509. .fontWeight(500)
  3510. .borderRadius(12)
  3511. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  3512. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  3513. .backgroundColor('#FFC107')
  3514. }
  3515. .padding({ top: 8 })
  3516. Text(StrUtil.isEmpty(item.artist) ? item.duration
  3517. :this.twoFingerType==2? item.artist +' ' + item.duration
  3518. : item.artist + ' ' + item?.duration)
  3519. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  3520. .padding({ top: 8 ,right:25})
  3521. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  3522. .maxLines(1)
  3523. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  3524. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3525. Color.Gray)
  3526. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  3527. Blank()
  3528. Text(this.isShowFileName?item.duration:item.size)
  3529. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  3530. .padding({ top: 8 })
  3531. .maxLines(1)
  3532. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  3533. ? Visibility.Visible : Visibility.None)
  3534. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3535. Color.Gray)
  3536. .margin({ left: StrUtil.isEmpty(item.artist) ?0:10 })
  3537. }
  3538. .gesture(LongPressGesture()
  3539. .onAction(async () => {
  3540. //如果是专辑和艺术家的首页,不能长按
  3541. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  3542. return
  3543. //如果是我的收藏 最近播放等也不能长按
  3544. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3545. item.name === LocalMusic.STR_HISTORY_MUSIC
  3546. )
  3547. return
  3548. this.longItemFilePath = item.filePath
  3549. this.tempLyricContent = await this.getLyricContent(item)
  3550. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  3551. })
  3552. .onActionEnd((event: GestureEvent) => {
  3553. })
  3554. )
  3555. }
  3556. .height('100%')
  3557. .width('100%')
  3558. .margin({ right: 10 })
  3559. .justifyContent(FlexAlign.Center)
  3560. .alignItems(HorizontalAlign.Start)
  3561. }
  3562. .height('100%')
  3563. .margin({ left: 5 })
  3564. .layoutWeight(1)
  3565. Column() {
  3566. Checkbox({ name: 'checkbox' + index })
  3567. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  3568. .selectedColor(this.themeColor)
  3569. .shape(CheckBoxShape.CIRCLE)
  3570. .opacity(this.isMultiSelect ? 1 : 0)
  3571. .animation({
  3572. duration: 666,
  3573. curve: 'Smooth' // 可选动画曲线
  3574. })
  3575. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  3576. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  3577. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  3578. .width(22)
  3579. .height(22)
  3580. ImageAnimator()
  3581. .images(this.imagesF)// 动画数组
  3582. .duration(1000)// 持续
  3583. .state(this.animationState)// 动画状态
  3584. .fillMode(FillMode.Forwards)
  3585. .width(18)
  3586. .margin({ right: 20, top: 8, bottom: 8 })
  3587. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  3588. Visibility.None)
  3589. .height(18)
  3590. .iterations(-1) // 播放次数
  3591. }
  3592. }
  3593. }
  3594. .backgroundColor(Color.Transparent)
  3595. .width('100%')
  3596. .reuseId('file_item')
  3597. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  3598. }
  3599. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  3600. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  3601. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  3602. direction: Direction.Ltr,
  3603. buttonPadding:{top:12,bottom:12},
  3604. backgroundColor: Color.Transparent,
  3605. fontSize:14,
  3606. selectedFontSize:15,
  3607. selectedFontColor:Color.White,
  3608. selectedBackgroundColor: this.themeColor,
  3609. localizedTextPadding: {
  3610. end: LengthMetrics.vp(20),
  3611. start: LengthMetrics.vp(20)
  3612. }
  3613. })
  3614. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  3615. //当胶囊按钮的选择发生变化时调用此函数
  3616. capsuleSelectedIndexesChanged() {
  3617. this.modeType = this.tabSelectedIndexes[0]
  3618. }
  3619. @Builder
  3620. tabTitle() {
  3621. Column({ space: 2 }) {
  3622. SegmentButton({ options: this.tabOptions, selectedIndexes: $tabSelectedIndexes })
  3623. Line()
  3624. .width('100%')
  3625. .height(1)
  3626. .backgroundColor($r('app.color.index_background'))
  3627. .opacity(this.barOpacity)
  3628. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  3629. }
  3630. .width('100%')
  3631. .height(this.topBarHeight)
  3632. .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  3633. }
  3634. // @Builder
  3635. // tabTitle() {
  3636. // Column() {
  3637. // // 使用 Stack 布局来实现绝对定位效果
  3638. // Stack() {
  3639. // // 背景动画容器
  3640. // Row() {
  3641. // ForEach(this.tabs, (i: string, index) => {
  3642. // Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  3643. // Flex()
  3644. // .backgroundColor(this.isDarkMode ? $r('app.color.tab_item_bg') : this.themeColor)
  3645. // .borderRadius(20)
  3646. // .padding(10)
  3647. // .margin(6)
  3648. // .width('100%')
  3649. // .height('100%')
  3650. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3651. // .visibility(this.modeType === index ? Visibility.Visible : Visibility.None)
  3652. // .opacity(this.modeType === index ? 1 : 0)
  3653. // .animation({
  3654. // duration: 666,
  3655. // playMode: PlayMode.Normal,
  3656. // curve: 'ease-in-out'
  3657. // });
  3658. // }
  3659. // .layoutWeight(1)
  3660. // .margin({
  3661. // left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5,
  3662. // right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5, bottom: 1
  3663. // });
  3664. // });
  3665. // }
  3666. // .width('100%')
  3667. // .height(50);
  3668. //
  3669. // // 导航栏容器
  3670. // Row() {
  3671. // ForEach(this.tabs, (item: string, index) => {
  3672. // Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  3673. // Text(item)
  3674. // .fontSize(16)
  3675. // .fontColor(this.modeType === index ? Color.White : $r('app.color.text_color'))
  3676. // .padding(15)
  3677. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3678. // .onClick(() => {
  3679. // this.modeType = index;
  3680. // // this.onModeChange();
  3681. // });
  3682. // }
  3683. // .layoutWeight(1)
  3684. // .stateStyles({
  3685. // pressed: { opacity: 0.6 } // 按压反馈
  3686. // });
  3687. // });
  3688. // }
  3689. // .width('100%')
  3690. // .height(this.topBarHeight)
  3691. // .opacity(this.barOpacity)
  3692. // .backgroundColor(Color.Transparent);
  3693. //
  3694. // }
  3695. // .width('100%')
  3696. // .height(this.topBarHeight)
  3697. // .opacity(this.barOpacity)
  3698. //
  3699. // Line()
  3700. // .width('100%')
  3701. // .height(1)
  3702. // .backgroundColor($r('app.color.index_background'))
  3703. // .opacity(this.barOpacity)
  3704. // .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  3705. // }
  3706. // .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  3707. // }
  3708. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  3709. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  3710. isShowCoverHeader() {
  3711. if (!this.isShowHeader) {
  3712. return false
  3713. }
  3714. if (this.modeType == 0) {
  3715. if (this.isHistory || this.isFavMusic) {
  3716. return true
  3717. }
  3718. if (this.currentPath != this.rootPath) {
  3719. return true
  3720. }
  3721. }
  3722. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  3723. }
  3724. getCoverTitleBg(): ResourceStr | image.PixelMap {
  3725. if (this.isCustomizeBg) {
  3726. return ('rgba(255,255,255,0.2)')
  3727. }
  3728. if (this.isDarkMode) {
  3729. return $r('app.color.user_center_card_background')
  3730. }
  3731. return this.currentTitleCover
  3732. }
  3733. // 第二步:popup构造器定义弹框内容
  3734. @Builder popupBuilder() {
  3735. Column({ space: 2 }) {
  3736. Text('友情提示:双指缩放可以放大缩小列表')
  3737. .fontSize(12)
  3738. .fontWeight(FontWeight.Regular)
  3739. .fontColor($r('app.color.text_color'))
  3740. }
  3741. .justifyContent(FlexAlign.SpaceAround)
  3742. .width(220)
  3743. .height(55)
  3744. .padding(15)
  3745. }
  3746. //搜索功能的实现
  3747. @State searchText: string = ''; // 用户输入内容
  3748. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  3749. @State isSearchMode: boolean = false
  3750. // 实时搜索逻辑(带防抖)
  3751. private onSearchInput(value: string) {
  3752. this.searchText = value.trim();
  3753. let mSearchList: Array<VideoItem> = []
  3754. switch (this.modeType) {
  3755. case 0:
  3756. case 1:
  3757. mSearchList = this.mediaKuList
  3758. break;
  3759. case 2:
  3760. mSearchList = this.artistList
  3761. break;
  3762. case 3:
  3763. mSearchList = this.albumList
  3764. break;
  3765. default :
  3766. mSearchList = this.videoLocalList
  3767. break;
  3768. }
  3769. // 新增条件判断:空输入时显示所有数据
  3770. if (this.searchText === '') {
  3771. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  3772. } else {
  3773. this.filteredList = mSearchList.filter((item: VideoItem) => {
  3774. //支持模糊匹配和艺术家 专辑匹配
  3775. const regex = new RegExp(this.searchText.toLowerCase().replace(/\s+/g, '.*'), 'i');
  3776. return regex.test(item.name.toLowerCase())||
  3777. regex.test(item.fileName?.toLowerCase() ?? "") ||
  3778. regex.test(item.artist?.toLowerCase() ?? "") ||
  3779. regex.test(item.album?.toLowerCase() ?? "")
  3780. });
  3781. }
  3782. this.updateListData(this.filteredList);
  3783. // this.isSearchMode = false; // 根据业务需求决定是否启用
  3784. }
  3785. @State dragItem: number = -1
  3786. @State scaleItem: number = -1
  3787. @State neighborItem: number = -1
  3788. @State neighborScale: number = -1
  3789. @State offsetY: number = 0
  3790. private dragRefOffset: number = 0
  3791. private ITEM_INTV: number = 78
  3792. scaleSelect(item: number): number {
  3793. if (this.scaleItem === item) {
  3794. return 1.05
  3795. } else if (this.neighborItem === item) {
  3796. return this.neighborScale
  3797. } else {
  3798. return 1
  3799. }
  3800. }
  3801. itemMove(index: number, newIndex: number): void {
  3802. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  3803. return;
  3804. }
  3805. let tmp = this.videoLocalList.splice(index, 1);
  3806. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  3807. this.dataSource.pushArrayData(this.videoLocalList)
  3808. if(this.modeType==4&&this.playlistTable){
  3809. updateAllSongsSortOrder(this.playlistTable, this.videoLocalList,this.currentSongListID)
  3810. }
  3811. }
  3812. //瀑布流布局 支持双指缩放
  3813. @State columns: number = 2;
  3814. @State waterFlowScale: number = 1;
  3815. @State imageScale: number = 1;
  3816. @State waterFlowOpacity: number = 1;
  3817. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  3818. private columnChanged: boolean = false;
  3819. private oldColumn: number = this.columns;
  3820. private pinchTime: number = 0;
  3821. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  3822. changeColumns(scale: number) {
  3823. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  3824. this.columns--;
  3825. this.columnChanged = true;
  3826. } else if (scale < 1 && this.columns < 4) {
  3827. this.columns++;
  3828. this.columnChanged = true;
  3829. }
  3830. }
  3831. @Builder
  3832. getWaterView(){
  3833. Scroll(this.scroller) {
  3834. Column() {
  3835. Blank().height(this.topSafeHeight + 55)
  3836. WaterFlow({
  3837. scroller:this.waterScroller,
  3838. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  3839. }) {
  3840. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3841. FlowItem() {
  3842. this.MusicWaterCardItem(item,index)
  3843. }
  3844. .width('100%')
  3845. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  3846. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  3847. {
  3848. preview: MenuPreviewMode.IMAGE,
  3849. previewAnimationOptions: { scale: [0.8, 1.0] },
  3850. })
  3851. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  3852. {
  3853. preview: MenuPreviewMode.IMAGE,
  3854. previewAnimationOptions: { scale: [0.8, 1.0] },
  3855. })
  3856. .transition(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }))
  3857. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  3858. TransitionEffect.scale({ x: 0, y: 0 })))
  3859. .gesture(
  3860. GestureGroup(GestureMode.Exclusive,
  3861. SwipeGesture({ direction: SwipeDirection.Horizontal })
  3862. .onAction((event: GestureEvent) => {
  3863. if (event) {
  3864. // this.sideBarController.openSideBar()
  3865. }
  3866. }),
  3867. TapGesture({ count: 1, fingers: 1 })
  3868. .onAction(async () => {
  3869. })
  3870. )
  3871. )
  3872. }, (item: VideoItem) => item.filePath)
  3873. }
  3874. // .columnsTemplate('repeat(auto-fit, 160)')
  3875. .id('waterflow') // 设置id用于截图
  3876. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  3877. .columnsGap(12) // 列间距
  3878. .rowsGap(16) // 行间距
  3879. .cachedCount(6)
  3880. .padding({bottom:this.bottomBarHeight+10})
  3881. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3882. .animation({ duration: 500, curve: Curve.Ease }))
  3883. .scrollBar(BarState.Off)
  3884. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  3885. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  3886. .edgeEffect(EdgeEffect.Spring, { alwaysEnabled: true })
  3887. .width('90%')
  3888. .height('100%')
  3889. .opacity(this.waterFlowOpacity)
  3890. .scale({
  3891. x: this.waterFlowScale,
  3892. y: this.waterFlowScale,
  3893. centerX: 0,
  3894. centerY: 0
  3895. })
  3896. .onAppear(() => {
  3897. this.scroller.scrollEdge(Edge.Top)
  3898. })
  3899. .nestedScroll({
  3900. scrollForward: NestedScrollMode.PARENT_FIRST,
  3901. scrollBackward: NestedScrollMode.SELF_FIRST
  3902. })
  3903. .priorityGesture(
  3904. PinchGesture()
  3905. .onActionStart((event: GestureEvent) => {
  3906. // 双指捏合手势识别成功时截图
  3907. this.pinchTime = event.timestamp;
  3908. this.columnChanged = false;
  3909. this.oldColumn = this.columns;
  3910. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  3911. if (error) {
  3912. console.info('error:' + JSON.stringify(error));
  3913. return;
  3914. }
  3915. this.waterFlowSnapshot = pixmap;
  3916. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  3917. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  3918. if (this.oldColumn ===4) {
  3919. this.twoFingerType =3
  3920. this.isGridMusic = true
  3921. }else if (this.oldColumn ===1) {
  3922. this.twoFingerType =1
  3923. this.isGridMusic = false
  3924. }
  3925. return;
  3926. }
  3927. })
  3928. })
  3929. .onActionUpdate((event: GestureEvent) => {
  3930. // 手势更新:处理缩放逻辑和视觉效果
  3931. // 边界限制:防止超出列数范围时继续缩放
  3932. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  3933. return;
  3934. }
  3935. // 节流处理:避免过于频繁的更新,提升性能
  3936. if (event.timestamp - this.pinchTime < 10000000) {
  3937. return;
  3938. }
  3939. this.pinchTime = event.timestamp;
  3940. this.waterFlowScale = event.scale;
  3941. this.imageScale = event.scale;
  3942. // 根据缩放比例设置WaterFlow透明度
  3943. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  3944. this.waterFlowOpacity *= 3;
  3945. if (!this.columnChanged) {
  3946. this.changeColumns(event.scale);
  3947. }
  3948. // 列数改变后的缩放比例调整:避免出现空白区域
  3949. if (this.columnChanged) {
  3950. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  3951. // 限制缩放范围,确保视觉效果自然
  3952. if (event.scale < 1) {
  3953. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  3954. } else {
  3955. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  3956. }
  3957. }
  3958. })
  3959. .onActionEnd((event: GestureEvent) => {
  3960. // 手势结束:执行归位动画并保存状态
  3961. // 执行归位动画:平滑过渡到正常状态
  3962. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  3963. this.waterFlowScale = 1;
  3964. this.waterFlowOpacity = 1;
  3965. })
  3966. // 持久化保存当前列数:下次启动时恢复
  3967. PreferencesUtil.putSync('lastColumns', this.columns);
  3968. })
  3969. )
  3970. //允许拖拽音乐和视频到List或Grid上自动导入视频
  3971. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3972. .onDrop((event?: DragEvent) => {
  3973. try {
  3974. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3975. if (dragData !== undefined) {
  3976. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3977. if (records.length > 0) {
  3978. for (let i = 0; i < records.length; i++) {
  3979. let types = records[i].getTypes();
  3980. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3981. const fileUriUds =
  3982. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3983. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3984. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3985. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3986. this.targetFile = fileUriUds.oriUri;
  3987. this.saveVideoDatas([this.targetFile])
  3988. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3989. }
  3990. }
  3991. }
  3992. } else {
  3993. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3994. }
  3995. } else {
  3996. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3997. }
  3998. } catch (error) {
  3999. const err = error as BusinessError;
  4000. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  4001. }
  4002. })
  4003. }
  4004. }
  4005. .scrollBar(BarState.Off)
  4006. }
  4007. //瀑布流卡片布局
  4008. @Builder
  4009. private MusicWaterCardItem(item: VideoItem, index: number) {
  4010. Button({ type: ButtonType.Normal, stateEffect: false }) {
  4011. Stack() {
  4012. Column() {
  4013. Image(item.pixelMapPath)
  4014. .backgroundImageSize(ImageSize.Auto)
  4015. .borderRadius({
  4016. topLeft: 12,
  4017. topRight : 12,
  4018. bottomLeft: 0,
  4019. bottomRight: 0
  4020. })
  4021. .draggable(false)// 禁止长按手势拖动
  4022. .autoResize(true) // 重采样,可减少内存占用
  4023. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4024. .width('100%')
  4025. .height('auto')
  4026. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  4027. .objectFit(ImageFit.Auto)
  4028. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  4029. height: '99%' ,
  4030. dragBar: true,
  4031. onDisappear: () => {
  4032. this.longItemFilePath = '';
  4033. this.tempLyricContent = ''
  4034. },
  4035. showClose: true,
  4036. preferType: SheetType.CENTER ,
  4037. title: { title: '编辑标签' }
  4038. })
  4039. .draggable(false)
  4040. .opacity(this.opacityItem)// 绑定透明度
  4041. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4042. // .animation({ duration: 500, curve: Curve.Ease }))
  4043. .animation({
  4044. duration: 666,
  4045. curve: 'ease-in-out' // 可选动画曲线
  4046. })
  4047. .margin({
  4048. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4049. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4050. })
  4051. Column() {
  4052. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4053. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  4054. .maxLines(1)
  4055. .fontWeight(FontWeight.Bold)
  4056. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4057. .animation({
  4058. duration: 555,
  4059. curve: 'Linear',
  4060. })
  4061. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  4062. height: '95%',
  4063. dragBar: true,
  4064. showClose: true,
  4065. onDisappear: () => {
  4066. this.longItemFilePathDetail = '';
  4067. },
  4068. blurStyle:BlurStyle.Thin,
  4069. backgroundColor:Color.Transparent,
  4070. preferType: SheetType.CENTER ,
  4071. title: { title: '详情' }
  4072. })
  4073. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4074. $r('app.color.text_color'))
  4075. Column() {
  4076. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  4077. .fontSize(11)
  4078. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  4079. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4080. .fontColor($r('app.color.text_color'))
  4081. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  4082. .fontSize(11)
  4083. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  4084. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4085. .fontColor($r('app.color.text_color'))
  4086. Row(){
  4087. Column(){
  4088. Text(item.md5Str?.includes('Lossless')?
  4089. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4090. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  4091. .padding({ top: 3,right:6,left:6,bottom:3 })
  4092. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4093. $r('app.color.text_color'))
  4094. .fontWeight(500)
  4095. .borderRadius(12)
  4096. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4097. .backgroundColor('#FFC107')
  4098. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  4099. }
  4100. .margin({ top: 2 ,right:6})
  4101. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  4102. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  4103. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  4104. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  4105. .maxLines(1)
  4106. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4107. .margin({ top: 2})
  4108. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  4109. || item.type == CommonConstants.TYPE_IS_ALBUM
  4110. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4111. .fontWeight(FontWeight.Medium)
  4112. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4113. $r('app.color.text_color'))
  4114. }
  4115. }
  4116. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  4117. }
  4118. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  4119. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  4120. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  4121. .width('100%')
  4122. .justifyContent(FlexAlign.Center)
  4123. .margin({
  4124. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4125. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4126. })
  4127. }
  4128. .width('100%')
  4129. .borderRadius(12)
  4130. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  4131. .backgroundImageSize({ height: '100%', width: '100%' })
  4132. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  4133. .animation({ curve: Curve.Sharp, duration: 300 })
  4134. Checkbox({ name: 'checkbox' + index })
  4135. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  4136. .selectedColor(this.themeColor)
  4137. .shape(CheckBoxShape.CIRCLE)
  4138. .opacity(this.isMultiSelect ? 1 : 0)
  4139. .animation({
  4140. duration: 666,
  4141. curve: 'Smooth' // 可选动画曲线
  4142. })
  4143. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  4144. Visibility.None)
  4145. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  4146. .margin({ left: 20, top: 8, bottom: 8 })
  4147. .width(38)
  4148. .height(38)
  4149. }
  4150. }
  4151. .backgroundColor(Color.Transparent)
  4152. .width('100%')
  4153. .height('auto')
  4154. .padding({top:2})
  4155. .shadow({
  4156. radius: 10,
  4157. type: ShadowType.BLUR,
  4158. color: 'on_primary'
  4159. })
  4160. .reuseId('card_item')
  4161. .onClick(() => {
  4162. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  4163. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4164. this.handleFileSelection(item, !isChecked);
  4165. } else {
  4166. this.doPlay(item, index)
  4167. }
  4168. })
  4169. }
  4170. // Grid布局的开始
  4171. private dragRefOffSetX: number = 0;
  4172. private dragRefOffSetY: number = 0;
  4173. private FIX_VP_X: number = 180;
  4174. private FIX_VP_Y: number = 84;
  4175. isDraggable(index: number): boolean {
  4176. return index >= 0;
  4177. }
  4178. getRowEnd(item: number) {
  4179. if (item.toString() === '0') {
  4180. return 1;
  4181. } else {
  4182. return 0;
  4183. }
  4184. }
  4185. isInLeft(index: number) {
  4186. return index % 2 == 0;
  4187. }
  4188. down(index: number): void {
  4189. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  4190. return;
  4191. }
  4192. this.offsetY -= this.FIX_VP_Y;
  4193. this.dragRefOffSetY += this.FIX_VP_Y;
  4194. this.itemMove(index, index + 1);
  4195. }
  4196. up(index: number): void {
  4197. if (!this.isDraggable(index - 2)) {
  4198. return;
  4199. }
  4200. this.offsetY += this.FIX_VP_Y;
  4201. this.dragRefOffSetY -= this.FIX_VP_Y;
  4202. this.itemMove(index, index - 1);
  4203. }
  4204. left(index: number): void {
  4205. if (this.isInLeft(index)) {
  4206. return;
  4207. }
  4208. if (!this.isDraggable(index - 1)) {
  4209. return;
  4210. }
  4211. this.offsetX += this.FIX_VP_X;
  4212. this.dragRefOffSetX -= this.FIX_VP_X;
  4213. this.itemMove(index, index - 1)
  4214. }
  4215. right(index: number): void {
  4216. if (!this.isInLeft(index)) {
  4217. return;
  4218. }
  4219. if (!this.isDraggable(index + 1)) {
  4220. return;
  4221. }
  4222. this.offsetX -= this.FIX_VP_X;
  4223. this.dragRefOffSetX += this.FIX_VP_X;
  4224. this.itemMove(index, index + 1)
  4225. }
  4226. private scroller: Scroller = new Scroller();
  4227. private waterScroller: Scroller = new Scroller();
  4228. @State startIndex: number = 0
  4229. @State endIndex: number = 0
  4230. @State scaleValue: number = 1
  4231. @State pinchValue: number = 1
  4232. layoutOptionsForHeader: GridLayoutOptions = {
  4233. regularSize: [1, 1], // 只支持[1, 1]
  4234. irregularIndexes: [0], // 索引为0的GridItem占用一行
  4235. };
  4236. @Builder
  4237. getGridView() {
  4238. Grid(this.scroller, this.layoutOptionsForHeader) {
  4239. GridItem() {
  4240. Column(){
  4241. Blank().height(this.topSafeHeight + 45)
  4242. }
  4243. }
  4244. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  4245. GridItem() {
  4246. Stack({ alignContent: Alignment.Center }) {
  4247. this.MusicItemGrid(item, index)
  4248. }
  4249. }
  4250. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  4251. {
  4252. preview: MenuPreviewMode.IMAGE,
  4253. previewAnimationOptions: { scale: [0.8, 1.0] },
  4254. })
  4255. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  4256. {
  4257. preview: MenuPreviewMode.IMAGE,
  4258. previewAnimationOptions: { scale: [0.8, 1.0] },
  4259. })
  4260. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  4261. TransitionEffect.scale({ x: 0, y: 0 })))
  4262. .clickEffect({ level: ClickEffectLevel.LIGHT })
  4263. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  4264. .zIndex(this.dragItem === index ? 1 : 0)
  4265. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  4266. }, (item: VideoItem) => item.filePath)
  4267. }
  4268. .width('94%')
  4269. .height('100%')
  4270. .editMode(true)
  4271. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4272. .animation({ duration: 500, curve: Curve.Ease }))
  4273. .padding({bottom:this.bottomBarHeight+this.bottomSafeHeight+10})
  4274. .reuseId('grid_item')
  4275. .layoutWeight(1)
  4276. .scrollBar(BarState.Off)
  4277. .supportAnimation(true)
  4278. .cachedCount(this.twoFingerType==1?5:this.twoFingerType==2?4:3)
  4279. .columnsTemplate(
  4280. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  4281. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  4282. )
  4283. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  4284. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  4285. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  4286. .gesture(PinchGesture({ fingers: 2 })
  4287. .onActionEnd((event: GestureEvent) => {
  4288. this.setGridTwoFingers()
  4289. })
  4290. .onActionUpdate(e => {
  4291. this.scaleValue = this.pinchValue * e.scale
  4292. })
  4293. .onActionStart(e => {
  4294. }))
  4295. .enableScrollInteraction(true)
  4296. .onScrollIndex((start: number, end: number) => {
  4297. this.startIndex = start
  4298. this.endIndex = end
  4299. })
  4300. .onScrollFrameBegin((offset: number) => {
  4301. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  4302. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  4303. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  4304. if (this.isScrollHide) {
  4305. this.setBarHeightHide2(offset)
  4306. } else {
  4307. this.setBarHeightNormal()
  4308. }
  4309. } else {
  4310. this.setBarHeightHide(offset)
  4311. }
  4312. return { offsetRemain: offset };
  4313. })
  4314. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  4315. .onDrop((event?: DragEvent) => {
  4316. try {
  4317. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  4318. if (dragData !== undefined) {
  4319. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  4320. if (records.length > 0) {
  4321. for (let i = 0; i < records.length; i++) {
  4322. let types = records[i].getTypes();
  4323. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  4324. const fileUriUds =
  4325. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  4326. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  4327. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  4328. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  4329. this.targetFile = fileUriUds.oriUri;
  4330. this.saveVideoDatas([this.targetFile])
  4331. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  4332. }
  4333. }
  4334. }
  4335. } else {
  4336. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  4337. }
  4338. } else {
  4339. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  4340. }
  4341. } catch (error) {
  4342. const err = error as BusinessError;
  4343. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  4344. }
  4345. })
  4346. }
  4347. @State targetFile: string = '';
  4348. setGridTwoFingers() {
  4349. this.pinchValue = this.scaleValue;
  4350. Logger.info('this.pinchValue = ' + this.pinchValue);
  4351. if (this.pinchValue >= 1) {
  4352. this.twoFingerType++
  4353. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  4354. if(this.twoFingerType >= 4){
  4355. this.twoFingerType = 4//切换成瀑布流
  4356. this.columns = 4
  4357. }
  4358. } else {
  4359. this.twoFingerType--
  4360. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  4361. if (this.twoFingerType < 1) {
  4362. this.twoFingerType = 3
  4363. this.isGridMusic = false
  4364. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4365. }
  4366. }
  4367. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  4368. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4369. this.pinchValue = 1;
  4370. this.scaleValue = 1;
  4371. }
  4372. @State longItemFilePath: string = ''
  4373. @State tempLyricContent: string = ''
  4374. @Builder
  4375. private MusicItemGrid(item: VideoItem, index: number) {
  4376. Button({ type: ButtonType.Normal, stateEffect: false }) {
  4377. Stack() {
  4378. Column() {
  4379. Image(item.pixelMapPath)
  4380. .height(this.getGridHeight())
  4381. .width(this.getGridWight())
  4382. .draggable(false)
  4383. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4384. .autoResize(true) // 重采样,可减少内存占用
  4385. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  4386. .clip(true)
  4387. .borderRadius({
  4388. topLeft: 12,
  4389. topRight: 12,
  4390. bottomLeft: 0,
  4391. bottomRight: 0
  4392. })
  4393. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  4394. height: '99%' ,
  4395. dragBar: true,
  4396. onDisappear: () => {
  4397. this.longItemFilePath = '';
  4398. this.tempLyricContent = ''
  4399. },
  4400. showClose: true,
  4401. preferType: SheetType.CENTER ,
  4402. title: { title: '编辑标签' }
  4403. })
  4404. .draggable(false)
  4405. .opacity(this.opacityItem)// 绑定透明度
  4406. .animation({
  4407. duration: 666,
  4408. curve: 'ease-in-out' // 可选动画曲线
  4409. })
  4410. .margin({
  4411. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4412. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4413. })
  4414. Column() {
  4415. Text(this.isShowFileName&&item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4416. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4417. .maxLines(1)
  4418. .fontWeight(FontWeight.Bold)
  4419. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4420. .animation({
  4421. duration: 555,
  4422. curve: 'Linear',
  4423. })
  4424. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  4425. height: '95%',
  4426. dragBar: true,
  4427. showClose: true,
  4428. onDisappear: () => {
  4429. this.longItemFilePathDetail = '';
  4430. },
  4431. blurStyle:BlurStyle.Thin,
  4432. backgroundColor:Color.Transparent,
  4433. preferType: SheetType.CENTER ,
  4434. title: { title: '详情' }
  4435. })
  4436. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4437. $r('app.color.text_color'))
  4438. Column() {
  4439. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  4440. .fontSize(11)
  4441. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  4442. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4443. .fontColor($r('app.color.text_color'))
  4444. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  4445. .fontSize(11)
  4446. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  4447. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4448. .fontColor($r('app.color.text_color'))
  4449. Row(){
  4450. Column(){
  4451. Text(item.md5Str?.includes('Lossless')?
  4452. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4453. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  4454. .padding({ top: 3,right:6,left:6,bottom:3 })
  4455. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4456. $r('app.color.text_color'))
  4457. .fontWeight(500)
  4458. .borderRadius(12)
  4459. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4460. .backgroundColor('#FFC107')
  4461. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  4462. }
  4463. .margin({ top: 2 ,right:6})
  4464. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  4465. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  4466. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  4467. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  4468. .maxLines(1)
  4469. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4470. .margin({ top: 2})
  4471. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  4472. || item.type == CommonConstants.TYPE_IS_ALBUM
  4473. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4474. .fontWeight(FontWeight.Medium)
  4475. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4476. $r('app.color.text_color'))
  4477. }
  4478. }
  4479. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  4480. }
  4481. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  4482. .width(this.getGridWight())
  4483. .justifyContent(FlexAlign.Center)
  4484. .margin({
  4485. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4486. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4487. })
  4488. }
  4489. .width(this.getGridWight())
  4490. .borderRadius(12)
  4491. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?undefined:item.pixelMapPath)
  4492. .backgroundImageSize({ height: '100%', width: '100%' })
  4493. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  4494. .animation({ curve: Curve.Sharp, duration: 300 })
  4495. Checkbox({ name: 'checkbox' + index })
  4496. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  4497. .selectedColor(this.themeColor)
  4498. .shape(CheckBoxShape.CIRCLE)
  4499. .opacity(this.isMultiSelect ? 1 : 0)
  4500. .animation({
  4501. duration: 666,
  4502. curve: 'Smooth' // 可选动画曲线
  4503. })
  4504. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  4505. Visibility.None)
  4506. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  4507. .margin({ left: 20, top: 8, bottom: 8 })
  4508. .width(38)
  4509. .height(38)
  4510. }
  4511. }
  4512. .backgroundColor(Color.Transparent)
  4513. .width('100%')
  4514. .padding({ top: 15 })
  4515. .height(this.getGridAllHeight())
  4516. .onClick(() => {
  4517. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  4518. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4519. this.handleFileSelection(item, !isChecked);
  4520. } else {
  4521. this.doPlay(item, index)
  4522. }
  4523. })
  4524. }
  4525. getGridAllHeight() {
  4526. let heightG = 222
  4527. switch (this.twoFingerType) {
  4528. case 1:
  4529. heightG = 143
  4530. break;
  4531. case 2:
  4532. heightG = 178
  4533. break;
  4534. case 3:
  4535. heightG = 222
  4536. break;
  4537. }
  4538. return heightG
  4539. }
  4540. getGridHeight() {
  4541. let heightG = 150
  4542. switch (this.twoFingerType) {
  4543. case 1:
  4544. heightG = 80
  4545. break;
  4546. case 2:
  4547. heightG = 110
  4548. break;
  4549. case 3:
  4550. heightG = 150
  4551. break;
  4552. }
  4553. return heightG
  4554. }
  4555. getGridWight() {
  4556. let wightG = 158
  4557. switch (this.twoFingerType) {
  4558. case 1:
  4559. wightG = 80
  4560. break;
  4561. case 2:
  4562. wightG = 110
  4563. break;
  4564. case 3:
  4565. wightG = 158
  4566. break;
  4567. }
  4568. return wightG
  4569. }
  4570. @State isShowDetail:boolean = false
  4571. @State longItemFilePathDetail:string =''
  4572. @Builder
  4573. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  4574. if(
  4575. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4576. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4577. item.name === LocalMusic.STR_HISTORY_MUSIC)
  4578. ){
  4579. //如果是专辑和艺术家的首页,不能长按
  4580. //如果是我的收藏 最近播放等也不能长按
  4581. }else{
  4582. Scroll() {
  4583. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  4584. Menu() {
  4585. MenuItem({
  4586. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  4587. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  4588. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  4589. })
  4590. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4591. .onClick(() => {
  4592. if (item) {
  4593. this.doFav(item)
  4594. }
  4595. this.longItemFilePath = ''
  4596. })
  4597. MenuItem({
  4598. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  4599. content: '下一首播放'
  4600. })
  4601. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4602. .onClick(() => {
  4603. this.addToNextPlay(item);
  4604. this.longItemFilePath = ''
  4605. })
  4606. MenuItem({
  4607. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  4608. content: '添加到歌单'
  4609. })
  4610. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4611. .onClick(async () => {
  4612. this.longItemFilePath = ''
  4613. await this.openAddToPlaylistDialog(item)
  4614. })
  4615. MenuItem({
  4616. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  4617. content: '编辑标签'
  4618. })
  4619. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  4620. height: '99%',
  4621. dragBar: true,
  4622. showClose: true,
  4623. preferType: SheetType.CENTER ,
  4624. title: { title: '编辑标签' }
  4625. })
  4626. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4627. .onClick(async() => {
  4628. this.setEditStrEmpty()
  4629. this.tempLyricContent = await this.getLyricContent(item);
  4630. if(this.isGridMusic||this.twoFingerType==4){
  4631. this.longItemFilePath = item.filePath
  4632. }else{
  4633. this.isShowEdit = !this.isShowEdit;
  4634. }
  4635. })
  4636. MenuItem({
  4637. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  4638. content: $r('app.string.select_all')
  4639. })
  4640. .onClick(() => {
  4641. this.isMultiSelect = !this.isMultiSelect
  4642. this.longItemFilePath = ''
  4643. this.selectedFiles.push(item)
  4644. })
  4645. MenuItem({
  4646. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.cut')),
  4647. content: $r('app.string.edit_audio')
  4648. })
  4649. .bindContentCover($$this.isEditAudio, this.EditAudioBuilder(item), {
  4650. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  4651. })
  4652. .onClick(() => {
  4653. this.isEditAudio = !this.isEditAudio
  4654. })
  4655. MenuItem({
  4656. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  4657. content: $r('app.string.extract_accompaniment')
  4658. })
  4659. .bindContentCover($$this.isExtractAcc, this.ExtractAccBuilder(item), {
  4660. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  4661. })
  4662. .onClick(() => {
  4663. if (!Utility.isNoble()) {
  4664. this.showVipDialog()
  4665. return
  4666. }
  4667. this.isExtractAcc = !this.isExtractAcc
  4668. })
  4669. MenuItem({
  4670. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.repeat')),
  4671. content: $r('app.string.converter_audio')
  4672. })
  4673. .bindContentCover($$this.isConverter, this.ConverterBuilder(item), {
  4674. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  4675. })
  4676. .onClick(() => {
  4677. if (!Utility.isNoble()) {
  4678. this.showVipDialog()
  4679. return
  4680. }
  4681. this.isConverter = !this.isConverter
  4682. })
  4683. MenuItem({
  4684. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.ai_edit')),
  4685. content: $r('app.string.vocal_separation')
  4686. })
  4687. .bindContentCover($$this.isAIVoiceSeparation, this.AiBuilder(item), {
  4688. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  4689. })
  4690. .onClick(() => {
  4691. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  4692. })
  4693. if(Utility.isVideoByExtension(item.filePath)){
  4694. MenuItem({
  4695. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.identify_song')),
  4696. content: $r('app.string.extract_audio')
  4697. })
  4698. .bindContentCover($$this.isExtractAudio, this.extractAudioFromVideoBuilder(item), {
  4699. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  4700. })
  4701. .onClick(() => {
  4702. this.isExtractAudio = !this.isExtractAudio
  4703. })
  4704. }
  4705. MenuItem({
  4706. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.phone')),
  4707. content: $r('app.string.set_ring')
  4708. })
  4709. .onClick(async () => {
  4710. await PermissionUtil.activatePermission(item.filePath)
  4711. // if(item.filePath.includes(this.packName)){
  4712. setRingTone(this.context, item.filePath,item.name)
  4713. // }else{
  4714. // ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限设置铃声')
  4715. // }
  4716. this.longItemFilePath = ''
  4717. })
  4718. MenuItem({
  4719. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  4720. content: $r('app.string.rename')
  4721. })
  4722. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  4723. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4724. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  4725. .onClick(() => {
  4726. this.showReNameDialog(item, index + '', filePath)
  4727. this.longItemFilePath = ''
  4728. })
  4729. MenuItem({
  4730. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  4731. content: $r('app.string.delete')
  4732. })
  4733. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  4734. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4735. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  4736. .onClick(() => {
  4737. this.selectedFiles.push(item)
  4738. this.showWarnIsDelete()
  4739. this.longItemFilePath = ''
  4740. })
  4741. MenuItem({
  4742. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  4743. content: $r('app.string.detail')
  4744. })
  4745. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  4746. height:'95%',
  4747. dragBar: true,
  4748. showClose: true,
  4749. blurStyle:BlurStyle.Thin,
  4750. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  4751. backgroundColor:Color.Transparent,
  4752. title: { title: '详情信息' }
  4753. })
  4754. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4755. .onClick(() => {
  4756. if(this.isGridMusic||this.twoFingerType==4){
  4757. this.longItemFilePathDetail = item.filePath
  4758. }else{
  4759. this.isShowDetail = !this.isShowDetail
  4760. }
  4761. })
  4762. MenuItem({
  4763. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  4764. content: $r('app.string.share')
  4765. })
  4766. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4767. .onClick(() => {
  4768. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  4769. this.longItemFilePath = ''
  4770. })
  4771. }
  4772. .font({ size: 15, weight: FontWeight.Normal })
  4773. }
  4774. .width(180)
  4775. }
  4776. .height('auto')
  4777. }
  4778. }
  4779. private listMaxScrollOffsetY: number = 0
  4780. @State selectedIndex: number = -1
  4781. setlistTwoFingers() {
  4782. this.pinchValue = this.scaleValue;
  4783. Logger.info('this.pinchValue = ' + this.pinchValue);
  4784. if (this.pinchValue >= 1) {
  4785. this.twoFingerType++
  4786. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  4787. if (this.twoFingerType > 3) {
  4788. this.twoFingerType = 1
  4789. this.isGridMusic = true
  4790. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4791. }
  4792. } else {
  4793. this.twoFingerType--
  4794. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  4795. if (this.twoFingerType < 1) {
  4796. this.twoFingerType = 4
  4797. this.columns = 1
  4798. }
  4799. }
  4800. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  4801. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4802. this.pinchValue = 1;
  4803. this.scaleValue = 1;
  4804. }
  4805. @Builder
  4806. getList(){
  4807. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  4808. this.getListView()
  4809. }
  4810. .pullDownRatio(this.ratioL)
  4811. .pullToRefresh(true)
  4812. .refreshOffset(0)
  4813. .onOffsetChange((offset: number) => {
  4814. // 越接近最大距离,下拉跟手系数越小。
  4815. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  4816. })
  4817. .onStateChange((refreshStatus: RefreshStatus) => {
  4818. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  4819. })
  4820. .onRefreshing(async () => {
  4821. if(this.modeType==0){
  4822. this.getHistoryList(false)
  4823. this.asyncCurrentPathOnlyFile()
  4824. }else if(this.modeType == 1){
  4825. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  4826. }else if(this.modeType == 2){
  4827. workerInstance.postMessage({ code: 3, data: this.context });
  4828. }else if(this.modeType == 3){
  4829. workerInstance.postMessage({ code: 4, data: this.context });
  4830. }else if(this.modeType == 4){
  4831. this.doSongListTask()
  4832. }
  4833. console.log('onRefreshing test');
  4834. })
  4835. }
  4836. // 扫描当前目录下的文件,不扫描子目录
  4837. asyncCurrentPathOnlyFile(){
  4838. if(this.modeType==0){
  4839. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  4840. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  4841. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  4842. if(this.modeType==0){
  4843. setTimeout(()=>{
  4844. this.isRefreshing =false
  4845. this.deleteCache(this.currentPath)
  4846. this.getSortedFiles(this.currentPath)
  4847. },500)
  4848. }
  4849. }).catch((e:object)=>{
  4850. this.isRefreshing =false
  4851. console.info("onecold task1 catch e: " + e);
  4852. })
  4853. }
  4854. }
  4855. @Builder
  4856. getListView() {
  4857. List({ scroller: this.listScroller }) {
  4858. // ListItemGroup({ header: this.coverHeader() }) {
  4859. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  4860. ListItem() {
  4861. Column() {
  4862. if (item.type === CommonConstants.TYPE_IS_DIR
  4863. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  4864. this.DirItem(item, index)
  4865. } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
  4866. } else {
  4867. this.MusicItem(item, index)
  4868. }
  4869. }
  4870. .shadow(this.scaleItem === index ? {
  4871. radius: 70,
  4872. color: '#15000000',
  4873. offsetX: 0,
  4874. offsetY: 0
  4875. } :
  4876. {
  4877. radius: 0,
  4878. color: '#15000000',
  4879. offsetX: 0,
  4880. offsetY: 0
  4881. })
  4882. .animation({ curve: Curve.Sharp, duration: 300 })
  4883. }
  4884. // .transition(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }))
  4885. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.9, y: 0.9 })
  4886. .animation({ duration: 500 }),
  4887. TransitionEffect.scale({ x: 0, y: 0 })))
  4888. .clickEffect({ level: ClickEffectLevel.LIGHT })
  4889. .swipeAction((
  4890. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  4891. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  4892. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  4893. start:null,edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  4894. .onClick(() => {
  4895. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  4896. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4897. this.handleFileSelection(item, !isChecked);
  4898. } else {
  4899. this.doPlay(item, index)
  4900. }
  4901. })
  4902. //拖动List关键代码开始
  4903. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  4904. .zIndex(this.dragItem === index ? 1 : 0)
  4905. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  4906. .gesture(
  4907. GestureGroup(GestureMode.Sequence,
  4908. LongPressGesture({ repeat: true })
  4909. .onAction((event?: GestureEvent) => {
  4910. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  4911. this.scaleItem = index
  4912. })
  4913. })
  4914. .onActionEnd(() => {
  4915. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  4916. this.scaleItem = -1
  4917. })
  4918. }),
  4919. PanGesture({ fingers: 1, direction: null, distance: 0 })
  4920. .onActionStart(() => {
  4921. this.dragItem = index // 记录当前拖动项索引
  4922. this.dragRefOffset = 0 // 重置偏移基准
  4923. })
  4924. .onActionUpdate((event: GestureEvent) => {
  4925. this.offsetY = event.offsetY - this.dragRefOffset;
  4926. this.neighborItem = -1;
  4927. let indexA = this.videoLocalList.indexOf(item);
  4928. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  4929. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  4930. let value: number = 0;
  4931. if (this.offsetY < 0) {
  4932. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  4933. this.neighborItem = indexA - 1;
  4934. this.neighborScale = 1 - value / 20;
  4935. } else if (this.offsetY > 0) {
  4936. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  4937. this.neighborItem = indexA + 1;
  4938. this.neighborScale = 1 - value / 20;
  4939. }
  4940. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  4941. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4942. this.offsetY -= this.ITEM_INTV;
  4943. this.dragRefOffset += this.ITEM_INTV;
  4944. this.itemMove(indexA, indexA + 1);
  4945. });
  4946. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  4947. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4948. this.offsetY += this.ITEM_INTV;
  4949. this.dragRefOffset -= this.ITEM_INTV;
  4950. this.itemMove(indexA, indexA - 1);
  4951. });
  4952. }
  4953. let curListOffset = this.listScroller.currentOffset()
  4954. // 获取手指信息
  4955. let fingerInfo = event.fingerList[0]
  4956. let clickPercentY =
  4957. (fingerInfo.globalY - Number(this.listArea.globalPosition.y)) / Number(this.listArea.height)
  4958. if (clickPercentY > 0.8 && !this.listScroller.isAtEnd()) {
  4959. let scrollVelocity = clickPercentY > 0.9 ? 4 : 2
  4960. if (this.listMaxScrollOffsetY - curListOffset.yOffset > scrollVelocity + 5) {
  4961. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset += scrollVelocity })
  4962. }
  4963. } else if (clickPercentY < 0.2 && curListOffset.yOffset >= 0) {
  4964. let scrollVelocity = clickPercentY < 0.1 ? 4 : 2
  4965. if (curListOffset.yOffset > scrollVelocity + 5) {
  4966. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset -= scrollVelocity })
  4967. }
  4968. }
  4969. })
  4970. .onActionEnd((event: GestureEvent) => {
  4971. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4972. this.dragItem = -1
  4973. this.neighborItem = -1
  4974. })
  4975. animateTo({
  4976. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  4977. }, () => {
  4978. this.scaleItem = -1
  4979. })
  4980. })
  4981. )
  4982. .onCancel(() => {
  4983. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4984. this.dragItem = -1
  4985. this.neighborItem = -1
  4986. })
  4987. animateTo({
  4988. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  4989. }, () => {
  4990. this.scaleItem = -1
  4991. })
  4992. })
  4993. ) //拖动List关键代码结束
  4994. }, (item: VideoItem) => item.filePath)
  4995. // }
  4996. }
  4997. .scrollBar(BarState.Off)
  4998. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  4999. .gesture(PinchGesture({ fingers: 2 })
  5000. .onActionEnd((event: GestureEvent) => {
  5001. this.setlistTwoFingers()
  5002. })
  5003. .onActionUpdate(e => {
  5004. this.scaleValue = this.pinchValue * e.scale
  5005. })
  5006. .onActionStart(e => {
  5007. }))
  5008. .contentStartOffset(this.topSafeHeight + 55)
  5009. .scrollBar(BarState.Off)
  5010. .contentEndOffset(this.bottomBarHeight+this.bottomSafeHeight)
  5011. .cachedCount(10)
  5012. // .reuseId('list_item')
  5013. .borderRadius(20)
  5014. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.9, y: 0.9 }).animation({ duration: 400 }),
  5015. // TransitionEffect.scale({ x: 0, y: 0 })))
  5016. .layoutWeight(1)
  5017. .onScrollIndex((start) => {
  5018. this.selectedIndex = start
  5019. })
  5020. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  5021. .lanes(
  5022. new BreakpointType<number>({
  5023. sm: 1,
  5024. md: 2,
  5025. lg: 2,
  5026. xl: 3,
  5027. xxl: 4
  5028. }).getValue(this.currentBreakpoint),
  5029. new BreakpointType<number>({
  5030. sm: 0,
  5031. md: 12,
  5032. lg: 12,
  5033. xl: 16,
  5034. xxl: 20
  5035. }).getValue(this.currentBreakpoint)
  5036. )
  5037. .onAreaChange((oldValue: Area, newValue: Area) => {
  5038. this.listArea = newValue
  5039. if (this.twoFingerType == 3) {
  5040. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  5041. } else if (this.twoFingerType == 2) {
  5042. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  5043. } else if (this.twoFingerType == 1) {
  5044. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  5045. }
  5046. })
  5047. .onScrollFrameBegin((offset: number) => {
  5048. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  5049. // if (this.isPhoneLan()) {
  5050. // this.setBarHeightHide(offset)
  5051. // } else
  5052. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  5053. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  5054. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  5055. if (this.isScrollHide) {
  5056. this.setBarHeightHide2(offset)
  5057. } else {
  5058. this.setBarHeightNormal()
  5059. }
  5060. } else {
  5061. this.setBarHeightHide(offset)
  5062. }
  5063. return { offsetRemain: offset };
  5064. })
  5065. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  5066. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  5067. .onDrop((event?: DragEvent) => {
  5068. try {
  5069. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  5070. if (dragData !== undefined) {
  5071. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  5072. if (records.length > 0) {
  5073. for (let i = 0; i < records.length; i++) {
  5074. let types = records[i].getTypes();
  5075. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  5076. const fileUriUds =
  5077. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  5078. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  5079. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  5080. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  5081. this.targetFile = fileUriUds.oriUri;
  5082. this.saveVideoDatas([this.targetFile])
  5083. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  5084. }
  5085. }
  5086. }
  5087. } else {
  5088. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  5089. }
  5090. } else {
  5091. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  5092. }
  5093. } catch (error) {
  5094. const err = error as BusinessError;
  5095. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  5096. }
  5097. })
  5098. }
  5099. setBarHeightNormal() {
  5100. this.hideDone = false;
  5101. this.getUIContext().animateTo({
  5102. duration: 300
  5103. }, () => {
  5104. this.bottomBarHeight = 68 + 0;
  5105. this.topBarHeight = 50 + 0;
  5106. this.barOpacity = 1;
  5107. this.barBottomOpacity = 1
  5108. this.currentYOffset = 0;
  5109. this.isHiding = false;
  5110. });
  5111. }
  5112. setBarHeightHide(offset: number) {
  5113. if (offset > 0 && !this.hideDone) {
  5114. this.currentYOffset += offset;
  5115. if (this.currentYOffset <= 100) {
  5116. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  5117. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  5118. this.barOpacity = 1 - this.currentYOffset / 100;
  5119. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  5120. } else {
  5121. this.topBarHeight = 0;
  5122. this.bottomBarHeight = 0;
  5123. this.barBottomOpacity = 0
  5124. this.barOpacity = 0;
  5125. this.hideDone = true;
  5126. }
  5127. this.isHiding = true;
  5128. }
  5129. if (offset < 0 && this.isHiding) {
  5130. this.hideDone = false;
  5131. this.getUIContext().animateTo({
  5132. duration: 300
  5133. }, () => {
  5134. this.bottomBarHeight = 68 + 0;
  5135. this.topBarHeight = 50 + 0;
  5136. this.barOpacity = 1;
  5137. this.barBottomOpacity = 1
  5138. this.currentYOffset = 0;
  5139. this.isHiding = false;
  5140. });
  5141. }
  5142. }
  5143. //这个方法没隐藏bottomBar,只隐藏topbar
  5144. setBarHeightHide2(offset: number) {
  5145. if (offset > 0 && !this.hideDone) {
  5146. this.currentYOffset += offset;
  5147. if (this.currentYOffset <= 100) {
  5148. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  5149. this.barOpacity = 1 - this.currentYOffset / 100;
  5150. } else {
  5151. this.topBarHeight = 0;
  5152. this.barOpacity = 0;
  5153. this.hideDone = true;
  5154. }
  5155. this.isHiding = true;
  5156. }
  5157. if (offset < 0 && this.isHiding) {
  5158. this.hideDone = false;
  5159. this.getUIContext().animateTo({
  5160. duration: 300
  5161. }, () => {
  5162. this.topBarHeight = 50 + 0;
  5163. this.barOpacity = 1;
  5164. this.currentYOffset = 0;
  5165. this.isHiding = false;
  5166. });
  5167. }
  5168. }
  5169. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  5170. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  5171. switch (item.type) {
  5172. case CommonConstants.TYPE_IS_DIR:
  5173. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  5174. let offsetB = 0
  5175. if(this.twoFingerType==4){
  5176. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  5177. let cur = this.waterScroller.currentOffset()
  5178. if (cur && typeof cur.yOffset === 'number') {
  5179. offsetB = cur.yOffset
  5180. }
  5181. }
  5182. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  5183. }else
  5184. if (this.isGridMusic) {
  5185. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  5186. let cur = this.scroller.currentOffset()
  5187. if (cur && typeof cur.yOffset === 'number') {
  5188. offsetB = cur.yOffset
  5189. }
  5190. }
  5191. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  5192. } else {
  5193. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  5194. let cur = this.listScroller.currentOffset()
  5195. if (cur && typeof cur.yOffset === 'number') {
  5196. offsetB = cur.yOffset
  5197. }
  5198. }
  5199. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  5200. }
  5201. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  5202. this.showVerifyDialog()
  5203. this.currentTitleName = '私密音频'
  5204. this.currentTitleCover = $r('app.media.ic_avatar1')
  5205. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  5206. this.titleName = '最近播放'
  5207. this.currentTitleCover = $r('app.media.alt')
  5208. this.currentTitleName = '最近播放'
  5209. //加载动画效果
  5210. this.updateListData(this.historyList, true)
  5211. // this.videoLocalList = this.historyList
  5212. if (ArrayUtil.isEmpty(this.historyList)) {
  5213. ToastUtil.showToast('最近播放记录空空如也')
  5214. } else {
  5215. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  5216. }
  5217. this.isHistory = true
  5218. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  5219. this.titleName = '我的收藏'
  5220. this.currentTitleName = '我的收藏'
  5221. this.currentTitleCover = $r('app.media.ic_avatar1')
  5222. //加载动画效果
  5223. this.updateListData(this.favList)
  5224. if (ArrayUtil.isEmpty(this.favList)) {
  5225. ToastUtil.showToast('无音乐收藏记录')
  5226. } else {
  5227. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  5228. }
  5229. this.isFavMusic = true
  5230. } else {
  5231. this.currentTitleName = item.name
  5232. this.currentPath = item.filePath
  5233. this.currentTitleCover = $r('app.media.ic_avatar1')
  5234. this.getSortedFiles(this.currentPath)
  5235. }
  5236. //进入歌单的时候的滚动位置在顶部
  5237. if(this.twoFingerType==4){
  5238. setTimeout(() => {
  5239. this.waterScroller.scrollEdge(Edge.Top)
  5240. this.scroller.scrollEdge(Edge.Top)
  5241. }, 380)
  5242. }else{
  5243. if (this.isGridMusic) {
  5244. this.scroller.scrollEdge(Edge.Top)
  5245. }else{
  5246. this.listScroller.scrollEdge(Edge.Top)
  5247. }
  5248. }
  5249. this.rightTopImage = $r('sys.symbol.chevron_left')
  5250. break;
  5251. case CommonConstants.TYPE_IS_ARTIST:
  5252. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  5253. let offsetA = 0
  5254. if(this.twoFingerType==4){
  5255. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  5256. let cur = this.waterScroller.currentOffset()
  5257. if (cur && typeof cur.yOffset === 'number') {
  5258. offsetA = cur.yOffset
  5259. }
  5260. }
  5261. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  5262. }else
  5263. if (this.isGridMusic) {
  5264. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  5265. let cur = this.scroller.currentOffset()
  5266. if (cur && typeof cur.yOffset === 'number') {
  5267. offsetA = cur.yOffset
  5268. }
  5269. }
  5270. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  5271. } else {
  5272. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  5273. let cur = this.listScroller.currentOffset()
  5274. if (cur && typeof cur.yOffset === 'number') {
  5275. offsetA = cur.yOffset
  5276. }
  5277. }
  5278. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  5279. }
  5280. let mList = this.artistMap.get(item.name)
  5281. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  5282. Utility.doSortListAscending(mList)
  5283. this.isCanBack = true
  5284. this.titleName = item.name
  5285. this.currentTitleName = '艺术家:' + item.name
  5286. if (item.pixelMapPath) {
  5287. this.currentTitleCover = item.pixelMapPath
  5288. }
  5289. this.updateListData(mList)
  5290. }
  5291. this.rightTopImage = $r('sys.symbol.chevron_left')
  5292. //进入歌单的时候的滚动位置在顶部
  5293. if(this.twoFingerType==4){
  5294. setTimeout(() => {
  5295. this.waterScroller.scrollEdge(Edge.Top)
  5296. this.scroller.scrollEdge(Edge.Top)
  5297. }, 380)
  5298. }else{
  5299. if (this.isGridMusic) {
  5300. this.scroller.scrollEdge(Edge.Top)
  5301. }else{
  5302. this.listScroller.scrollEdge(Edge.Top)
  5303. }
  5304. }
  5305. break;
  5306. case CommonConstants.TYPE_IS_ALBUM:
  5307. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  5308. let offset = 0
  5309. if(this.twoFingerType==4){
  5310. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  5311. let cur = this.waterScroller.currentOffset()
  5312. if (cur && typeof cur.yOffset === 'number') {
  5313. offset = cur.yOffset
  5314. }
  5315. }
  5316. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  5317. }else
  5318. if (this.isGridMusic) {
  5319. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  5320. let cur = this.scroller.currentOffset()
  5321. if (cur && typeof cur.yOffset === 'number') {
  5322. offset = cur.yOffset
  5323. }
  5324. }
  5325. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  5326. } else {
  5327. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  5328. let cur = this.listScroller.currentOffset()
  5329. if (cur && typeof cur.yOffset === 'number') {
  5330. offset = cur.yOffset
  5331. }
  5332. }
  5333. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  5334. }
  5335. let albumList = this.albumMap.get(item.name)
  5336. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  5337. Utility.doSortListAscending(albumList)
  5338. this.isCanBack = true
  5339. this.titleName = item.name
  5340. this.currentTitleName = '专辑:' + item.name
  5341. if (item.pixelMapPath) {
  5342. this.currentTitleCover = item.pixelMapPath
  5343. }
  5344. this.updateListData(albumList)
  5345. this.mScrollMap.set(item.name, this.selectedIndex)
  5346. this.rightTopImage = $r('sys.symbol.chevron_left')
  5347. }
  5348. //进入歌单的时候的滚动位置在顶部
  5349. if(this.twoFingerType==4){
  5350. setTimeout(() => {
  5351. this.waterScroller.scrollEdge(Edge.Top)
  5352. this.scroller.scrollEdge(Edge.Top)
  5353. }, 380)
  5354. }else{
  5355. if (this.isGridMusic) {
  5356. this.scroller.scrollEdge(Edge.Top)
  5357. }else{
  5358. this.listScroller.scrollEdge(Edge.Top)
  5359. }
  5360. }
  5361. break;
  5362. case CommonConstants.TYPE_IS_CSJAD:
  5363. return
  5364. break;
  5365. case CommonConstants.TYPE_LOCAL:
  5366. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  5367. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  5368. const cueTracks:CueTrack[] = cueinfo.tracks
  5369. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  5370. if(ArrayUtil.isNotEmpty(cueTracks)){
  5371. this.showCueDialog(cueTracks,cueinfo)
  5372. }
  5373. // this.showCueSheet = !this.showCueSheet
  5374. return
  5375. }
  5376. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  5377. this.stop();
  5378. }
  5379. if (isOpen) {
  5380. this.currentSong = item
  5381. if (index !== undefined) {
  5382. this.curIndex = index
  5383. }
  5384. this.songList = []
  5385. this.songList.push(item)
  5386. this.sonDataSource.pushArrayData(this.songList)
  5387. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  5388. this.currentSong = item
  5389. if (index !== undefined) {
  5390. this.curIndex = index
  5391. }
  5392. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  5393. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  5394. }else {
  5395. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  5396. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  5397. this.songList = globalVideoList
  5398. this.sonDataSource.pushArrayData(this.songList)
  5399. this.currentSong = globalVideoList[this.curIndex]
  5400. }
  5401. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  5402. this.videoUrl = this.currentSong.filePath
  5403. this.name = this.currentSong.name
  5404. this.cover = this.currentSong.pixelMapPath
  5405. this.artist = this.currentSong.artist
  5406. LogUtil.info('onecold this.currentSong.cover =' + this.currentSong.pixelMapPath)
  5407. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  5408. this.startPlayOrResumePlay()
  5409. break;
  5410. case CommonConstants.TYPE_WEBDAV:
  5411. // 处理网络音频播放(WebDAV)
  5412. Logger.info(`heanup 处理网络音频播放: ${item.name}, URL: ${item.filePath}`)
  5413. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  5414. this.stop();
  5415. }
  5416. if (isOpen) {
  5417. this.currentSong = item
  5418. if (index !== undefined) {
  5419. this.curIndex = index
  5420. }
  5421. this.songList = []
  5422. this.songList.push(item)
  5423. this.sonDataSource.pushArrayData(this.songList)
  5424. } else if (isFromSonPlayList) {
  5425. // 点击来自右下角的播放列表
  5426. this.currentSong = item
  5427. if (index !== undefined) {
  5428. this.curIndex = index
  5429. }
  5430. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  5431. Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  5432. } else {
  5433. // 从全局网络音频列表中查找
  5434. let globalVideoList = this.videoLocalList.filter(video => video.type === CommonConstants.TYPE_WEBDAV) as VideoItem[];
  5435. this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
  5436. if (this.curIndex === -1 && index !== undefined) {
  5437. this.curIndex = index;
  5438. }
  5439. this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
  5440. this.currentSong = this.songList[this.curIndex];
  5441. this.sonDataSource.pushArrayData(this.songList)
  5442. }
  5443. AppStorage.setOrCreate('currentSong', this.currentSong);
  5444. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  5445. this.videoUrl = await setVideoUrlForSong(this.currentSong);
  5446. Logger.info(TAG, `WebDAV URL同步构建完成(分支2): ${this.videoUrl}`);
  5447. this.name = this.currentSong.name
  5448. this.cover = this.currentSong.pixelMapPath
  5449. this.artist = this.currentSong.artist
  5450. Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 完整URL: ${this.videoUrl}`)
  5451. this.startPlayOrResumePlay()
  5452. break;
  5453. }
  5454. }
  5455. private cueComponentId: number = 0
  5456. //显示cue分轨列表对话框
  5457. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  5458. this.getUIContext().getPromptAction().openCustomDialog({
  5459. builder: () => {
  5460. this.cueComptentBuilder(cueTracks,cueinfo)
  5461. },
  5462. isModal:true,
  5463. showInSubWindow:false,
  5464. maskColor: Color.Transparent,
  5465. dialogTransition: // 设置弹窗内容显示的过渡效果
  5466. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  5467. .animation({ duration: 600, curve: Curve.Smooth }),
  5468. maskTransition: // 设置蒙层显示的过渡效果
  5469. TransitionEffect.opacity(0.5)
  5470. .animation({ duration: 600, curve: Curve.Smooth })
  5471. }).then((dialogId: number) => {
  5472. this.cueComponentId = dialogId
  5473. })
  5474. .catch((error: BusinessError) => {
  5475. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  5476. })
  5477. }
  5478. @Builder
  5479. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  5480. CueComptent({
  5481. title:cueinfo.title,
  5482. cueTracks:cueTracks,
  5483. isLongNameRoLL:this.isLongNameRoLL,
  5484. onCancel:()=>{
  5485. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  5486. },
  5487. onDoItemClick:(item: CueTrack, index: number)=>{
  5488. //获取cueinfo对应的filePath
  5489. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  5490. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  5491. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  5492. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  5493. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  5494. if (this.currentSong){
  5495. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  5496. this.stop();//播放之前先停止之前播放。
  5497. }
  5498. this.songList = globalVideoList
  5499. this.sonDataSource.pushArrayData(this.songList)
  5500. if(this.currentSong.type==CommonConstants.TYPE_WEBDAV){
  5501. this.videoUrl = this.currentSong.filePath.replace(/ /g, '%20');
  5502. }else{
  5503. this.videoUrl = this.currentSong.filePath
  5504. }
  5505. this.name = item.title||this.currentSong.name
  5506. this.cover = this.currentSong.pixelMapPath
  5507. this.artist = item.performer||this.currentSong.artist
  5508. this.currentSong.name = this.name
  5509. this.currentSong.artist = this.artist
  5510. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  5511. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  5512. }
  5513. }
  5514. })
  5515. }
  5516. @Builder
  5517. PlayController() {
  5518. Row() {
  5519. if(this.isHiCar()){
  5520. this.playConRigth()
  5521. Column(){
  5522. this.centerName()
  5523. }.layoutWeight(1)
  5524. .onClick(()=>{
  5525. this.showPlayerView()
  5526. })
  5527. this.playConLeft(false)
  5528. }else{
  5529. this.playConLeft()
  5530. this.playConRigth()
  5531. }
  5532. }
  5533. .width('100%')
  5534. .height(this.bottomBarHeight)
  5535. .hitTestBehavior(HitTestMode.Transparent)
  5536. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  5537. modalTransition: ModalTransition.NONE,
  5538. onWillDisappear: () => {
  5539. this.isShowPlay = false
  5540. },
  5541. // backgroundColor: 'rgba(0, 0, 0, 0.9)',
  5542. })
  5543. .padding({
  5544. left: 16,
  5545. right: 16
  5546. })
  5547. }
  5548. @State isFrontWhite: boolean = false
  5549. @Builder
  5550. centerName() {
  5551. Column() {
  5552. Text(this.currentSong?.name)
  5553. .fontSize(16)
  5554. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5555. .maxLines(1)
  5556. .fontColor(Color.White)
  5557. .fontWeight(500);
  5558. Row() {
  5559. Text(this.currentSong?.artist)
  5560. .margin({ top: 2 })
  5561. .fontSize(13)
  5562. .textAlign(TextAlign.Start)
  5563. .maxLines(1)
  5564. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5565. .fontColor(Color.White)
  5566. }
  5567. .visibility(this.currentSong?.artist? Visibility.Visible:Visibility.None)
  5568. }
  5569. .geometryTransition('name', { follow: true }) // 绑定标识符
  5570. .alignItems(HorizontalAlign.Center)
  5571. }
  5572. @Builder
  5573. playConLeft(isLeft: boolean = true) {
  5574. Row() {
  5575. // RotatingCover({ songLabel: this.currentSong?.pixelMapPath })
  5576. Image( this.currentSong?.pixelMapPath)
  5577. .height(45)
  5578. .width(45)
  5579. .alt( $r('app.media.music_red'))
  5580. .fillColor(this.themeColor)
  5581. .borderRadius(8)
  5582. .shadow({
  5583. radius: 10,
  5584. type: ShadowType.BLUR,
  5585. color: 'on_primary'
  5586. })
  5587. .clip(true)
  5588. .geometryTransition('cover', { follow: true }) // 绑定标识符
  5589. Column() {
  5590. Text(this.currentSong?.name)
  5591. .fontSize(16)
  5592. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5593. .maxLines(1)
  5594. .fontColor(Color.White)
  5595. .fontWeight(500);
  5596. Row() {
  5597. Text(this.currentSong?.artist)
  5598. .margin({ top: 2 })
  5599. .fontSize(13)
  5600. .textAlign(TextAlign.Start)
  5601. .maxLines(1)
  5602. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5603. .fontColor(Color.White)
  5604. }
  5605. .visibility(this.currentSong?.artist? Visibility.Visible:Visibility.None)
  5606. }
  5607. .padding({left:8})
  5608. .geometryTransition('name', { follow: true }) // 绑定标识符
  5609. .alignItems(isLeft?HorizontalAlign.Start:HorizontalAlign.End)
  5610. .margin({ right: isLeft?22:10 })
  5611. .visibility(isLeft? Visibility.Visible:Visibility.None)
  5612. }
  5613. .padding({ right: 18 })
  5614. .layoutWeight(isLeft?1:0)
  5615. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5616. .onClick(() => {
  5617. this.showPlayerView()
  5618. })
  5619. }
  5620. setShowPLayTrue(){
  5621. this.getUIContext()?.animateTo({
  5622. duration: 500,
  5623. curve: Curve.Friction
  5624. }, () => {
  5625. this.isShowPlay = !this.isShowPlay;
  5626. });
  5627. }
  5628. //打开播放页
  5629. showPlayerView() {
  5630. if (ArrayUtil.isNotEmpty(this.songList)) {
  5631. this.setShowPLayTrue()
  5632. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  5633. this.initLyric(lyricPath);
  5634. this.startAutoHide();
  5635. } else {
  5636. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  5637. }
  5638. }
  5639. @Builder
  5640. playConRigth() {
  5641. Row() {
  5642. SymbolGlyph($r('sys.symbol.backward_end_fill'))
  5643. .fontSize(28)
  5644. .fontColor([this.themeColor])
  5645. .alignSelf(ItemAlign.Center)
  5646. .visibility(this.isShowPrecious? Visibility.Visible:Visibility.None)
  5647. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5648. .margin({ left: 8, right: 14 })
  5649. .displayPriority(2)
  5650. .onClick(() => {
  5651. if (ArrayUtil.isNotEmpty(this.songList)) {
  5652. this.playPrevious()
  5653. } else {
  5654. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5655. }
  5656. })
  5657. //播放进度条
  5658. Stack() {
  5659. Progress({
  5660. value: Math.floor(this.progressValue),
  5661. type: ProgressType.Ring,
  5662. })
  5663. .color(this.themeColor)// 进度条前景色为灰色
  5664. .height(38)
  5665. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5666. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ? $r('app.media.hm_pause') : $r('app.media.hm_play2'))
  5667. .height(36)
  5668. .width(36)
  5669. .displayPriority(3)
  5670. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5671. .fillColor(this.themeColor)
  5672. .onClick(() => {
  5673. if (ArrayUtil.isNotEmpty(this.songList)) {
  5674. console.info('onecold playOrPause 4642')
  5675. this.playOrPause()
  5676. } else {
  5677. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5678. }
  5679. })
  5680. }
  5681. SymbolGlyph($r('sys.symbol.forward_end_fill'))
  5682. .fontSize(28)
  5683. .fontColor([this.themeColor])
  5684. .alignSelf(ItemAlign.Center)
  5685. .margin({
  5686. right: 14,
  5687. left: 14
  5688. })
  5689. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5690. .displayPriority(2)
  5691. .onClick(() => {
  5692. if (ArrayUtil.isNotEmpty(this.songList)) {
  5693. this.playNext()
  5694. } else {
  5695. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5696. }
  5697. })
  5698. Image($r('app.media.hm_playlist'))
  5699. .height(26)
  5700. .width(26)
  5701. .displayPriority(1)
  5702. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5703. .fillColor(this.themeColor)
  5704. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  5705. height: '95%',
  5706. dragBar: true,
  5707. showClose: true,
  5708. blurStyle: BlurStyle.Thin,
  5709. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  5710. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  5711. title: {
  5712. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  5713. + `(${this.songList.length}首)`
  5714. }
  5715. })
  5716. .onClick(() => {
  5717. if (ArrayUtil.isNotEmpty(this.songList)) {
  5718. this.isShowSheet = !this.isShowSheet;
  5719. this.isFrontWhite = false
  5720. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  5721. this.scrollIndex()
  5722. } else {
  5723. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5724. }
  5725. })
  5726. }
  5727. }
  5728. scrollIndex(){
  5729. try {
  5730. setTimeout(() => {
  5731. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  5732. if(this.curIndex>60){
  5733. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  5734. }else{
  5735. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  5736. }
  5737. })
  5738. }, 123)
  5739. }catch (error) {
  5740. console.error(`onecold scrollIndex出错: ${error}`);
  5741. }
  5742. }
  5743. //播放列表布局
  5744. @Builder
  5745. PlayListSheet() {
  5746. Column() {
  5747. this.PlayList()
  5748. }
  5749. .width('100%')
  5750. .height('100%')
  5751. }
  5752. @State titleStr: string = ''
  5753. @State ablumStr: string = ''
  5754. @State artistStr: string = ''
  5755. @State lyricConStr: string = ''
  5756. @State currentEditItem: string = ''
  5757. @State yearStr: string = ''
  5758. @State trackStr: string = ''
  5759. @State genreStr: string = ''
  5760. @State imagePathStr: string = ''
  5761. @State albumArtistStr: string = ''
  5762. @State composerStr: string = ''
  5763. @State lyricistStr: string = ''
  5764. @State commentStr: string = ''
  5765. @State discStr: string = ''
  5766. doUpdateData() {
  5767. setTimeout(() => {
  5768. if (this.modeType === 0) {
  5769. this.deleteCache(this.currentPath)
  5770. this.getSortedFiles(this.currentPath)
  5771. }
  5772. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  5773. workerInstance.postMessage({ code: 3, data: this.context });
  5774. workerInstance.postMessage({ code: 4, data: this.context });
  5775. }, 999)
  5776. }
  5777. //编辑信息
  5778. async doEdit(item: VideoItem) {
  5779. if (!item) {
  5780. return
  5781. }
  5782. if (StrUtil.isEmpty(this.titleStr)) {
  5783. ToastUtil.showToast('标题不能为空')
  5784. return
  5785. }
  5786. DialogHelper.showLoadingDialog()
  5787. await PermissionUtil.activatePermission(item.filePath)
  5788. let tempOutPath = ''
  5789. // 如果不是 packName 包下的文件,则直接路径用this.currentPath
  5790. if(!item.filePath.toLowerCase().includes(this.packName)){
  5791. tempOutPath = this.currentPath + '/' + item.fileName
  5792. }
  5793. console.info('onecold tempOutPath ='+tempOutPath)
  5794. //用户更改了封面,那就内嵌下封面
  5795. if(StrUtil.isNotEmpty(this.imagePathStr)){
  5796. const resultCover:boolean = await changeMusicCover(this.context,
  5797. item.filePath,this.imagePathStr,true,tempOutPath);
  5798. this.imagePathStr = ''
  5799. if(resultCover){
  5800. ToastUtil.showToast('内嵌封面成功')
  5801. }
  5802. }
  5803. const metadata:FFMpegTags = {
  5804. title: this.titleStr,
  5805. artist: this.artistStr,
  5806. album: this.ablumStr,
  5807. TYER:this.yearStr,
  5808. genre:this.genreStr,
  5809. track:this.trackStr,
  5810. album_artist:this.albumArtistStr,
  5811. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  5812. COMPOSER:this.composerStr,
  5813. lyricist:this.lyricistStr,
  5814. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  5815. comment:this.commentStr,
  5816. disc:this.discStr,
  5817. };
  5818. let newInput = item.filePath
  5819. //内嵌标签歌路径如果不是包含包名,输入newInput要赋值tempOutPath,然后tempOutPath为空
  5820. if(!item.filePath.toLowerCase().includes(this.packName)&&FileUtil.accessSync(tempOutPath)){
  5821. newInput = tempOutPath
  5822. tempOutPath = ''
  5823. }
  5824. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  5825. const result:boolean = await repairAudioMetadata(
  5826. newInput,
  5827. this.lyricConStr,
  5828. metadata,
  5829. true,
  5830. tempOutPath
  5831. );
  5832. if (result) {
  5833. if(!item.filePath.includes(this.packName)){
  5834. //内嵌成功的歌路径如果不是包含包名,则要入库
  5835. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newInput,
  5836. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  5837. this.table.insert(newItem, (id: number) => {
  5838. //加入数据库
  5839. if(this.modeType==0){
  5840. this.deleteCache(this.currentPath)
  5841. this.getSortedFiles(this.currentPath)
  5842. }
  5843. });
  5844. }
  5845. this.table.updateMediaInfo(item.filePath, this.titleStr, this.artistStr, this.ablumStr,this.lyricConStr,
  5846. this.yearStr,this.genreStr,this.trackStr,this.albumArtistStr,this.composerStr, this.lyricistStr,this.commentStr,this.discStr,
  5847. (success: boolean, error?: string) => {
  5848. // this.isShowEdit = false
  5849. if (success) {
  5850. console.log(" onecold 编辑信息成功,数据库已同步");
  5851. ToastUtil.showToast('内嵌音乐标签成功')
  5852. this.isShowMoreView = false
  5853. this.name = this.titleStr
  5854. if (item.filePath == this.currentSong?.filePath) {
  5855. this.currentSong.name = this.titleStr
  5856. this.artist = this.artistStr
  5857. this.currentSong.artist = this.artistStr
  5858. this.currentSong.album = this.ablumStr
  5859. this.currentSong.year = this.yearStr
  5860. this.currentSong.genre = this.genreStr
  5861. this.currentSong.track = this.trackStr
  5862. this.currentSong.lyricContent = this.lyricConStr
  5863. this.initLyric(item.filePath)
  5864. this.currentSong.ALBUMARTIST = this.albumArtistStr
  5865. this.currentSong.COMPOSER = this.composerStr
  5866. this.currentSong.LYRICIST = this.lyricistStr
  5867. this.currentSong.COMMENT = this.commentStr
  5868. }
  5869. this.doUpdateData()
  5870. } else {
  5871. // ToastUtil.showToast('保存失败' + error?.toString())
  5872. console.error(" onecold 编辑信息数据库失败原因: " + error);
  5873. }
  5874. // 关闭进度条
  5875. DialogHelper.closeLoading();
  5876. });
  5877. console.log(' onecold 元数据标签更新成功,');
  5878. } else {
  5879. // 关闭进度条
  5880. DialogHelper.closeLoading();
  5881. ToastUtil.showToast('内嵌音乐标签失败')
  5882. console.log('onecold 内嵌音乐标签失败');
  5883. }
  5884. this.longItemFilePath = ''
  5885. this.tempLyricContent = ''
  5886. this.isShowEdit = false
  5887. }
  5888. updateLyricToDB() {
  5889. }
  5890. @Builder
  5891. editSheet(item: VideoItem) {
  5892. Scroll() {
  5893. Column() {
  5894. this.editDetail(item)
  5895. }
  5896. }
  5897. .width('100%')
  5898. .height('100%')
  5899. }
  5900. @Builder
  5901. editDetail(item: VideoItem) {
  5902. Column() {
  5903. if (item) {
  5904. Row() {
  5905. Stack() {
  5906. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  5907. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  5908. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  5909. item.pixelMapPath)
  5910. .fillColor(this.themeColor)
  5911. .height(88)
  5912. .width(88)
  5913. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  5914. .borderRadius(12)
  5915. .clip(true)
  5916. .opacity(this.opacityItem)// 绑定透明度
  5917. .margin({ left: 25 })
  5918. }
  5919. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  5920. .onClick(async () => {
  5921. const imagePath:string | undefined = await this.goSelectImage(item);
  5922. if (imagePath) {
  5923. //用户更改过图片
  5924. this.imagePathStr = imagePath
  5925. }
  5926. })
  5927. .width('28%')
  5928. Row() {
  5929. Column() {
  5930. Text(item.name)
  5931. .fontSize(17)
  5932. .maxLines(1)
  5933. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  5934. .animation({
  5935. duration: 555,
  5936. curve: 'Linear',
  5937. })
  5938. .fontColor(this.themeColor)
  5939. .margin({ left: 8 })
  5940. Row() {
  5941. Text(item.artist)
  5942. .fontSize(14)
  5943. .maxLines(1)
  5944. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  5945. .padding({ top: 8 })
  5946. .fontColor(this.themeColor)
  5947. .margin({ left: 8 })
  5948. }
  5949. }
  5950. .height('100%')
  5951. .width(100)
  5952. .layoutWeight(1)
  5953. .justifyContent(FlexAlign.Center)
  5954. .alignItems(HorizontalAlign.Start)
  5955. Column() {
  5956. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5957. Row(){
  5958. SymbolGlyph($r('sys.symbol.picture'))
  5959. .fontSize(18)
  5960. .fontColor([Color.White])
  5961. Text('获取封面')
  5962. .margin({ left: 4 })
  5963. .fontSize(11)
  5964. .fontColor(Color.White)
  5965. .fontWeight(480)
  5966. .textAlign(TextAlign.Center)
  5967. }
  5968. .justifyContent(FlexAlign.Center)
  5969. }
  5970. .height(38)
  5971. .width(100)
  5972. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5973. .backgroundColor(this.themeColor)
  5974. .stateEffect(true)
  5975. .margin({ right: 35 })
  5976. .onClick(async () => {
  5977. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  5978. this.showTipsDialog();
  5979. return; // Return empty string when no API is configured
  5980. }
  5981. const imagePath:string | undefined = await this.doSearchCover(item);
  5982. console.info('onecold imagePath = '+imagePath)
  5983. if (StrUtil.isNotEmpty(imagePath)) {
  5984. //用户更改过图片
  5985. this.imagePathStr = imagePath
  5986. ToastUtil.showToast('获取封面成功')
  5987. }else{
  5988. ToastUtil.showToast('获取封面失败,请重试')
  5989. }
  5990. })
  5991. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5992. Row(){
  5993. SymbolGlyph($r('sys.symbol.input_mode'))
  5994. .fontSize(18)
  5995. .fontColor([Color.White])
  5996. Text('获取歌词')
  5997. .margin({ left: 4 })
  5998. .fontSize(11)
  5999. .fontColor(Color.White)
  6000. .fontWeight(480)
  6001. .textAlign(TextAlign.Center)
  6002. }
  6003. .justifyContent(FlexAlign.Center)
  6004. }
  6005. .height(38)
  6006. .width(100)
  6007. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6008. .backgroundColor(this.themeColor)
  6009. .stateEffect(true)
  6010. .margin({ top: 9, right: 35 })
  6011. .onClick(async () => {
  6012. //判断有没有设置api
  6013. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  6014. if (StrUtil.isEmpty(apiUrl)) {
  6015. this.isLyricSetting = false
  6016. this.showTipsDialog()
  6017. return
  6018. }
  6019. let artist = item.artist
  6020. let title = item.name
  6021. if(!artist)
  6022. artist = ''
  6023. if(!title)
  6024. title = ''
  6025. let res: string | undefined = await getApiLyric(apiUrl,title, artist, false);
  6026. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  6027. this.lyricConStr = res;
  6028. ToastUtil.showToast('获取歌词成功')
  6029. }else{
  6030. ToastUtil.showToast('获取歌词失败,请重试')
  6031. }
  6032. })
  6033. }
  6034. .justifyContent(FlexAlign.Start)
  6035. }
  6036. .height('100%')
  6037. .justifyContent(FlexAlign.Start)
  6038. .layoutWeight(1)
  6039. }
  6040. .width('100%')
  6041. .height(98)
  6042. Row() {
  6043. Text('标题:')
  6044. .fontSize(14)
  6045. .fontColor($r('app.color.text_color'))
  6046. .margin({ left: 22 })
  6047. TextInput({ text: item.name })
  6048. .height(40)
  6049. .maxLines(1)
  6050. .fontSize(14)
  6051. .layoutWeight(1)
  6052. .fontColor($r('app.color.text_color'))
  6053. .margin({ right: 20, left: 10 })
  6054. .onChange((val: string) => {
  6055. this.titleStr = val
  6056. })
  6057. }
  6058. .width('100%')
  6059. .margin({ top: 10, bottom: 10 })
  6060. .justifyContent(FlexAlign.Start)
  6061. Row() {
  6062. Text('艺术家:')
  6063. .fontSize(14)
  6064. .fontColor($r('app.color.text_color'))
  6065. .margin({ left: 22 })
  6066. TextInput({ text: item.artist })
  6067. .height(40)
  6068. .maxLines(1)
  6069. .fontSize(14)
  6070. .layoutWeight(1)
  6071. .fontColor($r('app.color.text_color'))
  6072. .margin({ right: 20, left: 10 })
  6073. .onChange((val: string) => {
  6074. this.artistStr = val
  6075. })
  6076. }
  6077. .width('100%')
  6078. .margin({ top: 10, bottom: 10 })
  6079. .justifyContent(FlexAlign.Start)
  6080. Row() {
  6081. Text('专辑名:')
  6082. .fontSize(14)
  6083. .fontColor($r('app.color.text_color'))
  6084. .margin({ left: 22 })
  6085. TextInput({ text: item.album })
  6086. .height(40)
  6087. .maxLines(1)
  6088. .fontSize(14)
  6089. .layoutWeight(1)
  6090. .fontColor($r('app.color.text_color'))
  6091. .margin({ right: 20, left: 10 })
  6092. .onChange((val: string) => {
  6093. this.ablumStr = val
  6094. })
  6095. }
  6096. .width('100%')
  6097. .margin({ top: 10, bottom: 10 })
  6098. .justifyContent(FlexAlign.Start)
  6099. Row() {
  6100. Column(){
  6101. Column(){
  6102. Text('歌词:')
  6103. .fontSize(14)
  6104. .fontColor($r('app.color.text_color'))
  6105. .margin({ top:9,left: 22 })
  6106. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6107. SymbolGlyph($r('sys.symbol.trash_fill'))
  6108. .fontSize(25)
  6109. .alignSelf(ItemAlign.Center)
  6110. .margin({ left: 22,top:25})
  6111. }
  6112. .backgroundColor(Color.Transparent)
  6113. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  6114. Visibility.None:Visibility.Visible)
  6115. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6116. .onClick(()=>{
  6117. this.lyricConStr = ''
  6118. this.lyricContent = ''
  6119. this.tempLyricContent = ''
  6120. })
  6121. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6122. SymbolGlyph($r('sys.symbol.plus'))
  6123. .fontSize(25)
  6124. .alignSelf(ItemAlign.Center)
  6125. .margin({ left: 22,top:25})
  6126. }
  6127. .backgroundColor(Color.Transparent)
  6128. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6129. .onClick( ()=>{
  6130. this.callFilePickerSelectFileForLyric()
  6131. })
  6132. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6133. SymbolGlyph($r('sys.symbol.traditional_square'))
  6134. .fontSize(25)
  6135. .alignSelf(ItemAlign.Center)
  6136. .margin({ left: 22,top:25})
  6137. }
  6138. .backgroundColor(Color.Transparent)
  6139. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  6140. Visibility.None:Visibility.Visible)
  6141. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6142. .onClick( ()=>{
  6143. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  6144. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  6145. })
  6146. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6147. Image($r('app.media.jianti'))
  6148. .height(25)
  6149. .fillColor($r('app.color.text_color'))
  6150. .alignSelf(ItemAlign.Center)
  6151. .margin({ left: 22,top:25})
  6152. }
  6153. .backgroundColor(Color.Transparent)
  6154. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  6155. Visibility.None:Visibility.Visible)
  6156. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6157. .onClick( ()=>{
  6158. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  6159. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  6160. })
  6161. }
  6162. .layoutWeight(1)
  6163. }
  6164. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  6165. this.tempLyricContent })
  6166. .type(TextAreaType.NORMAL)
  6167. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  6168. .fontSize(14)
  6169. .layoutWeight(1)
  6170. .fontColor($r('app.color.text_color'))
  6171. .margin({ right: 20, left: 10 })
  6172. .onChange((val: string) => {
  6173. this.lyricConStr = val
  6174. })
  6175. }
  6176. .width('100%')
  6177. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  6178. .margin({ top: 10, bottom: 10 })
  6179. .justifyContent(FlexAlign.Start)
  6180. Row() {
  6181. Text('年份:')
  6182. .fontSize(14)
  6183. .fontColor($r('app.color.text_color'))
  6184. .margin({ left: 22 })
  6185. TextInput({ text: item.year })
  6186. .height(40)
  6187. .maxLines(1)
  6188. .fontSize(14)
  6189. .type(InputType.Number)
  6190. .layoutWeight(1)
  6191. .fontColor($r('app.color.text_color'))
  6192. .margin({ right: 20, left: 10 })
  6193. .onChange((val: string) => {
  6194. this.yearStr = val
  6195. })
  6196. }
  6197. .width('100%')
  6198. .margin({ top: 10, bottom: 10 })
  6199. .justifyContent(FlexAlign.Start)
  6200. Row() {
  6201. Text('音轨号:')
  6202. .fontSize(14)
  6203. .fontColor($r('app.color.text_color'))
  6204. .margin({ left: 22 })
  6205. TextInput({ text:item.track=='未知'?'': item.track })
  6206. .height(40)
  6207. .maxLines(1)
  6208. .fontSize(14)
  6209. .type(InputType.Number)
  6210. .layoutWeight(1)
  6211. .fontColor($r('app.color.text_color'))
  6212. .margin({ right: 20, left: 10 })
  6213. .onChange((val: string) => {
  6214. this.trackStr = val
  6215. })
  6216. }
  6217. .width('100%')
  6218. .margin({ top: 10, bottom: 10 })
  6219. .justifyContent(FlexAlign.Start)
  6220. Row() {
  6221. Text('碟号:')
  6222. .fontSize(14)
  6223. .fontColor($r('app.color.text_color'))
  6224. .margin({ left: 22 })
  6225. TextInput({ text:item.disc })
  6226. .height(40)
  6227. .maxLines(1)
  6228. .fontSize(14)
  6229. .type(InputType.Number)
  6230. .layoutWeight(1)
  6231. .fontColor($r('app.color.text_color'))
  6232. .margin({ right: 20, left: 10 })
  6233. .onChange((val: string) => {
  6234. this.discStr = val
  6235. })
  6236. }
  6237. .width('100%')
  6238. .margin({ top: 10, bottom: 10 })
  6239. .justifyContent(FlexAlign.Start)
  6240. Row() {
  6241. Text('风格:')
  6242. .fontSize(14)
  6243. .fontColor($r('app.color.text_color'))
  6244. .margin({ left: 22 })
  6245. TextInput({ text: item.genre })
  6246. .height(40)
  6247. .maxLines(1)
  6248. .fontSize(14)
  6249. .layoutWeight(1)
  6250. .fontColor($r('app.color.text_color'))
  6251. .margin({ right: 20, left: 10 })
  6252. .onChange((val: string) => {
  6253. this.genreStr = val
  6254. })
  6255. }
  6256. .width('100%')
  6257. .margin({ top: 10, bottom: 10 })
  6258. .justifyContent(FlexAlign.Start)
  6259. Row() {
  6260. Text('专辑艺术家:')
  6261. .fontSize(14)
  6262. .fontColor($r('app.color.text_color'))
  6263. .margin({ left: 22 })
  6264. TextInput({ text: item.ALBUMARTIST })
  6265. .height(40)
  6266. .maxLines(1)
  6267. .fontSize(14)
  6268. .layoutWeight(1)
  6269. .fontColor($r('app.color.text_color'))
  6270. .margin({ right: 20, left: 10 })
  6271. .onChange((val: string) => {
  6272. this.albumArtistStr = val
  6273. })
  6274. }
  6275. .width('100%')
  6276. .margin({ top: 10, bottom: 10 })
  6277. .justifyContent(FlexAlign.Start)
  6278. Row() {
  6279. Text('作曲:')
  6280. .fontSize(14)
  6281. .fontColor($r('app.color.text_color'))
  6282. .margin({ left: 22 })
  6283. TextInput({ text: item.COMPOSER })
  6284. .height(40)
  6285. .maxLines(1)
  6286. .fontSize(14)
  6287. .layoutWeight(1)
  6288. .fontColor($r('app.color.text_color'))
  6289. .margin({ right: 20, left: 10 })
  6290. .onChange((val: string) => {
  6291. this.composerStr = val
  6292. })
  6293. }
  6294. .width('100%')
  6295. .margin({ top: 10, bottom: 10 })
  6296. .justifyContent(FlexAlign.Start)
  6297. Row() {
  6298. Text('作词:')
  6299. .fontSize(14)
  6300. .fontColor($r('app.color.text_color'))
  6301. .margin({ left: 22 })
  6302. TextInput({ text: item.LYRICIST })
  6303. .height(40)
  6304. .maxLines(1)
  6305. .fontSize(14)
  6306. .layoutWeight(1)
  6307. .fontColor($r('app.color.text_color'))
  6308. .margin({ right: 20, left: 10 })
  6309. .onChange((val: string) => {
  6310. this.lyricistStr = val
  6311. })
  6312. }
  6313. .width('100%')
  6314. .margin({ top: 10, bottom: 10 })
  6315. .justifyContent(FlexAlign.Start)
  6316. Row() {
  6317. Text('注释:')
  6318. .fontSize(14)
  6319. .fontColor($r('app.color.text_color'))
  6320. .margin({ left: 22 })
  6321. TextInput({ text: item.COMMENT })
  6322. .height(40)
  6323. .maxLines(1)
  6324. .fontSize(14)
  6325. .layoutWeight(1)
  6326. .fontColor($r('app.color.text_color'))
  6327. .margin({ right: 20, left: 10 })
  6328. .onChange((val: string) => {
  6329. this.commentStr = val
  6330. })
  6331. }
  6332. .width('100%')
  6333. .margin({ top: 10, bottom: 10 })
  6334. .justifyContent(FlexAlign.Start)
  6335. Row() {
  6336. Button('保存')
  6337. .fontColor(Color.White)
  6338. .layoutWeight(1)
  6339. .height(50)
  6340. .width(100)
  6341. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6342. .backgroundColor(this.themeColor)
  6343. .stateEffect(true)
  6344. .margin({ right: 20, bottom: 20 })
  6345. .onClick(async () => {
  6346. this.doEdit(item)
  6347. })
  6348. Button('取消')
  6349. .fontColor(Color.White)
  6350. .layoutWeight(1)
  6351. .height(50)
  6352. .width(100)
  6353. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6354. .backgroundColor(this.themeColor)
  6355. .stateEffect(true)
  6356. .margin({ left: 20, bottom: 20 })
  6357. .onClick(async () => {
  6358. if(this.isGridMusic){
  6359. this.longItemFilePath =''
  6360. }else{
  6361. this.isShowEdit = false
  6362. }
  6363. this.setEditStrEmpty()
  6364. if(this.isShowPlay){
  6365. this.isShowEdit = false
  6366. }
  6367. })
  6368. }
  6369. .margin({
  6370. left: 38,
  6371. right: 38,
  6372. top: 10,
  6373. bottom: 10
  6374. })
  6375. .width(250)
  6376. .height(60)
  6377. }
  6378. }
  6379. .margin({ bottom: 20 })
  6380. }
  6381. setEditStrEmpty(){
  6382. this.imagePathStr = ''
  6383. this.lyricConStr = ''
  6384. this.artistStr = ''
  6385. this.titleStr = ''
  6386. this.ablumStr = ''
  6387. this.genreStr = ''
  6388. this.yearStr = ''
  6389. this.trackStr = ''
  6390. this.albumArtistStr = ''
  6391. this.composerStr = ''
  6392. this.lyricistStr = ''
  6393. this.commentStr = ''
  6394. this.discStr = ''
  6395. }
  6396. @Builder
  6397. detailSheet(item:VideoItem) {
  6398. Scroll() {
  6399. Column() {
  6400. this.songDetail(item)
  6401. }
  6402. }
  6403. .width('100%')
  6404. .height('100%')
  6405. }
  6406. @Builder
  6407. songDetail(currentItem:VideoItem) {
  6408. Column() {
  6409. if (currentItem) {
  6410. Row() {
  6411. Stack() {
  6412. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.music_red') :
  6413. currentItem.pixelMapPath)
  6414. .fillColor(this.themeColor)
  6415. .height(80)
  6416. .width(80)
  6417. .borderRadius(10)
  6418. .opacity(this.opacityItem)// 绑定透明度
  6419. .margin({ left: 22 })
  6420. }
  6421. Column() {
  6422. Column() {
  6423. Text(currentItem.name)
  6424. .fontSize(16)
  6425. .maxLines(1)
  6426. .animation({
  6427. duration: 555,
  6428. curve: 'Linear',
  6429. })
  6430. .fontColor($r('app.color.text_color'))
  6431. .margin({ left: 15 })
  6432. }
  6433. .height('100%')
  6434. .width('100%')
  6435. .justifyContent(FlexAlign.Center)
  6436. .alignItems(HorizontalAlign.Start)
  6437. }
  6438. .height('100%')
  6439. }
  6440. .width('100%')
  6441. .height(90)
  6442. .justifyContent(FlexAlign.SpaceBetween)
  6443. Row() {
  6444. Text('艺术家:')
  6445. .fontSize(14)
  6446. .fontColor($r('app.color.text_color'))
  6447. .margin({ left: 22 })
  6448. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  6449. .fontSize(14)
  6450. .fontColor($r('app.color.text_color'))
  6451. .margin({ left: 10 })
  6452. .layoutWeight(1)
  6453. }
  6454. .width('100%')
  6455. .margin({ top: 10, bottom: 10 })
  6456. .justifyContent(FlexAlign.Start)
  6457. Row() {
  6458. Text('专辑名:')
  6459. .fontSize(14)
  6460. .fontColor($r('app.color.text_color'))
  6461. .margin({ left: 22 })
  6462. Text(currentItem?.album ?currentItem.album : '未知专辑')
  6463. .fontSize(14)
  6464. .margin({ left: 10 })
  6465. .fontColor($r('app.color.text_color'))
  6466. .layoutWeight(1)
  6467. }
  6468. .width('100%')
  6469. .margin({ top: 10, bottom: 10 })
  6470. .justifyContent(FlexAlign.Start)
  6471. Row() {
  6472. Text('时长:')
  6473. .fontSize(14)
  6474. .fontColor($r('app.color.text_color'))
  6475. .margin({ left: 22 })
  6476. Text(StrUtil.isEmpty(currentItem.duration)?
  6477. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  6478. .fontSize(14)
  6479. .margin({ left: 10 })
  6480. .fontColor($r('app.color.text_color'))
  6481. .layoutWeight(1)
  6482. }
  6483. .width('100%')
  6484. .margin({ top: 10, bottom: 10 })
  6485. .justifyContent(FlexAlign.Start)
  6486. Row() {
  6487. Text('采样率:')
  6488. .fontSize(14)
  6489. .fontColor($r('app.color.text_color'))
  6490. .margin({ left: 22 })
  6491. Text(Utility.convertToKHz(currentItem.sampleRate))
  6492. .fontSize(14)
  6493. .margin({ left: 10 })
  6494. .fontColor($r('app.color.text_color'))
  6495. .layoutWeight(1)
  6496. }
  6497. .width('100%')
  6498. .margin({ top: 10, bottom: 10 })
  6499. .justifyContent(FlexAlign.Start)
  6500. Row() {
  6501. Text('比特率:')
  6502. .fontSize(14)
  6503. .fontColor($r('app.color.text_color'))
  6504. .margin({ left: 22 })
  6505. Text(currentItem.bit_rate)
  6506. .fontSize(14)
  6507. .margin({ left: 10 })
  6508. .fontColor($r('app.color.text_color'))
  6509. .layoutWeight(1)
  6510. }
  6511. .width('100%')
  6512. .margin({ top: 10, bottom: 10 })
  6513. .justifyContent(FlexAlign.Start)
  6514. Row() {
  6515. Text('位深:')
  6516. .fontSize(14)
  6517. .fontColor($r('app.color.text_color'))
  6518. .margin({ left: 22 })
  6519. Text(`${currentItem.bits_per_raw_sample} bits`)
  6520. .fontSize(14)
  6521. .margin({ left: 10 })
  6522. .fontColor($r('app.color.text_color'))
  6523. .layoutWeight(1)
  6524. }
  6525. .width('100%')
  6526. .margin({ top: 10, bottom: 10 })
  6527. .justifyContent(FlexAlign.Start)
  6528. Row() {
  6529. Text('声道:')
  6530. .fontSize(14)
  6531. .fontColor($r('app.color.text_color'))
  6532. .margin({ left: 22 })
  6533. Text(`${currentItem.channels}`)
  6534. .fontSize(14)
  6535. .margin({ left: 10 })
  6536. .fontColor($r('app.color.text_color'))
  6537. .layoutWeight(1)
  6538. }
  6539. .width('100%')
  6540. .margin({ top: 10, bottom: 10 })
  6541. .justifyContent(FlexAlign.Start)
  6542. Row() {
  6543. Text('声道布局:')
  6544. .fontSize(14)
  6545. .fontColor($r('app.color.text_color'))
  6546. .margin({ left: 22 })
  6547. Text(`${currentItem.channel_layout}`)
  6548. .fontSize(14)
  6549. .margin({ left: 10 })
  6550. .fontColor($r('app.color.text_color'))
  6551. .layoutWeight(1)
  6552. }
  6553. .width('100%')
  6554. .margin({ top: 10, bottom: 10 })
  6555. .justifyContent(FlexAlign.Start)
  6556. Row() {
  6557. Text('起始播放点:')
  6558. .fontSize(14)
  6559. .fontColor($r('app.color.text_color'))
  6560. .margin({ left: 22 })
  6561. Text(`${currentItem.start_time}`)
  6562. .fontSize(14)
  6563. .margin({ left: 10 })
  6564. .fontColor($r('app.color.text_color'))
  6565. .layoutWeight(1)
  6566. }
  6567. .width('100%')
  6568. .margin({ top: 10, bottom: 10 })
  6569. .justifyContent(FlexAlign.Start)
  6570. Row() {
  6571. Text('风格:')
  6572. .fontSize(14)
  6573. .fontColor($r('app.color.text_color'))
  6574. .margin({ left: 22 })
  6575. Text(currentItem.genre)
  6576. .fontSize(14)
  6577. .margin({ left: 10 })
  6578. .fontColor($r('app.color.text_color'))
  6579. .layoutWeight(1)
  6580. }
  6581. .width('100%')
  6582. .margin({ top: 10, bottom: 10 })
  6583. .justifyContent(FlexAlign.Start)
  6584. Row() {
  6585. Text('发行时间:')
  6586. .fontSize(14)
  6587. .fontColor($r('app.color.text_color'))
  6588. .margin({ left: 22 })
  6589. Text(currentItem.year)
  6590. .fontSize(14)
  6591. .margin({ left: 10 })
  6592. .fontColor($r('app.color.text_color'))
  6593. .layoutWeight(1)
  6594. }
  6595. .width('100%')
  6596. .margin({ top: 10, bottom: 10 })
  6597. .justifyContent(FlexAlign.Start)
  6598. Row() {
  6599. Text('质量评分:')
  6600. .fontSize(14)
  6601. .fontColor($r('app.color.text_color'))
  6602. .margin({ left: 22 })
  6603. Text(currentItem.probe_score+"")
  6604. .fontSize(14)
  6605. .margin({ left: 10 })
  6606. .fontColor($r('app.color.text_color'))
  6607. .layoutWeight(1)
  6608. }
  6609. .width('100%')
  6610. .margin({ top: 10, bottom: 10 })
  6611. .justifyContent(FlexAlign.Start)
  6612. Row() {
  6613. Text('音轨号:')
  6614. .fontSize(14)
  6615. .fontColor($r('app.color.text_color'))
  6616. .margin({ left: 22 })
  6617. Text(currentItem.track)
  6618. .fontSize(14)
  6619. .margin({ left: 10 })
  6620. .fontColor($r('app.color.text_color'))
  6621. .layoutWeight(1)
  6622. }
  6623. .width('100%')
  6624. .margin({ top: 10, bottom: 10 })
  6625. .justifyContent(FlexAlign.Start)
  6626. Row() {
  6627. Text('碟号:')
  6628. .fontSize(14)
  6629. .fontColor($r('app.color.text_color'))
  6630. .margin({ left: 22 })
  6631. Text(currentItem.disc)
  6632. .fontSize(14)
  6633. .margin({ left: 10 })
  6634. .fontColor($r('app.color.text_color'))
  6635. .layoutWeight(1)
  6636. }
  6637. .width('100%')
  6638. .margin({ top: 10, bottom: 10 })
  6639. .justifyContent(FlexAlign.Start)
  6640. Row() {
  6641. Text('专辑艺术家:')
  6642. .fontSize(14)
  6643. .fontColor($r('app.color.text_color'))
  6644. .margin({ left: 22 })
  6645. Text(currentItem.ALBUMARTIST)
  6646. .fontSize(14)
  6647. .margin({ left: 10 })
  6648. .fontColor($r('app.color.text_color'))
  6649. .layoutWeight(1)
  6650. }
  6651. .width('100%')
  6652. .margin({ top: 10, bottom: 10 })
  6653. .justifyContent(FlexAlign.Start)
  6654. Row() {
  6655. Text('作曲家:')
  6656. .fontSize(14)
  6657. .fontColor($r('app.color.text_color'))
  6658. .margin({ left: 22 })
  6659. Text(currentItem.COMPOSER)
  6660. .fontSize(14)
  6661. .margin({ left: 10 })
  6662. .fontColor($r('app.color.text_color'))
  6663. .layoutWeight(1)
  6664. }
  6665. .width('100%')
  6666. .margin({ top: 10, bottom: 10 })
  6667. .justifyContent(FlexAlign.Start)
  6668. Row() {
  6669. Text('作词家:')
  6670. .fontSize(14)
  6671. .fontColor($r('app.color.text_color'))
  6672. .margin({ left: 22 })
  6673. Text(currentItem.LYRICIST)
  6674. .fontSize(14)
  6675. .margin({ left: 10 })
  6676. .fontColor($r('app.color.text_color'))
  6677. .layoutWeight(1)
  6678. }
  6679. .width('100%')
  6680. .margin({ top: 10, bottom: 10 })
  6681. .justifyContent(FlexAlign.Start)
  6682. Row() {
  6683. Text('注释:')
  6684. .fontSize(14)
  6685. .fontColor($r('app.color.text_color'))
  6686. .margin({ left: 22 })
  6687. Text(currentItem.COMMENT)
  6688. .fontSize(14)
  6689. .margin({ left: 10 })
  6690. .fontColor($r('app.color.text_color'))
  6691. .layoutWeight(1)
  6692. }
  6693. .width('100%')
  6694. .margin({ top: 10, bottom: 10 })
  6695. .justifyContent(FlexAlign.Start)
  6696. Row() {
  6697. Text('格式:')
  6698. .fontSize(14)
  6699. .fontColor($r('app.color.text_color'))
  6700. .margin({ left: 22 })
  6701. Text(Utility.formatMimeType(currentItem.mimeType))
  6702. .fontSize(14)
  6703. .margin({ left: 10 })
  6704. .fontColor($r('app.color.text_color'))
  6705. .layoutWeight(1)
  6706. }
  6707. .width('100%')
  6708. .margin({ top: 10, bottom: 10 })
  6709. .justifyContent(FlexAlign.Start)
  6710. Row() {
  6711. Text('播放次数:')
  6712. .fontSize(14)
  6713. .fontColor($r('app.color.text_color'))
  6714. .margin({ left: 22 })
  6715. Text(currentItem.playCount?.toString())
  6716. .fontSize(14)
  6717. .margin({ left: 10 })
  6718. .fontColor($r('app.color.text_color'))
  6719. .layoutWeight(1)
  6720. }
  6721. .width('100%')
  6722. .margin({ top: 10, bottom: 10 })
  6723. .justifyContent(FlexAlign.Start)
  6724. Row() {
  6725. Text('流数量:')
  6726. .fontSize(14)
  6727. .fontColor($r('app.color.text_color'))
  6728. .margin({ left: 22 })
  6729. Text(currentItem.nb_streams?.toString())
  6730. .fontSize(14)
  6731. .margin({ left: 10 })
  6732. .fontColor($r('app.color.text_color'))
  6733. .layoutWeight(1)
  6734. }
  6735. .width('100%')
  6736. .margin({ top: 10, bottom: 10 })
  6737. .justifyContent(FlexAlign.Start)
  6738. Row() {
  6739. Text('文件大小:')
  6740. .fontSize(14)
  6741. .fontColor($r('app.color.text_color'))
  6742. .margin({ left: 22 })
  6743. Text(currentItem.size)
  6744. .fontSize(14)
  6745. .margin({ left: 10 })
  6746. .fontColor($r('app.color.text_color'))
  6747. .layoutWeight(1)
  6748. }
  6749. .width('100%')
  6750. .margin({ top: 10, bottom: 10 })
  6751. .justifyContent(FlexAlign.Start)
  6752. Row() {
  6753. Text('文件名:')
  6754. .fontSize(14)
  6755. .fontColor($r('app.color.text_color'))
  6756. .margin({ left: 22 })
  6757. Text(currentItem.fileName)
  6758. .fontSize(14)
  6759. .margin({ left: 10 })
  6760. .fontColor($r('app.color.text_color'))
  6761. .layoutWeight(1)
  6762. }
  6763. .width('100%')
  6764. .margin({ top: 10, bottom: 10 })
  6765. .justifyContent(FlexAlign.Start)
  6766. Row() {
  6767. Text('修改时间:')
  6768. .fontSize(14)
  6769. .fontColor($r('app.color.text_color'))
  6770. .margin({ left: 22 })
  6771. Text(currentItem.cTime)
  6772. .fontSize(14)
  6773. .margin({ left: 10 })
  6774. .fontColor($r('app.color.text_color'))
  6775. .layoutWeight(1)
  6776. }
  6777. .width('100%')
  6778. .margin({ top: 10, bottom: 10 })
  6779. .justifyContent(FlexAlign.Start)
  6780. Row() {
  6781. Text('存放目录:')
  6782. .fontSize(14)
  6783. .fontColor($r('app.color.text_color'))
  6784. .margin({ left: 22 })
  6785. Text(currentItem.filePath)
  6786. .fontSize(12)
  6787. .margin({ left: 10 })
  6788. .fontColor($r('app.color.text_color'))
  6789. .layoutWeight(1)
  6790. }
  6791. .margin({ top: 10, bottom: 10 })
  6792. .width('100%')
  6793. .justifyContent(FlexAlign.Start)
  6794. Row() {
  6795. Text('内嵌歌词:')
  6796. .fontSize(14)
  6797. .fontColor($r('app.color.text_color'))
  6798. .margin({ left: 22 })
  6799. Text(currentItem.lyricContent)
  6800. .fontSize(12)
  6801. .copyOption(CopyOptions.InApp)
  6802. .margin({ left: 10 })
  6803. .fontColor($r('app.color.text_color'))
  6804. .layoutWeight(1)
  6805. }
  6806. .margin({ top: 10, bottom: 10 })
  6807. .width('100%')
  6808. .justifyContent(FlexAlign.Start)
  6809. }
  6810. }
  6811. .margin({ bottom: 20 })
  6812. }
  6813. //定时关闭布局
  6814. @Builder
  6815. TimeCloseSheet() {
  6816. Scroll() {
  6817. Column() {
  6818. this.TimeClose()
  6819. }
  6820. }
  6821. .width('100%')
  6822. .height('100%')
  6823. }
  6824. //倒计时关闭音乐,退出App功能实现。
  6825. @State selectedMinutes: number = 0 // 0表示未开启
  6826. @State remainingSeconds: number = 0
  6827. // 预设时间选项
  6828. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  6829. private formatTime(seconds: number): string {
  6830. const mins = Math.floor(seconds / 60)
  6831. const secs = seconds % 60
  6832. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  6833. }
  6834. // 开始倒计时
  6835. private handleTimeSelect(minutes: number) {
  6836. if (minutes === this.selectedMinutes) {
  6837. this.stopCountdown();
  6838. this.selectedMinutes = 0;
  6839. return;
  6840. }
  6841. this.selectedMinutes = minutes;
  6842. this.remainingSeconds = minutes * 60;
  6843. this.startCountdown(); // 新增调用
  6844. }
  6845. @Builder
  6846. TimeClose() {
  6847. Column() {
  6848. // 倒计时显示区域
  6849. Text(this.selectedMinutes > 0 ?
  6850. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  6851. "定时关闭未开启")
  6852. .fontSize(17)
  6853. .fontColor($r('app.color.text_color'))
  6854. .margin({ top: 2, bottom: 8 });
  6855. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  6856. ForEach(this.presetTimes, (minutes: number, index: number) => {
  6857. // 单行时间选项容器
  6858. Row() {
  6859. // 文字描述区域
  6860. Text(this.getDisplayText(minutes))
  6861. .fontSize(15)
  6862. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  6863. $r('app.color.text_color'))// 选中态颜色变化
  6864. .textAlign(TextAlign.Start)
  6865. .layoutWeight(1); // 占据剩余空间
  6866. // 复选框样式的选择器
  6867. Row() {
  6868. if (minutes === this.selectedMinutes) {
  6869. // 选中状态 - 带勾号的圆形复选框
  6870. Row() {
  6871. // 使用系统内置的勾号图标
  6872. Image($r('sys.media.ohos_ic_public_ok'))
  6873. .width(14)
  6874. .height(14)
  6875. .fillColor(Color.White)
  6876. }
  6877. .width(24)
  6878. .height(24)
  6879. .borderRadius(12)
  6880. .backgroundColor(this.themeColor)
  6881. .justifyContent(FlexAlign.Center)
  6882. .alignItems(VerticalAlign.Center)
  6883. } else {
  6884. // 未选中状态的圆形边框
  6885. Row()
  6886. .width(24)
  6887. .height(24)
  6888. .borderRadius(12)
  6889. .border({
  6890. width: 2,
  6891. color: $r('app.color.text_color'),
  6892. style: BorderStyle.Solid
  6893. })
  6894. .backgroundColor(Color.Transparent)
  6895. }
  6896. }
  6897. .width(24)
  6898. .height(24)
  6899. .margin({ left: 20 })
  6900. .justifyContent(FlexAlign.Center)
  6901. .alignItems(VerticalAlign.Center)
  6902. }
  6903. .width('100%')
  6904. .padding({
  6905. top: 18,
  6906. bottom: 18,
  6907. left: 18,
  6908. right: 18
  6909. })
  6910. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  6911. $r('app.color.bottom_control_background')) // 选中背景高亮
  6912. .borderRadius(12)
  6913. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6914. .margin({ bottom: 18 })
  6915. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  6916. });
  6917. }
  6918. .width('100%')
  6919. .padding(16)
  6920. }
  6921. }
  6922. // 获取显示文本
  6923. private getDisplayText(minutes: number): string {
  6924. if (minutes === -1) {
  6925. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  6926. }
  6927. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  6928. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  6929. }
  6930. // 处理选择事件
  6931. private handleSelect(minutes: number): void {
  6932. if (minutes === -1) { // 自定义
  6933. // 弹出自定义时间对话框
  6934. DialogHelper.showTextInputDialog({
  6935. title: '自定义时间',
  6936. maskColor: Color.Transparent,
  6937. inputType: InputType.Number,
  6938. text: '',
  6939. onChange: (text) => {
  6940. console.error("onChange: " + text);
  6941. },
  6942. onAction: (action, dialogId, content) => {
  6943. if (action == DialogAction.TWO) {
  6944. const customMinutes = Number(content);
  6945. if (customMinutes > 0) {
  6946. this.handleTimeSelect(customMinutes); // 设置自定义时间
  6947. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  6948. }
  6949. }
  6950. }
  6951. });
  6952. } else {
  6953. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  6954. }
  6955. }
  6956. // 添加定时器引用
  6957. private timerId: number = -1;
  6958. // 启动/重置倒计时
  6959. private startCountdown() {
  6960. // 清除旧定时器
  6961. if (this.timerId !== -1) {
  6962. clearInterval(this.timerId);
  6963. }
  6964. // 创建新定时器
  6965. if (this.selectedMinutes > 0) {
  6966. this.timerId = setInterval(() => {
  6967. if (this.remainingSeconds === 15) {
  6968. this.showConfirmationDialog();
  6969. }
  6970. if (this.remainingSeconds > 0) {
  6971. this.remainingSeconds -= 1;
  6972. } else {
  6973. this.stopCountdown();
  6974. this.handleTimeout();
  6975. }
  6976. }, 1000);
  6977. }
  6978. }
  6979. // 15倒计时后再次提示显示确认是否关闭App对话框
  6980. private showConfirmationDialog() {
  6981. DialogHelper.showAlertDialog({
  6982. backgroundColor: $r('app.color.btn_green'),
  6983. title: '确认关闭',
  6984. maskColor: Color.Transparent,
  6985. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  6986. borderStyle: BorderStyle.Dashed,
  6987. primaryButton: '暂不关闭',
  6988. secondaryButton: '确定',
  6989. onAction: (action) => {
  6990. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  6991. this.stopCountdown();
  6992. this.selectedMinutes = 0
  6993. } else if (action == DialogAction.TWO) {
  6994. }
  6995. }
  6996. })
  6997. }
  6998. // 停止倒计时
  6999. private stopCountdown() {
  7000. if (this.timerId !== -1) {
  7001. clearInterval(this.timerId);
  7002. this.timerId = -1;
  7003. }
  7004. }
  7005. // 超时处理
  7006. private handleTimeout() {
  7007. // 执行播放器关闭逻辑
  7008. this.selectedMinutes = 0;
  7009. ToastUtil.showToast(" 定时关闭已完成");
  7010. this.stop(); // 假设存在的播放器实例
  7011. //退出APP
  7012. const mContext = getContext(this) as common.UIAbilityContext
  7013. mContext.terminateSelf();
  7014. AvSessionController.getInstance(true).unregisterSessionListener()
  7015. }
  7016. //倒计时关闭音乐,退出App功能实现结束。
  7017. //播放列表的拖动List 重新排序
  7018. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  7019. //左滑操作 移动文件 重命名 删除等操作
  7020. @Builder
  7021. sonButton(item: VideoItem, index: number, filePath: string) {
  7022. Row() {
  7023. //加入下一首播放
  7024. Button() {
  7025. Image($r('app.media.next_to_play'))
  7026. .fillColor(Color.White)
  7027. .width(20)
  7028. }
  7029. .width(40)
  7030. .height(40)
  7031. .type(ButtonType.Circle)
  7032. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  7033. .backgroundColor(this.themeColor)
  7034. .margin(5)
  7035. .onClick(() => {
  7036. this.addToNextPlay(item);
  7037. })
  7038. Button() {
  7039. Image($r('app.media.close'))
  7040. .fillColor(Color.White)
  7041. .width(20)
  7042. }
  7043. .width(40)
  7044. .height(40)
  7045. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  7046. .type(ButtonType.Circle)
  7047. .backgroundColor(this.themeColor)
  7048. .margin(5)
  7049. .onClick(() => {
  7050. this.songList.splice(Number(index), 1)
  7051. this.sonDataSource.pushArrayData(this.songList)
  7052. })
  7053. Button() {
  7054. Image($r('app.media.share2'))
  7055. .fillColor(Color.White)
  7056. .width(20)
  7057. }
  7058. .width(40)
  7059. .height(40)
  7060. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  7061. .type(ButtonType.Circle)
  7062. .backgroundColor(this.themeColor)
  7063. .margin(5)
  7064. .onClick(() => {
  7065. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  7066. })
  7067. }
  7068. }
  7069. itemMoveSon(index: number, newIndex: number): void {
  7070. if (newIndex < 0 || newIndex >= this.songList.length) {
  7071. return;
  7072. }
  7073. let tmp = this.songList.splice(index, 1);
  7074. this.songList.splice(newIndex, 0, tmp[0]);
  7075. this.sonDataSource.pushArrayData(this.songList)
  7076. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  7077. if(this.modeType==4&&this.playlistTable){
  7078. updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
  7079. }
  7080. }
  7081. @Builder
  7082. PlayList() {
  7083. List({ scroller: this.playListScroller }) {
  7084. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  7085. ListItem() {
  7086. this.MusicItemSon(item, index)
  7087. }
  7088. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  7089. .animation({
  7090. duration: 666,
  7091. curve: 'ease-in-out' // 可选动画曲线
  7092. })
  7093. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  7094. TransitionEffect.scale({ x: 0, y: 0 })))
  7095. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  7096. //拖动List关键代码开始
  7097. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  7098. .zIndex(this.dragItem === index ? 1 : 0)
  7099. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  7100. .gesture(
  7101. GestureGroup(GestureMode.Sequence,
  7102. LongPressGesture({ repeat: true })
  7103. .onAction((event?: GestureEvent) => {
  7104. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  7105. this.scaleItem = index
  7106. })
  7107. })
  7108. .onActionEnd(() => {
  7109. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  7110. this.scaleItem = -1
  7111. })
  7112. }),
  7113. PanGesture({ fingers: 1, direction: null, distance: 0 })
  7114. .onActionStart(() => {
  7115. this.dragItem = index // 记录当前拖动项索引
  7116. this.dragRefOffset = 0 // 重置偏移基准
  7117. })
  7118. .onActionUpdate((event: GestureEvent) => {
  7119. this.offsetY = event.offsetY - this.dragRefOffset;
  7120. this.neighborItem = -1;
  7121. let indexA = this.songList.indexOf(item);
  7122. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  7123. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  7124. let value: number = 0;
  7125. if (this.offsetY < 0) {
  7126. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  7127. this.neighborItem = indexA - 1;
  7128. this.neighborScale = 1 - value / 20;
  7129. } else if (this.offsetY > 0) {
  7130. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  7131. this.neighborItem = indexA + 1;
  7132. this.neighborScale = 1 - value / 20;
  7133. }
  7134. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  7135. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  7136. this.offsetY -= this.ITEM_INTV;
  7137. this.dragRefOffset += this.ITEM_INTV;
  7138. this.itemMoveSon(indexA, indexA + 1);
  7139. });
  7140. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  7141. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  7142. this.offsetY += this.ITEM_INTV;
  7143. this.dragRefOffset -= this.ITEM_INTV;
  7144. this.itemMoveSon(indexA, indexA - 1);
  7145. });
  7146. }
  7147. })
  7148. .onActionEnd((event: GestureEvent) => {
  7149. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  7150. this.dragItem = -1
  7151. this.neighborItem = -1
  7152. })
  7153. animateTo({
  7154. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  7155. }, () => {
  7156. this.scaleItem = -1
  7157. })
  7158. })
  7159. )
  7160. .onCancel(() => {
  7161. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  7162. this.dragItem = -1
  7163. this.neighborItem = -1
  7164. })
  7165. animateTo({
  7166. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  7167. }, () => {
  7168. this.scaleItem = -1
  7169. })
  7170. })
  7171. ) //拖动List关键代码结束
  7172. .onClick(() => {
  7173. this.doPlay(item, index, true)
  7174. })
  7175. }, (item: VideoItem) => item.filePath)
  7176. }
  7177. .width('100%')
  7178. .height('100%')
  7179. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  7180. // .animation({ duration: 500, curve: Curve.Ease }))
  7181. .cachedCount(10)
  7182. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  7183. .gesture(PinchGesture({ fingers: 2 })
  7184. .onActionEnd((event: GestureEvent) => {
  7185. this.setSonListTwoFingers()
  7186. })
  7187. .onActionUpdate(e => {
  7188. this.scaleValue = this.pinchValue * e.scale
  7189. })
  7190. .onActionStart(e => {
  7191. }))
  7192. .padding({
  7193. bottom: 0
  7194. })
  7195. }
  7196. setSonListTwoFingers() {
  7197. this.pinchValue = this.scaleValue;
  7198. Logger.info('this.pinchValue = ' + this.pinchValue);
  7199. if (this.pinchValue >= 1) {
  7200. this.sonTwoFingerType++
  7201. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  7202. if (this.sonTwoFingerType > 3) {
  7203. this.sonTwoFingerType = 1
  7204. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  7205. }
  7206. } else {
  7207. this.sonTwoFingerType--
  7208. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  7209. if (this.sonTwoFingerType < 1) {
  7210. this.sonTwoFingerType = 1
  7211. }
  7212. }
  7213. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  7214. this.pinchValue = 1;
  7215. this.scaleValue = 1;
  7216. }
  7217. @State sonTwoFingerType:number = 3
  7218. @Builder
  7219. private MusicItemSon(item: VideoItem, index?: number) {
  7220. Button({ type: ButtonType.Normal, stateEffect: true }) {
  7221. Row() {
  7222. Stack() {
  7223. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  7224. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  7225. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  7226. .alt($r('app.media.music_red'))
  7227. .fillColor(this.themeColor)
  7228. .borderRadius('100%')
  7229. .clip(true)
  7230. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  7231. .draggable(false)// 禁止长按手势拖动
  7232. .autoResize(true) // 重采样,可减少内存占用
  7233. .margin({ left: 20 })
  7234. }
  7235. .width('15%')
  7236. Column() {
  7237. Column() {
  7238. Text(this.isShowFileName?item.fileName :item.name)
  7239. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  7240. .fontColor(this.curIndex === index ? this.themeColor :
  7241. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  7242. .maxLines(1)
  7243. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  7244. Row() {
  7245. Column(){
  7246. Text(item.md5Str?.includes('Lossless')?
  7247. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  7248. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  7249. .padding({ top: 3,right:6,left:6,bottom:3 })
  7250. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  7251. $r('app.color.text_color'))
  7252. .fontWeight(500)
  7253. .borderRadius(12)
  7254. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  7255. .backgroundColor('#FFC107')
  7256. }
  7257. .padding({ top: 8 })
  7258. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  7259. item.artist + ' ' + item?.duration)
  7260. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  7261. .padding({ top: 8 })
  7262. .maxLines(1)
  7263. .fontColor(this.curIndex === index ? this.themeColor :
  7264. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  7265. .margin({ left: this.sonTwoFingerType == 3 ? 5 : 3 })
  7266. Blank()
  7267. Text(item.size)
  7268. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  7269. .padding({ top: 8 })
  7270. .maxLines(1)
  7271. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  7272. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  7273. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  7274. .margin({ left: 10 })
  7275. }
  7276. }
  7277. .height('100%')
  7278. .width('100%')
  7279. .justifyContent(FlexAlign.Center)
  7280. .alignItems(HorizontalAlign.Start)
  7281. }
  7282. .height('100%')
  7283. .width('65%')
  7284. Column() {
  7285. ImageAnimator()
  7286. .images(this.imagesF)// 动画数组
  7287. .duration(1000)// 持续
  7288. .state(this.animationState)// 动画状态
  7289. .fillMode(FillMode.Forwards)
  7290. .width(18)
  7291. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  7292. Visibility.None)
  7293. .height(18)
  7294. .iterations(-1) // 播放次数
  7295. }
  7296. .width('20%')
  7297. }
  7298. }
  7299. .backgroundColor(Color.Transparent)
  7300. .width('100%')
  7301. .reuseId('son_item')
  7302. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  7303. .shadow(this.scaleItem === index ? {
  7304. radius: 70,
  7305. color: '#15000000',
  7306. offsetX: 0,
  7307. offsetY: 0
  7308. } :
  7309. {
  7310. radius: 0,
  7311. color: '#15000000',
  7312. offsetX: 0,
  7313. offsetY: 0
  7314. })
  7315. .animation({ curve: Curve.Sharp, duration: 300 })
  7316. }
  7317. @Builder
  7318. MusicPlayBuilder() {
  7319. Column() {
  7320. this.IjkMusicPlayerView()
  7321. }
  7322. .transition(TransitionEffect.asymmetric(
  7323. TransitionEffect.opacity(1),
  7324. TransitionEffect.OPACITY
  7325. ))
  7326. .visualEffect(deviceInfo.sdkApiVersion>=20&&this.bgController?
  7327. new hdsEffect.HdsEffectBuilder()
  7328. .shaderEffect({
  7329. effectType: hdsEffect.EffectType.UV_BACKGROUND_FLOW_LIGHT,
  7330. animation: {
  7331. duration: 10000,
  7332. iterations: -1,
  7333. autoPlay: true,
  7334. onFinish: ()=> {
  7335. console.info('Succeeded in finishing');
  7336. }
  7337. },
  7338. controller: this.bgController,
  7339. })
  7340. .buildEffect():null)
  7341. .height('100%')
  7342. .width('100%')
  7343. .onDisAppear(() => {
  7344. this.translateY = 0;
  7345. })
  7346. .translate({ y: this.translateY })
  7347. .gesture(
  7348. PanGesture(this.panOption)
  7349. .onActionUpdate((event?: GestureEvent) => {
  7350. if (event) {
  7351. // 只允许向下滑动,向上滑动时限制为0
  7352. this.translateY = Math.max(0, event.offsetY);
  7353. }
  7354. })
  7355. .onActionEnd((event?: GestureEvent) => {
  7356. // 使用更低的阈值和滑动速度判断
  7357. const minDistance = 100; // 最小滑动距离 100vp
  7358. const minVelocity = 500; // 最小滑动速度
  7359. // 获取滑动速度(如果可用)
  7360. const velocity = event?.velocityY || 0;
  7361. // 判断是否应该关闭:距离足够 或者 速度足够快
  7362. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  7363. if (shouldClose) {
  7364. // 添加关闭动画
  7365. this.getUIContext().animateTo({
  7366. duration: 300,
  7367. curve: Curve.Smooth
  7368. }, () => {
  7369. this.isShowPlay = false;
  7370. this.translateY = 0;
  7371. })
  7372. } else {
  7373. // 回弹动画
  7374. this.getUIContext().animateTo({
  7375. duration: 300,
  7376. curve: Curve.Smooth
  7377. }, () => {
  7378. this.translateY = 0;
  7379. })
  7380. }
  7381. })
  7382. )
  7383. }
  7384. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  7385. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  7386. HeightBreakpoint.HEIGHT_LG;
  7387. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  7388. @State topBarHeight: number = 50
  7389. @State barOpacity: number = 1
  7390. @State barBottomOpacity: number = 1
  7391. private hideDone: boolean = false;
  7392. @State currentYOffset: number = 0;
  7393. @State bottomBarHeight: number = 68;
  7394. private isHiding: boolean = false;
  7395. //是否是Pura X外屏,或者小屏幕
  7396. isPuraWP() {
  7397. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  7398. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  7399. }
  7400. //是否是Pura X外屏,或者小屏幕,手机横屏
  7401. /**
  7402. * 是否是Pura X外屏,或者小屏幕,手机横屏
  7403. * @returns
  7404. */
  7405. isCoverOpacity() {
  7406. if (this.isPuraWP()) {
  7407. return true
  7408. }
  7409. if (this.isPhoneLan()) {
  7410. return true
  7411. }
  7412. if (deviceInfo.marketName.includes('Pura X')
  7413. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  7414. return true
  7415. }
  7416. return false
  7417. }
  7418. //是不是手机横屏
  7419. isPhoneLan() {
  7420. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  7421. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  7422. LogUtil.info('hicar isPhoneLan width= ' + this.windowWidth);
  7423. LogUtil.info('hicar isPhoneLan height= ' + this.windowHeight);
  7424. LogUtil.info(`twocold hicarWindow size: ${this.windowWidth}x${this.windowHeight}, this.isHiCarStatus: ${this.isHiCarStatus}`);
  7425. LogUtil.info(`twocold hicar Window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall: ${this.isHiCarSmall()}`);
  7426. if (this.isHiCarKuanBianPing()) {
  7427. return true
  7428. }
  7429. if (this.isHiCar()) {
  7430. return false
  7431. }
  7432. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  7433. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  7434. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  7435. return true
  7436. }
  7437. return false
  7438. }
  7439. //是不是1920x720的hicar的屏幕分辨率
  7440. isHiCarKuanBianPing(){
  7441. if(!this.isHiCar()){
  7442. return false
  7443. }
  7444. const hiCarAspectRatios: HiCarAspectRatio[] = [
  7445. { ratio: 1920 / 720, name: "1920x720" },
  7446. ];
  7447. const currentRatio: number = this.windowWidth / this.windowHeight;
  7448. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  7449. LogUtil.info('twocold isHiCarKuanBianPing currentRatio = ' + currentRatio)
  7450. for (const hiCarRatio of hiCarAspectRatios) {
  7451. LogUtil.info('twocold isHiCarKuanBianPing hiCarRatio= ' + hiCarRatio.ratio)
  7452. LogUtil.info('twocold isHiCarKuanBianPing Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  7453. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  7454. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  7455. //宽扁平的尺寸设置列表展示
  7456. this.twoFingerType ==3
  7457. this.isGridMusic = false
  7458. return true;
  7459. }
  7460. }
  7461. return false;
  7462. }
  7463. //是不是hicar的屏幕分辨率
  7464. isHiCarSmall() {
  7465. if(!this.isHiCar()){
  7466. return false
  7467. }
  7468. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  7469. {
  7470. this.columns = 6
  7471. return false
  7472. }
  7473. const hiCarAspectRatios: HiCarAspectRatio[] = [
  7474. { ratio: 800 / 480, name: "800x480" },
  7475. { ratio: 1280 / 720, name: "1280x720" },
  7476. { ratio: 1920 / 1080, name: "1920x1080" },
  7477. ];
  7478. const currentRatio: number = this.windowWidth / this.windowHeight;
  7479. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  7480. LogUtil.info('twocold isHiCarSmall currentRatio = ' + currentRatio)
  7481. for (const hiCarRatio of hiCarAspectRatios) {
  7482. LogUtil.info('twocold isHiCarSmall hiCarRatio= ' + hiCarRatio.ratio)
  7483. LogUtil.info('twocold isHiCarSmall Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  7484. LogUtil.info('twocold isHiCarSmall isHiCarStatus= ' + this.isHiCarStatus);
  7485. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  7486. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  7487. //宽扁平的尺寸设置列表展示
  7488. return true;
  7489. }
  7490. }
  7491. return false;
  7492. }
  7493. isHiCar() {
  7494. return this.isHiCarStatus&&this.curDisplayIsHiCar;
  7495. }
  7496. //是不是正常的手机竖屏
  7497. isPhonePortrait() {
  7498. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  7499. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  7500. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  7501. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  7502. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  7503. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  7504. return true
  7505. }
  7506. return false
  7507. }
  7508. @State showSpeedDialog: boolean = false
  7509. @State longPressSpeed: number = 3 //长按默认倍数
  7510. @Builder
  7511. SpeedDialog() {
  7512. Stack() {
  7513. Column() {
  7514. Text('已切换至' + this.longPressSpeed + '倍速播放')
  7515. .fontColor(Color.White)
  7516. .visibility(Visibility.Hidden)
  7517. }
  7518. .backgroundColor(Color.Black)
  7519. .borderRadius(20)
  7520. .padding({
  7521. top: 10,
  7522. right: 20,
  7523. left: 15,
  7524. bottom: 20
  7525. })
  7526. .opacity(0.6)
  7527. Text('已切换至' + this.longPressSpeed + '倍速播放')
  7528. .fontColor(Color.White)
  7529. }
  7530. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  7531. .zIndex(5)
  7532. .margin({ top: 80 })
  7533. }
  7534. @Builder
  7535. IjkMusicPlayerView() {
  7536. Stack() {
  7537. if(canIUse("SystemCapability.UIDesign.HDSComponent.Core")
  7538. &&deviceInfo.sdkApiVersion>=20&&this.sceneBgController){
  7539. HdsVisualComponent()
  7540. .scene(HdsSceneType.DUAL_EDGE_FLOW_LIGHT_WITH_BACKGROUND_MASK, this.sceneBgController, () => {
  7541. console.info('Succeeded in finishing');
  7542. })
  7543. .width('100%')
  7544. .height('100%')
  7545. .visibility(this.isShowBgLiuGUANG?Visibility.Visible:Visibility.None)
  7546. }
  7547. Column() {
  7548. Column() {
  7549. //播放标题
  7550. Column() {
  7551. this.PlayTitle()
  7552. }
  7553. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  7554. .width('100%')
  7555. .margin({ top: 0 })
  7556. .height(PlayConstants.HEIGHT)
  7557. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  7558. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  7559. if (this.showSpeedDialog) {
  7560. this.SpeedDialog()
  7561. }
  7562. Stack() {
  7563. //手势拖动快进
  7564. Column()
  7565. .width(CommonConstants.FULL_PERCENT)
  7566. .height('100%')
  7567. .gesture(
  7568. GestureGroup(GestureMode.Parallel,
  7569. // 长按屏幕倍数播放
  7570. LongPressGesture({ repeat: true })
  7571. .onAction(() => {
  7572. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  7573. this.showSpeedDialog = true;
  7574. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  7575. }
  7576. })
  7577. .onActionEnd(() => {
  7578. this.showSpeedDialog = false;
  7579. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  7580. }),
  7581. //双击屏幕暂停或者播放
  7582. TapGesture({ count: 2 })
  7583. .onAction((event: GestureEvent) => {
  7584. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  7585. ToastUtil.showToast('已暂停')
  7586. }
  7587. console.info('onecold playOrPause 6693')
  7588. this.playOrPause()
  7589. })
  7590. )
  7591. )
  7592. }
  7593. .height('65%')
  7594. Swiper() {
  7595. this.CoverInfo()
  7596. this.PlayerLyrics()
  7597. }
  7598. .onChange((index: number) => {
  7599. this.currentSwiperIndex = index
  7600. })
  7601. .indicator(false)
  7602. .displayCount(new BreakpointType({
  7603. sm: 1,
  7604. md: 2,
  7605. lg: 2,
  7606. xl: 2,
  7607. xxl: 2
  7608. }).getValue(this.currentBreakpoint))
  7609. .clip(false)
  7610. .loop(false)
  7611. .autoPlay(false)
  7612. // .interval(8000)
  7613. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  7614. .height('100%')
  7615. .hitTestBehavior(HitTestMode.Transparent)
  7616. Image($r('app.media.icon_replay'))
  7617. .objectFit(ImageFit.Auto)
  7618. .width('120px')
  7619. .height('120px')
  7620. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  7621. .border({ width: 0 })
  7622. .visibility(Visibility.None)
  7623. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  7624. .onClick(() => {
  7625. console.info('onecold startPlayOrResumePlay 6744')
  7626. this.startPlayOrResumePlay();
  7627. })
  7628. }
  7629. .width(CommonConstants.FULL_PERCENT)
  7630. .height(CommonConstants.FULL_PERCENT)
  7631. .justifyContent(FlexAlign.End)
  7632. }
  7633. .justifyContent(FlexAlign.End)
  7634. .margin({ bottom: 8 })
  7635. }
  7636. .backgroundImage(!this.isMusicBGCover||StrUtil.isEmpty(this.cover)?null: this.cover)
  7637. .backgroundImageSize(this.isPuraWP()||!this.isMusicBGCover ? { width: '100%' } : { height: '150%', width: '100%' })
  7638. .animation({
  7639. duration: 666,
  7640. curve: 'ease-in-out' // 可选动画曲线
  7641. })
  7642. .backgroundBlurStyle((this.isPuraWP() && this.currentSwiperIndex === 0) ||!this.isMusicBGCover
  7643. ? BlurStyle.NONE :
  7644. BlurStyle.BACKGROUND_ULTRA_THICK)
  7645. .hitTestBehavior(HitTestMode.Transparent)
  7646. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  7647. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  7648. .onClick(() => {
  7649. if(this.isHiCar())
  7650. return
  7651. if(this.is_auto_hide_progress){
  7652. this.is_auto_hide_progress = false
  7653. }
  7654. this.startAutoHide()
  7655. })
  7656. }
  7657. @State progressValue: number = 0;
  7658. @State currentTime: string = "00:00";
  7659. @State totalTime: string = "00:00";
  7660. @State loadingVisible: Visibility = Visibility.None;
  7661. @State replayVisible: Visibility = Visibility.None;
  7662. @State slideEnable: boolean = false;
  7663. @State aspRatio: number = 0.5;
  7664. @State mContext: object | undefined = undefined;
  7665. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  7666. @State mFirst: boolean = true;
  7667. @State mDestroyPage: boolean = false;
  7668. @State playSpeed: number = 1;
  7669. @State oldSeconds: number = 0;
  7670. @State isSeekTo: boolean = false;
  7671. @State isCurrentTime: boolean = false;
  7672. @State videoWidth: string = '100%';
  7673. @State videoHeight: string = '100%';
  7674. @State initAspectRatio: number = 1;
  7675. @State videoAspectRatio: number = this.initAspectRatio;
  7676. @State videoUrl: string = '';
  7677. private last: number = 0;
  7678. @State videoParentAspectRatio: number = this.initAspectRatio;
  7679. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  7680. @State CONTROL_PlayStatus: number = PlayStatus.INIT;
  7681. @State PROGRESS_MAX_VALUE: number = 100;
  7682. @State updateProgressTimer: number = 0;
  7683. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  7684. @State name: string = '';
  7685. // @State loop: boolean = false;
  7686. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  7687. @State multiple: string = '1.0X';
  7688. xcomponentController: XComponentController = new XComponentController()
  7689. private panOptionBright: PanGestureOptions =
  7690. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  7691. private panOptionVolume: PanGestureOptions =
  7692. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  7693. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  7694. //手势的音量控制和亮度控制
  7695. private positionX: number = PlayConstants.POSITION_X;
  7696. private positionY: number = PlayConstants.POSITION_Y;
  7697. private windowClass: window.Window = globalThis.windowClass
  7698. @State volume: number = 0.5;
  7699. @State volumeSmall: boolean = false
  7700. @State autoParseMusicName: boolean = true
  7701. @State isShowFileName: boolean = false
  7702. @State isLongNameRoLL: boolean = true//长歌名滚动
  7703. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  7704. @State bright: number = PlayConstants.BRIGHT;
  7705. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  7706. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  7707. @State screenWidth: number = 0
  7708. @State screenHeight: number = 0
  7709. @State statusBarHeight: number = 0
  7710. @State isYesFull: boolean = false
  7711. private seekValue: number = 0
  7712. @State isVideoLock: boolean = false; // Whether the video playback is locked
  7713. eventHub = getContext().eventHub;
  7714. //投播组件
  7715. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  7716. private castController: avSession.AVCastController | undefined = undefined;
  7717. @State isCastPlaying: boolean = false;
  7718. @State currentTime2: number = 0;
  7719. @State currentStringTime: string = '00:00';
  7720. @State duration: number = 0;
  7721. @State isReady: boolean = false;
  7722. @State durationTime: number = 0;
  7723. @State durationStringTime: string = '00:00';
  7724. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  7725. // @State isPlaying: boolean = false;
  7726. private castSeek: boolean = false;
  7727. private castItem: avSession.AVQueueItem | undefined = undefined;
  7728. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  7729. @State rotateAngle2: number = -9
  7730. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  7731. @State cover: string | undefined = '';
  7732. @State artist: string | undefined = ''
  7733. // 1.初始化controller
  7734. private lyricController: LyricController = new LyricController()
  7735. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  7736. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  7737. private parser = new LyricParser()
  7738. @State randomColor: string = 'rgb(0,0,0)'
  7739. @State randomShakenX: number = 0
  7740. @State randomShakenY: number = 0
  7741. @State lyricTextSize: number = 24
  7742. @State lyricContent: string = ''
  7743. @State isDebug: boolean = false
  7744. @State isHightLightCenter: boolean = true
  7745. /**
  7746. * 初始化歌词加载与展示逻辑
  7747. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  7748. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  7749. * @param isApi2 是否使用API2获取歌词(可选)
  7750. *
  7751. * 主要流程:
  7752. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  7753. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  7754. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  7755. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  7756. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  7757. * 6. 解析失败或读取失败时,清空歌词显示。
  7758. *
  7759. * 注意事项:
  7760. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  7761. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  7762. * - 歌词内容解析后通过lyricController驱动UI渲染。
  7763. */
  7764. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  7765. if (StrUtil.isEmpty(lyricPath)) {
  7766. return
  7767. }
  7768. this.initPipLyricSetting()
  7769. this.lyricControllerSingle
  7770. .setTextSize(15)
  7771. .setCacheSize(4)
  7772. .setTextColor("#FFFFFF")
  7773. .setHighlightColor("#FFFFFF")
  7774. .setHighlightScale(1.2)
  7775. .setEmptyHint("")
  7776. .setAlignMode('center')
  7777. .setAnimationDuration(500)
  7778. .setSingleLine(true)
  7779. this.lyricContent = ''
  7780. this.lyricController
  7781. .setTextSize(this.currentLyricSize)
  7782. .setCacheSize(4)
  7783. .setTextColor("#DDDDDD")
  7784. .setHighlightColor("#FFFFFF")
  7785. .setEmptyHint("")
  7786. .setAnimationDuration(1000)
  7787. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  7788. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  7789. this.setBlurDegree(this.blurDegree, false)
  7790. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  7791. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  7792. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  7793. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  7794. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  7795. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  7796. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  7797. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  7798. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  7799. this.lyricController.setTextWeight(this.lyricTextWeight)
  7800. this.showSingleLyric = false
  7801. this.timeOffset = 0
  7802. this.lyricController.setLyric(null)
  7803. this.lyricControllerSingle.setLyric(null)
  7804. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  7805. console.log("onecold lyricPath =" + lyricPath)
  7806. let neiqianLrc = ''
  7807. let lyContent = this.currentSong?.lyricContent
  7808. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  7809. neiqianLrc = lyContent
  7810. }
  7811. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast&&!isLocal&&!isLocal) {
  7812. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  7813. //赋值给this.lyricContent,播控中心才可以显示歌词
  7814. this.lyricContent = neiqianLrc
  7815. // 将文件内容按行分割成字符串数组
  7816. let lines = neiqianLrc.split('\n').map(line => line.trim());
  7817. // 3.解析歌词
  7818. let lyric = this.parser.parse(lines);
  7819. // 4.设置歌词
  7820. this.lyricController.setLyric(lyric);
  7821. this.lyricControllerXF.setLyric(lyric)
  7822. this.lyricControllerSingle.setLyric(lyric)
  7823. return
  7824. }
  7825. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  7826. && !Utility.isVideoByExtension(this.videoUrl))) {
  7827. if (this.currentSong !== undefined) {
  7828. // ToastUtil.showShort('正在为你搜索在线歌词!')
  7829. //判断是不是赞助会员,是会员的话才开启歌词功能
  7830. // if (!this.isDebug) {
  7831. // if (!Utility.isNoble()) {
  7832. // LogUtil.debug("onecold 不是赞助会员")
  7833. // return
  7834. // }
  7835. // if(!Utility.isPassInstallTime(33)){
  7836. // LogUtil.debug("onecold not pass time")
  7837. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  7838. // return
  7839. // }
  7840. // }
  7841. let artist = this.currentSong?.artist
  7842. if (artist === undefined) {
  7843. artist = ''
  7844. }
  7845. if (isApi2 === undefined) {
  7846. isApi2 = false
  7847. }
  7848. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  7849. // LogUtil.debug("onecold res =" + res)
  7850. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  7851. if (StrUtil.isNotEmpty(res)) {
  7852. this.lyricContent = res
  7853. let lines = res.split('\n').map(line => line.trim());
  7854. // 3.解析歌词
  7855. let lyric = this.parser.parse(lines);
  7856. // 4.设置歌词
  7857. this.lyricController.setLyric(lyric);
  7858. this.lyricControllerXF.setLyric(lyric)
  7859. this.lyricControllerSingle.setLyric(lyric)
  7860. this.showSingleLyric = true
  7861. // 4.保存歌词文件lyric到本地
  7862. //2025年8月28日歌词不再加密下载
  7863. this.saveDataToFile(res, lyricPath, false)
  7864. } else {
  7865. this.lyricController.setLyric(null)
  7866. this.lyricControllerXF.setLyric(null)
  7867. this.lyricControllerSingle.setLyric(null)
  7868. if (isOnLineAndToast) {
  7869. ToastUtil.showShort('未获取到歌词!')
  7870. }
  7871. }
  7872. } else {
  7873. this.lyricController.setLyric(null)
  7874. this.lyricControllerXF.setLyric(null)
  7875. this.lyricControllerSingle.setLyric(null)
  7876. if (isOnLineAndToast) {
  7877. ToastUtil.showShort('未获取到歌词!')
  7878. }
  7879. }
  7880. })
  7881. } else {
  7882. this.lyricController.setLyric(null)
  7883. this.lyricControllerXF.setLyric(null)
  7884. this.lyricControllerSingle.setLyric(null)
  7885. if (isOnLineAndToast) {
  7886. ToastUtil.showShort('未获取到歌词!')
  7887. }
  7888. }
  7889. return
  7890. }
  7891. try {
  7892. let isJiaMi = false;
  7893. let realLyricPath = lyricPath
  7894. if (FileUtil.accessSync(jiaMilyricPath)) {
  7895. isJiaMi = true
  7896. realLyricPath = jiaMilyricPath
  7897. console.info("onecold 找到加密本地歌词 ");
  7898. } else {
  7899. isJiaMi = false
  7900. realLyricPath = lyricPath
  7901. console.info("onecold 找到本地歌词 ");
  7902. }
  7903. // 3.读取文件内容并指定编码为 UTF-8
  7904. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  7905. const stat = await fileIo.stat(file.fd);
  7906. const arrayBuffer = new ArrayBuffer(stat.size);
  7907. fs.read(file.fd, arrayBuffer)
  7908. .then((readLen: number) => {
  7909. console.info("read file data succeed");
  7910. // let buf = buffer.from(arrayBuffer, 0, readLen);
  7911. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  7912. // 检查 buf 是否为空
  7913. if (buf.length === 0) {
  7914. throw new Error("Buffer is empty after reading the file");
  7915. }
  7916. try {
  7917. // 检测文件编码
  7918. // let detectedEncoding = chardet.detect(buf);
  7919. // console.info("onecoldT Detected encoding: " + detectedEncoding);
  7920. let detectedEncoding = this.detect(arrayBuffer)
  7921. console.info("onecoldT Detected encoding: " + detectedEncoding);
  7922. // 使用检测到的编码解码,解决中文乱码问题
  7923. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  7924. console.info("onecoldT Detected textDecoder: " + textDecoder);
  7925. let fileContent = textDecoder.decode(buf);
  7926. console.info(`onecoldT The content of file1: ${fileContent}`);
  7927. //解密
  7928. if (isJiaMi) {
  7929. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  7930. }
  7931. console.info(`onecold The content of file2: ${fileContent}`);
  7932. this.lyricContent = fileContent
  7933. if(isLocal){//编辑标签选择本地歌词需要赋值给this.lyricConStr
  7934. this.lyricConStr = fileContent
  7935. }
  7936. // 将文件内容按行分割成字符串数组
  7937. let lines = fileContent.split('\n').map(line => line.trim());
  7938. console.info(`onecold The content of file: ${fileContent}`);
  7939. // 3.解析歌词
  7940. let lyric = this.parser.parse(lines);
  7941. // 4.设置歌词
  7942. this.lyricController.setLyric(lyric);
  7943. this.lyricControllerXF.setLyric(lyric)
  7944. this.lyricControllerSingle.setLyric(lyric)
  7945. this.showSingleLyric = true
  7946. console.info(`The content of file: ${fileContent}`);
  7947. } catch (chardetError) {
  7948. console.error("chardet.detect failed with error: " + chardetError.message);
  7949. this.lyricController.setLyric(null);
  7950. this.lyricControllerXF.setLyric(null)
  7951. this.lyricControllerSingle.setLyric(null)
  7952. }
  7953. })
  7954. .catch((err: BusinessError) => {
  7955. this.lyricController.setLyric(null)
  7956. this.lyricControllerXF.setLyric(null)
  7957. this.lyricControllerSingle.setLyric(null)
  7958. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  7959. })
  7960. .catch((err: Error) => {
  7961. this.lyricController.setLyric(null)
  7962. this.lyricControllerXF.setLyric(null)
  7963. this.lyricControllerSingle.setLyric(null)
  7964. console.error("read file 2 data failed with error message: " + err.message);
  7965. })
  7966. .finally(() => {
  7967. fs.closeSync(file);
  7968. });
  7969. } catch (error) {
  7970. this.lyricController.setLyric(null)
  7971. this.lyricControllerSingle.setLyric(null)
  7972. this.lyricControllerXF.setLyric(null)
  7973. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  7974. }
  7975. }
  7976. detect(data: ArrayBuffer): string {
  7977. //创建检测对象
  7978. let detector: UniversalDetector = new UniversalDetector();
  7979. // 传入检测数据并实时判断编码格式
  7980. detector.handleData(data, 0, data.byteLength);
  7981. // 标记检测数据 读取结束
  7982. detector.dataEnd();
  7983. // 获取检测结果
  7984. let detected: string = detector.getDetectedCharset();
  7985. // 释放资源
  7986. detector.reset();
  7987. return detected;
  7988. }
  7989. //初始化悬浮歌词的自定义设置
  7990. initPipLyricSetting() {
  7991. this.lyricControllerXF
  7992. .setTextSize(this.currentLyricSize)
  7993. .setCacheSize(4)
  7994. .setTextColor("#DDDDDD")
  7995. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  7996. .setEmptyHint("")
  7997. .setAnimationDuration(1000)
  7998. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  7999. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  8000. this.setBlurDegree(this.blurDegreePip, true)
  8001. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  8002. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  8003. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  8004. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  8005. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  8006. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  8007. this.lyricControllerXF.setHightLightCenter(true)
  8008. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  8009. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  8010. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  8011. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  8012. if (this.pipBgIndex === 0) {
  8013. if (this.cover) {
  8014. this.pipBg = this.cover
  8015. } else {
  8016. this.pipBg = this.imageColor
  8017. }
  8018. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  8019. }
  8020. }
  8021. //根据item返回歌词内容
  8022. async getLyricContent(item: VideoItem): Promise<string> {
  8023. let neiqianLrc = ''
  8024. let lyContent = item?.lyricContent
  8025. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  8026. neiqianLrc = lyContent
  8027. return neiqianLrc
  8028. }
  8029. try {
  8030. //取数据库里面的歌词lyContent
  8031. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  8032. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  8033. console.log("onecold Lyrics:", lyricContent);
  8034. neiqianLrc = lyricContent
  8035. return neiqianLrc
  8036. }
  8037. } catch (error) {
  8038. console.error("Error fetching lyrics:", error);
  8039. }
  8040. try {
  8041. let filePath = item.filePath;
  8042. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  8043. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  8044. let isJiaMi = false;
  8045. let realLyricPath = lyricPath;
  8046. if (FileUtil.accessSync(jiaMilyricPath)) {
  8047. isJiaMi = true;
  8048. realLyricPath = jiaMilyricPath;
  8049. console.info("onecold 找到加密本地歌词");
  8050. } else {
  8051. console.info("onecold 找到本地歌词");
  8052. }
  8053. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  8054. const stat = await fileIo.stat(file.fd);
  8055. const arrayBuffer = new ArrayBuffer(stat.size);
  8056. const readLen = await fs.read(file.fd, arrayBuffer);
  8057. console.info("read file data succeed");
  8058. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  8059. if (buf.length === 0) {
  8060. throw new Error("Buffer is empty after reading the file");
  8061. }
  8062. // let detectedEncoding = chardet.detect(buf);
  8063. let detectedEncoding = this.detect(arrayBuffer)
  8064. console.info("Detected encoding: " + detectedEncoding);
  8065. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  8066. let fileContent = textDecoder.decode(buf);
  8067. console.info(`onecold The content of file1: ${fileContent}`);
  8068. if (isJiaMi) {
  8069. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  8070. }
  8071. console.info(`onecold The content of file2: ${fileContent}`);
  8072. fs.closeSync(file);
  8073. return fileContent;
  8074. } catch (error) {
  8075. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  8076. return '';
  8077. }
  8078. }
  8079. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  8080. if (StrUtil.isEmpty(filePath)) {
  8081. return
  8082. }
  8083. try {
  8084. //将content进行加密
  8085. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  8086. let lyricContent = ''
  8087. if (isJiaMi) {
  8088. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  8089. } else {
  8090. lyricContent = content
  8091. }
  8092. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  8093. // 清空文件内容
  8094. await fileIo.truncate(file.fd, 0);
  8095. await fileIo.write(file.fd, lyricContent);
  8096. await fileIo.close(file);
  8097. console.log('onecold lyric file Data saved successfully.');
  8098. } catch (error) {
  8099. console.error('onecold lyric file Failed to save data:', error);
  8100. }
  8101. }
  8102. // 定义开始旋转的方法
  8103. // 定时器用于一百毫秒执行一次旋转角度
  8104. @State timer: number = 0
  8105. @State rotateAngle: number = 0
  8106. //封面旋转动画
  8107. animationRoFun() {
  8108. if (this.isPlaying && !this.isCoverRectangle) {
  8109. this.timer = setInterval(() => {
  8110. this.rotateAngle += 1
  8111. }, 100)
  8112. this.startRotation()
  8113. } else {
  8114. clearInterval(this.timer)
  8115. this.stopRotation()
  8116. }
  8117. }
  8118. // 定义开始旋转的方法
  8119. startRotation() {
  8120. if (this.isPlaying) {
  8121. animateTo({
  8122. duration: 777,
  8123. iterations: 1,
  8124. curve: Curve.Linear
  8125. }, () => {
  8126. this.rotateAngle2 = -9
  8127. })
  8128. }
  8129. }
  8130. // 回调,暂停和播放按钮回调,下一首和上一首
  8131. playChange() {
  8132. // if(this.isCoverRectangle){
  8133. // return
  8134. // }
  8135. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8136. this.setIsPlaying(true)
  8137. this.animationState = AnimationStatus.Running
  8138. } else {
  8139. this.setIsPlaying(false)
  8140. this.animationState = AnimationStatus.Paused
  8141. }
  8142. }
  8143. // 定义停止旋转的方法
  8144. stopRotation() {
  8145. if (this.isCoverRectangle) {
  8146. this.rotateAngle = 0
  8147. } else {
  8148. //唱针以左上角为点选择逆时针40度
  8149. animateTo({
  8150. duration: 1000,
  8151. curve: Curve.Linear,
  8152. iterations: 1,
  8153. }, () => {
  8154. this.rotateAngle2 = -45;
  8155. });
  8156. }
  8157. }
  8158. @Builder
  8159. private LyricsTopItem() {
  8160. Row() {
  8161. Stack() {
  8162. Image(this.cover)
  8163. .height(58)
  8164. .width(58)
  8165. .alt($r('app.media.alt'))
  8166. .borderRadius(8)
  8167. .clickEffect({ level: ClickEffectLevel.HEAVY })
  8168. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  8169. .shadow({
  8170. radius: 22,
  8171. type: ShadowType.BLUR,
  8172. color: 'on_primary'
  8173. })
  8174. }
  8175. .width('18%')
  8176. Column() {
  8177. Column() {
  8178. Text(this.name)
  8179. .fontSize(16)
  8180. .maxLines(1)
  8181. .fontWeight(FontWeight.Bolder)
  8182. .fontColor(this.currentLyricColor)
  8183. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  8184. Row() {
  8185. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  8186. .fontSize(13)
  8187. .fontWeight(FontWeight.Bold)
  8188. .padding({ top: 8 })
  8189. .fontColor(this.currentLyricColor)
  8190. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  8191. Blank()
  8192. }
  8193. }
  8194. .height('100%')
  8195. .width('100%')
  8196. .justifyContent(FlexAlign.Center)
  8197. .alignItems(HorizontalAlign.Start)
  8198. }
  8199. .height('100%')
  8200. .width('65%')
  8201. Column() {
  8202. Image($r('app.media.lyric'))
  8203. .width(28)
  8204. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8205. .margin({ right: 30 })
  8206. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8207. .onClick(() => {
  8208. this.isLyricSetting = !this.isLyricSetting;
  8209. })
  8210. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  8211. height: '95%',
  8212. dragBar: true,
  8213. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8214. showClose: true,
  8215. blurStyle: BlurStyle.Thin,
  8216. backgroundColor: Color.Transparent,
  8217. // title: { title: $r('app.string.lyric_setting') }
  8218. })
  8219. }
  8220. .width('18%')
  8221. }
  8222. .width('82%')
  8223. .height(58)
  8224. .justifyContent(FlexAlign.SpaceBetween)
  8225. }
  8226. //歌词显示
  8227. @Builder
  8228. PlayerLyrics() {
  8229. Column() {
  8230. Column() {
  8231. this.LyricsTopItem()
  8232. }
  8233. .height(this.isPuraWP() ? 15 : 58)
  8234. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  8235. Visibility.None : Visibility.Visible)
  8236. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  8237. .width("100%")
  8238. Column() {
  8239. LyricView2({
  8240. controller: this.lyricController,
  8241. enableSeek: true,
  8242. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  8243. seekLineColor: "#80ffffff", // 滑动定位线颜色
  8244. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  8245. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  8246. if (!this.isPlaying) {
  8247. console.info('onecold startPlayOrResumePlay 7527')
  8248. this.startPlayOrResumePlay()
  8249. }
  8250. else {
  8251. this.isSeekTo = true;
  8252. this.mDestroyPage = false;
  8253. this.showLoadIng();
  8254. this.seekTo(position + "");
  8255. this.isSeekTo = false;
  8256. }
  8257. return true
  8258. }
  8259. })
  8260. .width("100%")
  8261. .layoutWeight(1)
  8262. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  8263. if (this.isPhoneLan()) {
  8264. Column() {
  8265. this.playProgressView()
  8266. // this.playCenterView()
  8267. }
  8268. .margin({ bottom: 30, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  8269. }
  8270. }
  8271. .position({
  8272. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  8273. (this.isPuraWP() ? 58 : 99)
  8274. })
  8275. .justifyContent(FlexAlign.Center)
  8276. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  8277. }
  8278. }
  8279. @Builder
  8280. SingleLyricView() {
  8281. Column() {
  8282. Column() {
  8283. LyricView2({
  8284. controller: this.lyricControllerSingle,
  8285. enableSeek: false,
  8286. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  8287. seekLineColor: "#80ffffff", // 滑动定位线颜色
  8288. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  8289. })
  8290. }
  8291. .height(66)
  8292. .margin({ bottom: 20 })
  8293. }
  8294. }
  8295. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  8296. @Builder
  8297. BottomControl() {
  8298. Column() {
  8299. this.TopPlayProgressView()
  8300. //播放 暂停,下一首,上一首
  8301. this.playCenterView()
  8302. //播放进度条
  8303. this.BottomView()
  8304. }
  8305. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  8306. }
  8307. //播放控制上一首 下一首 暂停和播放
  8308. @Builder
  8309. playCenterView(){
  8310. Row() {
  8311. Button({type:ButtonType.Circle,stateEffect:true}){
  8312. //更多功能
  8313. Image($r('app.media.menu'))
  8314. .width(24)
  8315. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8316. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  8317. height: '99%',
  8318. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  8319. dragBar: true,
  8320. showClose: true,
  8321. blurStyle: BlurStyle.Thin,
  8322. backgroundColor: Color.Transparent,
  8323. })
  8324. }
  8325. .height(45)
  8326. .width(45)
  8327. .margin({ left: 5 })
  8328. .backgroundColor(Color.Transparent)
  8329. .onClick(() => {
  8330. this.isShowMoreView = !this.isShowMoreView;
  8331. })
  8332. Button({type:ButtonType.Circle,stateEffect:true}){
  8333. Image($r('app.media.ic_previous'))
  8334. .width(33)
  8335. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8336. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8337. }
  8338. .height(45)
  8339. .width(45)
  8340. .onClick(async () => {
  8341. await this.playPrevious()
  8342. })
  8343. .backgroundColor(Color.Transparent)
  8344. Button({type:ButtonType.Circle,stateEffect:true}){
  8345. Column() {
  8346. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  8347. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  8348. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  8349. .width(this.isPhoneLan()?45:55)
  8350. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8351. .fillColor(Color.White)
  8352. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8353. }
  8354. }
  8355. .onClick(async () => {
  8356. this.playOrPause()
  8357. })
  8358. .backgroundColor(Color.Transparent)
  8359. .layoutWeight(1)
  8360. Button({ type: ButtonType.Circle, stateEffect: true }) {
  8361. Image($r('app.media.ic_next'))
  8362. .width(33)
  8363. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8364. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8365. }
  8366. .height(45)
  8367. .width(45)
  8368. .backgroundColor(Color.Transparent)
  8369. .onClick(async () => {
  8370. await this.playNext();
  8371. })
  8372. this.fullButton()
  8373. }
  8374. .width('95%')
  8375. .margin({ bottom:this.isCoverOpacity()?0:15 })
  8376. .justifyContent(FlexAlign.SpaceEvenly)
  8377. }
  8378. @Builder
  8379. TopPlayProgressView(){
  8380. Row() {
  8381. Column(){
  8382. Row(){
  8383. Stack(){
  8384. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  8385. .fontColor([Color.White])
  8386. .fontSize(21)
  8387. .effectStrategy(1)
  8388. Text(this.fastForwardSeconds)
  8389. .fontColor(Color.White)
  8390. .fontSize(10)
  8391. .fontWeight(FontWeight.Bold)
  8392. }
  8393. .margin({left:12,bottom:6})
  8394. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  8395. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8396. .onClick(()=>{
  8397. this.backForward()
  8398. })
  8399. Slider({
  8400. value: this.progressValue,
  8401. min: 0,
  8402. max: this.PROGRESS_MAX_VALUE,
  8403. step: 1,
  8404. style: SliderStyle.InSet
  8405. })
  8406. .height(20)
  8407. .blockColor('rgba(255,255,255,1)')
  8408. .trackColor('rgba(255,255,255,0.3)')
  8409. .selectedColor(Color.White)
  8410. .trackThickness(4)
  8411. .layoutWeight(1)
  8412. .showSteps(false)
  8413. .showTips(true)
  8414. .alignSelf(ItemAlign.Center)
  8415. .enabled(this.slideEnable)
  8416. .onChange((value: number, mode: SliderChangeMode) => {
  8417. // if (mode == 2) {
  8418. this.isSeekTo = true;
  8419. this.mDestroyPage = false;
  8420. this.showLoadIng();
  8421. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  8422. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  8423. this.seekTo(seekValue + "");
  8424. // this.setProgress()
  8425. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  8426. this.isSeekTo = false;
  8427. // }
  8428. })
  8429. Stack(){
  8430. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  8431. .fontColor([Color.White])
  8432. .fontSize(21)
  8433. .effectStrategy(1)
  8434. Text(this.fastForwardSeconds)
  8435. .fontColor(Color.White)
  8436. .fontSize(10)
  8437. .fontWeight(FontWeight.Bold)
  8438. }
  8439. .margin({right:10,bottom:6})
  8440. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  8441. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8442. .onClick(()=>{
  8443. this.fastForward()
  8444. })
  8445. }
  8446. .padding({ right: 7,left:22 })
  8447. Row(){
  8448. Text(this.currentTime)
  8449. .fontSize(10)
  8450. .fontColor(Color.White)
  8451. Blank()
  8452. .layoutWeight(1)
  8453. Text(this.totalTime)
  8454. .fontSize(10)
  8455. .fontColor(Color.White)
  8456. }
  8457. .justifyContent(FlexAlign.Start)
  8458. .padding({ right: 18,left:36 })
  8459. }
  8460. }
  8461. //x5的竖屏模式需要99%
  8462. .width(this.isLandscape?'80%':'93%')
  8463. .justifyContent(FlexAlign.Center)
  8464. .margin({bottom:3})
  8465. .animation({
  8466. duration: 666,
  8467. curve: 'ease-in-out' // 可选动画曲线
  8468. })
  8469. }
  8470. //播放进度条
  8471. @Builder
  8472. BottomView(){
  8473. Row() {
  8474. Button({type:ButtonType.Circle,stateEffect:true}){
  8475. Column() {
  8476. if (this.playType === 0) {
  8477. Image($r('app.media.loop'))
  8478. .width(27)
  8479. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8480. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8481. } else if (this.playType === 1) {
  8482. Image($r('app.media.single'))
  8483. .width(27)
  8484. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8485. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8486. } else if (this.playType === 2) {
  8487. Image($r('app.media.normal_play'))
  8488. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8489. .width(27)
  8490. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8491. } else if (this.playType === 3) {
  8492. Image($r('app.media.random'))
  8493. .width(27)
  8494. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8495. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8496. }
  8497. }
  8498. }
  8499. .layoutWeight(1)
  8500. .margin({ left: 5 })
  8501. .height(45)
  8502. .width(45)
  8503. .backgroundColor(Color.Transparent)
  8504. .onClick(async () => {
  8505. this.setLoopMode()
  8506. })
  8507. if(this.currentSong){
  8508. Button({type:ButtonType.Circle,stateEffect:true}){
  8509. Column() {
  8510. Image($r('app.media.rename2'))
  8511. .width(21)
  8512. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8513. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8514. }
  8515. }
  8516. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  8517. height: '99%',
  8518. dragBar: true,
  8519. showClose: true,
  8520. preferType: SheetType.BOTTOM,
  8521. title: { title: '编辑标签' }
  8522. })
  8523. .height(45)
  8524. .width(45)
  8525. .layoutWeight(1)
  8526. .backgroundColor(Color.Transparent)
  8527. .onClick(async () => {
  8528. this.setEditStrEmpty()
  8529. this.tempLyricContent = this.lyricContent
  8530. this.isShowEdit = !this.isShowEdit;
  8531. })
  8532. }
  8533. Button({type:ButtonType.Circle,stateEffect:true}){
  8534. Column() {
  8535. Image($r('app.media.lyric'))
  8536. .width(26)
  8537. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8538. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8539. }
  8540. }
  8541. .height(45)
  8542. .width(45)
  8543. .layoutWeight(1)
  8544. .backgroundColor(Color.Transparent)
  8545. .onClick(async () => {
  8546. this.isLyricSetting = !this.isLyricSetting;
  8547. })
  8548. //播放列表
  8549. Button({type:ButtonType.Circle,stateEffect:true}){
  8550. Image($r('app.media.hm_playlist'))
  8551. .width(24)
  8552. .fillColor(Color.White)
  8553. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8554. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8555. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  8556. height: '95%',
  8557. dragBar: true,
  8558. showClose: true,
  8559. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8560. blurStyle: BlurStyle.Thin,
  8561. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  8562. title: {
  8563. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  8564. + `(${this.songList.length}首)`
  8565. }
  8566. })
  8567. }
  8568. .layoutWeight(1)
  8569. .height(45)
  8570. .width(45)
  8571. .backgroundColor(Color.Transparent)
  8572. .onClick(() => {
  8573. this.isShowSheetView = !this.isShowSheetView;
  8574. if(this.isPlayListBgGrass){
  8575. this.isFrontWhite = true
  8576. }else{
  8577. this.isFrontWhite = false
  8578. }
  8579. this.scrollIndex()
  8580. })
  8581. }
  8582. .width(this.isLandscape?'88%':'95%')
  8583. .justifyContent(FlexAlign.SpaceAround)
  8584. .height(30)
  8585. .animation({
  8586. duration: 666,
  8587. curve: 'ease-in-out' // 可选动画曲线
  8588. })
  8589. }
  8590. @Builder
  8591. fullButton(){
  8592. Button({type:ButtonType.Circle,stateEffect:true}){
  8593. Column() {
  8594. Image($r('app.media.full_4'))
  8595. .width(25)
  8596. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8597. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8598. }
  8599. }
  8600. .layoutWeight(1)
  8601. .backgroundColor(Color.Transparent)
  8602. .height(45)
  8603. .width(45)
  8604. .onClick(async () => {
  8605. if (this.isLandscape) {
  8606. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  8607. } else {
  8608. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  8609. }
  8610. })
  8611. }
  8612. //旧版本播放进度条
  8613. @Builder
  8614. playProgressView() {
  8615. Row() {
  8616. Button({ type: ButtonType.Circle, stateEffect: true }) {
  8617. Column() {
  8618. if (this.playType === 0) {
  8619. Image($r('app.media.loop'))
  8620. .width($r('app.float.control_image_width'))
  8621. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8622. } else if (this.playType === 1) {
  8623. Image($r('app.media.single'))
  8624. .width($r('app.float.control_image_width'))
  8625. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8626. } else if (this.playType === 2) {
  8627. Image($r('app.media.normal_play'))
  8628. .width($r('app.float.control_image_width'))
  8629. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8630. } else if (this.playType === 3) {
  8631. Image($r('app.media.random'))
  8632. .width($r('app.float.control_image_width'))
  8633. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8634. }
  8635. }
  8636. }
  8637. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  8638. .animation({
  8639. duration: 666,
  8640. curve: 'ease-in-out' // 可选动画曲线
  8641. })
  8642. .backgroundColor(Color.Transparent)
  8643. .margin({ right: 10 })
  8644. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8645. .onClick(async () => {
  8646. this.setLoopMode()
  8647. })
  8648. Text(this.currentTime)
  8649. .fontSize($r('app.float.slider_font_size'))
  8650. .fontColor(Color.White)
  8651. .margin(3)
  8652. Slider({
  8653. value: this.progressValue,
  8654. min: 0,
  8655. max: this.PROGRESS_MAX_VALUE,
  8656. step: 1,
  8657. style: SliderStyle.OutSet
  8658. })
  8659. .width('600px')
  8660. .blockColor('rgba(255,255,255,1)')
  8661. .trackColor('rgba(255,255,255,0.3)')
  8662. .selectedColor(Color.White)
  8663. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  8664. .layoutWeight(1)
  8665. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  8666. .showSteps(false)
  8667. .showTips(true)
  8668. .enabled(this.slideEnable)
  8669. .onChange((value: number, mode: SliderChangeMode) => {
  8670. // if (mode == 2) {
  8671. this.isSeekTo = true;
  8672. this.mDestroyPage = false;
  8673. this.showLoadIng();
  8674. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  8675. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  8676. this.seekTo(seekValue + "");
  8677. // this.setProgress()
  8678. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  8679. this.isSeekTo = false;
  8680. // }
  8681. })
  8682. Text(this.totalTime)
  8683. .fontSize($r('app.float.slider_font_size'))
  8684. .fontColor(Color.White)
  8685. .margin(3)
  8686. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  8687. //播放列表
  8688. Button({ type: ButtonType.Circle, stateEffect: true }) {
  8689. Image($r('app.media.hm_playlist'))
  8690. .width($r('app.float.control_image_width'))
  8691. .fillColor(Color.White)
  8692. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8693. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  8694. height: '95%',
  8695. dragBar: true,
  8696. showClose: true,
  8697. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8698. blurStyle: BlurStyle.Thin,
  8699. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  8700. title: {
  8701. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  8702. + `(${this.songList.length}首)`
  8703. }
  8704. })
  8705. }
  8706. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  8707. .animation({
  8708. duration: 666,
  8709. curve: 'ease-in-out' // 可选动画曲线
  8710. })
  8711. .backgroundColor(Color.Transparent)
  8712. .margin({ right: 20, left: 10 })
  8713. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8714. .onClick(() => {
  8715. this.isShowSheetView = !this.isShowSheetView;
  8716. if (this.isPlayListBgGrass) {
  8717. this.isFrontWhite = true
  8718. } else {
  8719. this.isFrontWhite = false
  8720. }
  8721. this.scrollIndex()
  8722. })
  8723. }
  8724. //x5的竖屏模式需要99%
  8725. .width(this.isPhonePortrait() ? '93.4%'
  8726. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  8727. .height(this.isPhoneLan() ? 25 : 33)
  8728. .animation({
  8729. duration: 666,
  8730. curve: 'ease-in-out' // 可选动画曲线
  8731. })
  8732. }
  8733. isBigScreen() {
  8734. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  8735. return true
  8736. }
  8737. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8738. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  8739. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  8740. return false
  8741. } else {
  8742. return true
  8743. }
  8744. return false
  8745. }
  8746. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  8747. @State isCoverRectangle: boolean = false
  8748. @State isCoverTop: boolean = true
  8749. // 添加控制缩放的状态变量
  8750. @State scaleValueImage: number = 1
  8751. @Builder
  8752. CoverInfo() {
  8753. Column() {
  8754. //如果是方形,判断是不是封面在顶部,如果不是顶部,显示musicNameInfo, 如果是圆形显示musicNameInfo
  8755. if (this.isCoverRectangle) {
  8756. if (!this.isCoverTop) {
  8757. this.musicNameInfo(false)
  8758. }
  8759. } else {
  8760. this.musicNameInfo(false)
  8761. }
  8762. Stack() {
  8763. // 唱片旋转效果
  8764. Image($r('app.media.ic_music_disc'))
  8765. .width(245)
  8766. .height(245)
  8767. .margin({ right: 20, left: 20 ,top:this.isCoverRectangle||this.isLandscape?0:43})
  8768. .aspectRatio(1)
  8769. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  8770. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  8771. .borderRadius('100%')
  8772. .align(Alignment.Center)
  8773. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  8774. .rotate({
  8775. angle: this.rotateAngle,
  8776. centerX: "50%",
  8777. centerY: "50%",
  8778. })
  8779. .animation({
  8780. duration: 100,
  8781. curve: Curve.Linear
  8782. })
  8783. .shadow({
  8784. radius: 22,
  8785. type: ShadowType.BLUR,
  8786. color: 'on_primary'
  8787. })
  8788. Column() {
  8789. if (this.isCoverTop && !this.isCoverOpacity() && this.isCoverRectangle) {
  8790. Image(this.cover)
  8791. .height(this.isHiCar()?(px2vp(this.windowHeight)*0.46):'auto')
  8792. .width(this.isHiCar()?'auto':this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '88%')
  8793. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  8794. .alt($r('app.media.alt'))
  8795. .margin({ right: 8, left: 8, top: 8 })
  8796. .aspectRatio(1)
  8797. .opacity(this.opacityValueImage)
  8798. .geometryTransition('cover') // 绑定标识符
  8799. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  8800. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  8801. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  8802. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  8803. .align(Alignment.Center)//
  8804. .clip(true)
  8805. .rotate({
  8806. x: 0,
  8807. y: 0,
  8808. z: 1,
  8809. angle: this.rotateAngle
  8810. })
  8811. .shadow({
  8812. radius: 22,
  8813. type: ShadowType.BLUR,
  8814. color: 'on_primary'
  8815. })
  8816. .onClick(() => {
  8817. })
  8818. // .visualEffect(new hdsEffect.HdsEffectBuilder()
  8819. // .shaderEffect({
  8820. // effectType: hdsEffect.EffectType.DUAL_EDGE_FLOW_LIGHT,
  8821. // animation: {
  8822. // duration: 4000,
  8823. // iterations: -1,
  8824. // autoPlay: true,
  8825. // onFinish: () => {
  8826. // console.info('Succeeded in finishing');
  8827. // }
  8828. // },
  8829. // controller: this.controller,
  8830. // params: {
  8831. // firstEdgeFlowLight: {
  8832. // startPos: 0,
  8833. // endPos: 1.0,
  8834. // color: '#1AD0F1',
  8835. // },
  8836. // secondEdgeFlowLight: {
  8837. // startPos: 0.5,
  8838. // endPos: 1.5,
  8839. // color: '#FFA4E5',
  8840. // }
  8841. // }
  8842. // })
  8843. // .buildEffect())
  8844. this.musicNameInfo(false)
  8845. } else {
  8846. Image(this.cover)
  8847. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  8848. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 162))
  8849. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  8850. .alt($r('app.media.alt'))
  8851. .margin({ right: 20, left: 20,top:this.isCoverRectangle||this.isLandscape?0:43 })
  8852. .aspectRatio(1)
  8853. .opacity(this.opacityValueImage)
  8854. .geometryTransition('cover') // 绑定标识符
  8855. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  8856. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  8857. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  8858. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  8859. .align(Alignment.Center)//
  8860. .clip(true)
  8861. .shadow({
  8862. radius: 22,
  8863. type: ShadowType.BLUR,
  8864. color: 'on_primary'
  8865. })
  8866. .rotate({
  8867. x: 0,
  8868. y: 0,
  8869. z: 1,
  8870. angle: this.rotateAngle
  8871. })
  8872. .onClick(() => {
  8873. })
  8874. if (this.isPhoneLan()) {
  8875. Text(this.name)
  8876. .fontSize(18)
  8877. .fontWeight(FontWeight.Bold)
  8878. .margin({ top: 13 })
  8879. .textOverflow({ overflow: TextOverflow.Ellipsis })
  8880. .maxLines(1)
  8881. .width('99%')
  8882. .textAlign(TextAlign.Center)
  8883. .fontColor(Color.White)
  8884. }
  8885. }
  8886. }
  8887. // 唱针以左上角为点选择逆时针40度
  8888. Image($r('app.media.ic_music_cover_hand'))
  8889. .height(130)
  8890. .margin({ bottom: 220, top: 0 })
  8891. .align(Alignment.Top)
  8892. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  8893. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  8894. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  8895. Column({ space: 8 }) {
  8896. Text(this.name)
  8897. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  8898. .fontWeight(FontWeight.Bold)
  8899. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8900. .maxLines(1)
  8901. .width('48%')
  8902. .textAlign(TextAlign.Center)
  8903. .fontColor(Color.White)
  8904. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  8905. Text(this.artist)
  8906. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  8907. .fontColor(Color.White)
  8908. .fontWeight(FontWeight.Bold)
  8909. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  8910. }
  8911. .justifyContent(FlexAlign.Start)
  8912. .zIndex(1)
  8913. .geometryTransition('name')
  8914. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  8915. }
  8916. .margin({
  8917. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  8918. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  8919. top: this.isCoverOpacity() ? 0 : 20
  8920. })
  8921. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  8922. this.SingleLyricView()
  8923. }
  8924. if (this.isPhoneLan()) {
  8925. Column() {
  8926. this.playCenterView()
  8927. // this.playProgressView()
  8928. }
  8929. .position({ left: 28, bottom: 38 })
  8930. } else {
  8931. this.BottomControl()
  8932. }
  8933. }
  8934. .width(CommonConstants.FULL_PERCENT)
  8935. .clip(true)
  8936. }
  8937. @Builder
  8938. private musicNameInfo(isHidden: boolean) {
  8939. Row(){
  8940. Column({ space: 8 }) {
  8941. Text(this.name)
  8942. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 20)
  8943. .fontWeight(FontWeight.Bold)
  8944. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8945. .maxLines(1)
  8946. .width('99%')
  8947. .textAlign(TextAlign.Start)
  8948. .fontColor(Color.White)
  8949. Text(this.artist + ' ' + this.currentSong?.album)
  8950. .fontSize(this.isCoverOpacity() ? 12 : 15)
  8951. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8952. .fontColor(Color.White)
  8953. .textAlign(TextAlign.Start)
  8954. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  8955. .width('99%')
  8956. .maxLines(1)
  8957. }
  8958. .zIndex(1)
  8959. .geometryTransition('name') // 绑定标识符
  8960. .layoutWeight(1)
  8961. .margin({ left: 15 })
  8962. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  8963. Blank()
  8964. Row(){
  8965. Button({type:ButtonType.Circle,stateEffect:true}){
  8966. //添加或取消收藏
  8967. SymbolGlyph(Utility.getIsFav(this.favList,this.currentSong)?
  8968. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'))
  8969. .fontSize(22)
  8970. .fontColor([Color.White])
  8971. .alignSelf(ItemAlign.Center)
  8972. // .width(24)
  8973. .clickEffect({level:ClickEffectLevel.MIDDLE})
  8974. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8975. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8976. .onClick(async () => {
  8977. if(this.currentSong){
  8978. this.doFav(this.currentSong)
  8979. }
  8980. })
  8981. }
  8982. .margin({ left: 15,right:3 })
  8983. .backgroundColor(Color.Transparent)
  8984. .width(45)
  8985. .height(45)
  8986. }
  8987. }
  8988. .width('90%')
  8989. .margin({ top: this.isCoverOpacity() ? 10 : isHidden ? 20 : 10 })
  8990. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  8991. }
  8992. @Builder
  8993. private PlayTitle() {
  8994. Row() {
  8995. Row() {
  8996. Image($r('app.media.ic_back_down'))
  8997. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  8998. .hitTestBehavior(HitTestMode.Transparent)
  8999. Text(this.name + ' ' + this.artist)
  9000. .fontColor(Color.White)
  9001. .fontSize($r('app.float.title_font_size'))
  9002. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9003. .maxLines(1)
  9004. .visibility(Visibility.None)
  9005. .margin({ left: 2, right: 30 })
  9006. }
  9007. .layoutWeight(1)
  9008. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9009. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  9010. .onClick(() => {
  9011. this.getUIContext()?.animateTo({
  9012. duration: 350,
  9013. curve: Curve.Friction
  9014. }, () => {
  9015. this.isShowPlay = !this.isShowPlay;
  9016. });
  9017. })
  9018. Column() {
  9019. AVCastPicker({
  9020. normalColor: Color.White,
  9021. onStateChange: this.onStateVastChange
  9022. })
  9023. .width(24)
  9024. .height(24)
  9025. }
  9026. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  9027. }
  9028. .width(PlayConstants.ROW_WIDTH)
  9029. }
  9030. @Builder
  9031. lyricSettingSheet(isPip: boolean) {
  9032. Scroll() {
  9033. this.lyricSetting(isPip)
  9034. }
  9035. .width('100%')
  9036. .height('100%')
  9037. }
  9038. @Builder
  9039. lyricSetting(isPip: boolean) {
  9040. Column() {
  9041. // 时间调节模块
  9042. if (!isPip) {
  9043. this.BuildTimeControls()
  9044. }
  9045. // 字号控制模块
  9046. this.BuildFontControls(isPip)
  9047. }
  9048. }
  9049. // 歌词时间偏移状态
  9050. @State timeOffset: number = 0.0
  9051. @State currentLyricColor: string = '#FFFFFF'
  9052. @State currentLyricColorPip: string = '#FFFFFF'
  9053. @State currentHighLightLyricColor: string = '#FF4081'
  9054. @State currentHighLightLyricColorPip: string = '#FF4081'
  9055. // 歌词字号状态
  9056. @State currentLyricSize: number = 20
  9057. @State currentLyricSizePip: number = 20
  9058. // 高亮歌词放大倍数
  9059. @State currentHightLyricSize: number = 1.2
  9060. @State currentHightLyricSizePip: number = 1.2
  9061. @State currentLyricLineSpace: number = 10
  9062. @State currentLyricLineSpacePip: number = 10
  9063. @State currentLyricAlignMode: number = 1
  9064. @State currentLyricAlignModePip: number = 1
  9065. @State blurDegree: number = 2
  9066. @State blurDegreePip: number = 2
  9067. @State isShowSelectColor: boolean = false
  9068. @State isShowHLSelectColor: boolean = false
  9069. @State isShowPipBgSelectColor: boolean = false
  9070. @State pipLyWidth: number = 330
  9071. @State pipLyHeight: number = 120
  9072. // 构建颜色选择器
  9073. @Builder
  9074. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  9075. Row({ space: 10 }) {
  9076. HSBColorPicker({
  9077. color: '#FFFFFF',
  9078. radius: 8,
  9079. layout: HSBColorPickerLayout.COLUMN,
  9080. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  9081. '#fa7105'],
  9082. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  9083. this.changeLyricColor(value, isPip, isBGPip)
  9084. })
  9085. .height(250)
  9086. .layoutWeight(1)
  9087. .padding(25)
  9088. }
  9089. .width('66%')
  9090. }
  9091. @State isOpenPip: boolean = false
  9092. @State pipBgIndex: number = 0
  9093. // 构建字号控制器
  9094. @Builder
  9095. BuildFontControls(isPip: boolean) {
  9096. Column() {
  9097. if (isPip) {
  9098. Column() {
  9099. Row() {
  9100. Text('悬浮歌词')
  9101. .margin({ left: 18 })
  9102. .fontSize(15)
  9103. .fontColor(Color.White)
  9104. .fontWeight(480)
  9105. .layoutWeight(1)
  9106. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  9107. .selectedColor(this.themeColor)
  9108. .switchPointColor(Color.White)
  9109. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9110. .margin({ right: 18 })
  9111. .onChange((checked: boolean) => {
  9112. this.isOpenPip = checked;
  9113. if (this.isOpenPip) {
  9114. this.startPip()
  9115. } else {
  9116. this.stopPip()
  9117. }
  9118. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  9119. })
  9120. .width(50)
  9121. .height(30);
  9122. }
  9123. .height(55)
  9124. }
  9125. .backgroundColor(Color.Transparent)
  9126. .borderRadius(15)
  9127. .margin({
  9128. left: 30,
  9129. right: 30,
  9130. top: 0,
  9131. bottom: 20
  9132. })
  9133. .padding(0)
  9134. .border({
  9135. color: Color.White,
  9136. width: 1.8
  9137. })
  9138. }else{
  9139. Column() {
  9140. Row() {
  9141. Text('单行歌词')
  9142. .margin({ left: 18 })
  9143. .fontSize(15)
  9144. .fontColor(Color.White)
  9145. .fontWeight(480)
  9146. .layoutWeight(1)
  9147. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  9148. .selectedColor(this.themeColor)
  9149. .switchPointColor(Color.White)
  9150. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9151. .margin({ right: 18 })
  9152. .onChange((checked: boolean) => {
  9153. this.isShowSingleLineLyric = checked;
  9154. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  9155. })
  9156. .width(50)
  9157. .height(30);
  9158. }
  9159. .height(55)
  9160. }
  9161. .backgroundColor(Color.Transparent)
  9162. .borderRadius(15)
  9163. .margin({
  9164. left: 30,
  9165. right: 30,
  9166. top: 10,
  9167. bottom: 10
  9168. })
  9169. .padding(0)
  9170. .border({
  9171. color: Color.White,
  9172. width: 1.8
  9173. })
  9174. }
  9175. Row() {
  9176. Text(`歌词居中:`)
  9177. .fontSize(14)
  9178. .fontColor(Color.White)
  9179. .margin({ left: 2 })
  9180. Row() {
  9181. ForEach(['居中', '居左'], (size: string, index: number) => {
  9182. Button(size)
  9183. .width(60)
  9184. .height(28)
  9185. .fontSize(12)
  9186. .fontColor('#FFFFFF')
  9187. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  9188. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  9189. .border({
  9190. color: (!isPip && this.currentLyricAlignMode === index) ||
  9191. (isPip && this.currentLyricAlignModePip === index) ?
  9192. '#007DFF' : '#DDDDDD',
  9193. width: 1.8
  9194. })
  9195. .onClick(() => {
  9196. this.setLyricAlignMode(index, isPip)
  9197. })
  9198. .margin({ left: 10, right: 8 })
  9199. })
  9200. }
  9201. .width('76%')
  9202. Blank()
  9203. }
  9204. .margin({
  9205. top: 10,
  9206. bottom: 10,
  9207. right: 20,
  9208. left: 20
  9209. })
  9210. if (isPip) {
  9211. Row() {
  9212. Text(`悬浮背景:`)
  9213. .fontSize(14)
  9214. .fontColor(Color.White)
  9215. Select([
  9216. { value: CommonConstants.PIP_LYRIC_BG[0] },
  9217. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  9218. .font({ size: 13, weight: FontWeight.Medium })
  9219. .fontColor(Color.White)
  9220. .margin({ left: 10 })
  9221. .selected(this.pipBgIndex)
  9222. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  9223. .onSelect(async (_index: number, text?: string | undefined) => {
  9224. this.pipBgIndex = _index
  9225. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  9226. if (this.pipBgIndex === 0) {
  9227. if (this.cover) {
  9228. this.pipBg = this.cover
  9229. } else {
  9230. this.pipBg = this.imageColor
  9231. }
  9232. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  9233. } else {
  9234. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  9235. }
  9236. })
  9237. Column() {
  9238. }
  9239. .backgroundColor(this.pipBg)
  9240. .margin({ left: 10, right: 10 })
  9241. .borderRadius(20)
  9242. .height(28)
  9243. .width(28)
  9244. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9245. Row() {
  9246. SymbolGlyph($r('sys.symbol.paintbrush'))
  9247. .fontColor([Color.White])
  9248. .effectStrategy(1)
  9249. Text(`选择颜色`)
  9250. .fontSize(13)
  9251. .margin({ left: 10 })
  9252. .fontColor(Color.White)
  9253. }
  9254. }
  9255. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  9256. .backgroundColor(Color.Transparent)
  9257. .border({
  9258. color: '#FFFFFF',
  9259. radius: 20,
  9260. width: 1.8
  9261. })
  9262. .height(36)
  9263. .width(110)
  9264. .onClick(() => {
  9265. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  9266. })
  9267. .bindPopup(this.isShowPipBgSelectColor, {
  9268. builder: this.SelectColor(false, isPip, true),
  9269. placement: Placement.Top,
  9270. mask: { color: '#33000000' },
  9271. enableArrow: false, //是否显示箭头
  9272. showInSubWindow: false,
  9273. onStateChange: (e) => {
  9274. if (!e.isVisible) {
  9275. this.isShowPipBgSelectColor = false
  9276. }
  9277. }
  9278. })
  9279. }
  9280. .width('76%')
  9281. .margin({ bottom: 5, right: 45, left: 20 })
  9282. }
  9283. if (!isPip) {
  9284. Row() {
  9285. Text(`高亮居中:`)
  9286. .fontSize(14)
  9287. .fontColor(Color.White)
  9288. Column() {
  9289. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  9290. .selectedColor(this.themeColor)
  9291. .switchPointColor(Color.White)
  9292. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9293. .onChange((checked: boolean) => {
  9294. this.isHightLightCenter = checked;
  9295. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  9296. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  9297. })
  9298. .width(50)
  9299. .height(30)
  9300. .alignSelf(ItemAlign.Start)
  9301. .margin({ left: 12 })
  9302. Blank()
  9303. }
  9304. .width('76%')
  9305. }
  9306. .margin({
  9307. left: 20,
  9308. right: 15,
  9309. top: 10,
  9310. bottom: 10
  9311. })
  9312. }
  9313. Row() {
  9314. Text(`歌词颜色:`)
  9315. .fontSize(14)
  9316. .fontColor(Color.White)
  9317. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  9318. .fontSize(15)
  9319. .fontColor(Color.White)
  9320. .margin({ left: 12, right: 12 })
  9321. Column() {
  9322. }
  9323. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  9324. .margin({ right: 12 })
  9325. .borderRadius(20)
  9326. .height(28)
  9327. .width(28)
  9328. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9329. Row() {
  9330. SymbolGlyph($r('sys.symbol.paintbrush'))
  9331. .fontColor([Color.White])
  9332. .effectStrategy(1)
  9333. Text(`选择颜色`)
  9334. .fontSize(13)
  9335. .margin({ left: 10 })
  9336. .fontColor(Color.White)
  9337. }
  9338. }
  9339. .backgroundColor(Color.Transparent)
  9340. .border({
  9341. color: '#FFFFFF',
  9342. radius: 20,
  9343. width: 1.8
  9344. })
  9345. .height(36)
  9346. .width(110)
  9347. .onClick(() => {
  9348. this.isShowSelectColor = !this.isShowSelectColor
  9349. })
  9350. .bindPopup(this.isShowSelectColor, {
  9351. builder: this.SelectColor(false, isPip),
  9352. placement: Placement.Top,
  9353. mask: { color: '#33000000' },
  9354. enableArrow: false, //是否显示箭头
  9355. showInSubWindow: false,
  9356. onStateChange: (e) => {
  9357. if (!e.isVisible) {
  9358. this.isShowSelectColor = false
  9359. }
  9360. }
  9361. })
  9362. }
  9363. .width('76%')
  9364. .margin({
  9365. top: 10,
  9366. bottom: 10,
  9367. right: 45,
  9368. left: 20
  9369. })
  9370. Row() {
  9371. Text(`高亮颜色:`)
  9372. .fontSize(14)
  9373. .fontColor(Color.White)
  9374. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  9375. .fontSize(15)
  9376. .fontColor(Color.White)
  9377. .margin({ left: 12, right: 12 })
  9378. Column() {
  9379. }
  9380. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  9381. .margin({ right: 12 })
  9382. .borderRadius(20)
  9383. .height(28)
  9384. .width(28)
  9385. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9386. Row() {
  9387. SymbolGlyph($r('sys.symbol.paintbrush'))
  9388. .fontColor([Color.White])
  9389. .effectStrategy(1)
  9390. Text(`选择颜色`)
  9391. .fontSize(13)
  9392. .margin({ left: 10 })
  9393. .fontColor(Color.White)
  9394. }
  9395. }
  9396. .backgroundColor(Color.Transparent)
  9397. .border({
  9398. color: '#FFFFFF',
  9399. radius: 20,
  9400. width: 1.8
  9401. })
  9402. .height(36)
  9403. .width(110)
  9404. .onClick(() => {
  9405. this.isShowHLSelectColor = !this.isShowHLSelectColor
  9406. })
  9407. .bindPopup(this.isShowHLSelectColor, {
  9408. builder: this.SelectColor(true, isPip),
  9409. placement: Placement.Top,
  9410. mask: { color: '#33000000' },
  9411. enableArrow: false, //是否显示箭头
  9412. showInSubWindow: false,
  9413. onStateChange: (e) => {
  9414. if (!e.isVisible) {
  9415. this.isShowHLSelectColor = false
  9416. }
  9417. }
  9418. })
  9419. }
  9420. .width('76%')
  9421. .margin({
  9422. top: 10,
  9423. bottom: 10,
  9424. right: 45,
  9425. left: 20
  9426. })
  9427. if (isPip) {
  9428. Row() {
  9429. Text(`显示宽度:`)
  9430. .fontSize(14)
  9431. .fontColor(Color.White)
  9432. Slider({
  9433. value: this.pipLyWidth,
  9434. min: 10,
  9435. max: 800,
  9436. step: 1,
  9437. style: SliderStyle.OutSet
  9438. })
  9439. .blockColor(this.themeColor)
  9440. .trackColor($r('app.color.speed_text_color'))
  9441. .selectedColor(Color.White)
  9442. .trackThickness(6)
  9443. .onChange((value: number) => {
  9444. this.pipLyWidth = value
  9445. if (this.pipController) {
  9446. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  9447. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  9448. }
  9449. })
  9450. .width('76%')
  9451. }
  9452. .margin({
  9453. left: 20,
  9454. right: 15,
  9455. top: 5,
  9456. bottom: 5
  9457. })
  9458. Row() {
  9459. Text(`显示高度:`)
  9460. .fontSize(14)
  9461. .fontColor(Color.White)
  9462. Slider({
  9463. value: this.pipLyHeight,
  9464. min: 10,
  9465. max: 1000,
  9466. step: 1,
  9467. style: SliderStyle.OutSet
  9468. })
  9469. .blockColor(this.themeColor)
  9470. .trackColor($r('app.color.speed_text_color'))
  9471. .selectedColor(Color.White)
  9472. .trackThickness(6)
  9473. .onChange((value: number) => {
  9474. this.pipLyHeight = value
  9475. if (this.pipController) {
  9476. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  9477. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  9478. }
  9479. })
  9480. .width('76%')
  9481. }
  9482. .margin({
  9483. left: 20,
  9484. right: 15,
  9485. top: 5,
  9486. bottom: 5
  9487. })
  9488. }
  9489. Row() {
  9490. Text(`歌词字号:`)
  9491. .fontSize(14)
  9492. .fontColor(Color.White)
  9493. Slider({
  9494. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  9495. min: 12,
  9496. max: 30,
  9497. step: 0.1,
  9498. style: SliderStyle.OutSet
  9499. })
  9500. .blockColor(this.themeColor)
  9501. .trackColor($r('app.color.speed_text_color'))
  9502. .selectedColor(Color.White)
  9503. .trackThickness(6)
  9504. .onChange((value: number) => {
  9505. this.setLyricTextSize(value, isPip)
  9506. })
  9507. .width('76%')
  9508. }
  9509. .margin({
  9510. left: 20,
  9511. right: 15,
  9512. top: 5,
  9513. bottom: 5
  9514. })
  9515. Row() {
  9516. Text(`高亮倍数:`)
  9517. .fontSize(14)
  9518. .fontColor(Color.White)
  9519. Slider({
  9520. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  9521. min: 1,
  9522. max: 2,
  9523. step: 0.1,
  9524. style: SliderStyle.OutSet
  9525. })
  9526. .blockColor(this.themeColor)
  9527. .trackColor($r('app.color.speed_text_color'))
  9528. .selectedColor(Color.White)
  9529. .trackThickness(6)
  9530. .onChange((value: number) => {
  9531. this.setHighLyricTextSize(value, isPip)
  9532. })
  9533. .width('76%')
  9534. }
  9535. .margin({
  9536. left: 20,
  9537. right: 15,
  9538. top: 5,
  9539. bottom: 5
  9540. })
  9541. Row() {
  9542. Text(`歌词间隙:`)
  9543. .fontSize(14)
  9544. .fontColor(Color.White)
  9545. Slider({
  9546. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  9547. min: 0,
  9548. max: 100,
  9549. step: 1,
  9550. style: SliderStyle.OutSet
  9551. })
  9552. .blockColor(this.themeColor)
  9553. .trackColor($r('app.color.speed_text_color'))
  9554. .selectedColor(Color.White)
  9555. .trackThickness(6)
  9556. .onChange((value: number) => {
  9557. this.setLyricLineSpace(value, isPip)
  9558. })
  9559. .width('76%')
  9560. }
  9561. .margin({
  9562. left: 20,
  9563. right: 15,
  9564. top: 5,
  9565. bottom: 5
  9566. })
  9567. //取值间隔为100,默认为400,取值越大,字体越粗
  9568. Row() {
  9569. Text(`歌词字重:`)
  9570. .fontSize(14)
  9571. .fontColor(Color.White)
  9572. Slider({
  9573. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  9574. min: 100,
  9575. max: 900,
  9576. step: 100,
  9577. style: SliderStyle.OutSet
  9578. })
  9579. .blockColor(this.themeColor)
  9580. .trackColor($r('app.color.speed_text_color'))
  9581. .selectedColor(Color.White)
  9582. .trackThickness(6)
  9583. .onChange((value: number) => {
  9584. if (isPip) {
  9585. this.lyricTextWeightPip = value
  9586. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  9587. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  9588. } else {
  9589. this.lyricTextWeight = value
  9590. this.lyricController.setTextWeight(this.lyricTextWeight)
  9591. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  9592. }
  9593. })
  9594. .width('76%')
  9595. }
  9596. .margin({
  9597. left: 20,
  9598. right: 15,
  9599. top: 5,
  9600. bottom: 5
  9601. })
  9602. if (!isPip) {
  9603. Row() {
  9604. Text(`歌词模糊:`)
  9605. .fontSize(14)
  9606. .fontColor(Color.White)
  9607. Slider({
  9608. value: isPip ? this.blurDegreePip : this.blurDegree,
  9609. min: 0,
  9610. max: 5,
  9611. step: 0.1,
  9612. style: SliderStyle.OutSet
  9613. })
  9614. .blockColor(this.themeColor)
  9615. .trackColor($r('app.color.speed_text_color'))
  9616. .selectedColor(Color.White)
  9617. .trackThickness(6)
  9618. .onChange((value: number) => {
  9619. this.setBlurDegree(value, isPip)
  9620. })
  9621. .width('76%')
  9622. }
  9623. .margin({
  9624. left: 20,
  9625. right: 15,
  9626. top: 5,
  9627. bottom: 15
  9628. })
  9629. }
  9630. Row() {
  9631. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  9632. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  9633. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  9634. }
  9635. .justifyContent(FlexAlign.Center)
  9636. .margin({ top: 3, bottom: 10 })
  9637. }
  9638. }
  9639. private setBlurDegree(index: number, isPip: boolean) {
  9640. if (isPip) {
  9641. this.blurDegreePip = index
  9642. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  9643. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  9644. } else {
  9645. this.blurDegree = index
  9646. this.lyricController.setBlurDegree(this.blurDegree)
  9647. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  9648. }
  9649. }
  9650. private setLyricAlignMode(index: number, isPip: boolean) {
  9651. if (isPip) {
  9652. this.currentLyricAlignModePip = index
  9653. if (this.currentLyricAlignModePip === 1) {
  9654. this.lyricControllerXF.setAlignMode("left")
  9655. } else {
  9656. this.lyricControllerXF.setAlignMode("center")
  9657. }
  9658. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  9659. } else {
  9660. this.currentLyricAlignMode = index
  9661. if (this.currentLyricAlignMode === 1) {
  9662. this.lyricController.setAlignMode("left")
  9663. } else {
  9664. this.lyricController.setAlignMode("center")
  9665. }
  9666. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  9667. }
  9668. }
  9669. private setLyricTextSize(index: number, isPip: boolean) {
  9670. if (isPip) {
  9671. this.currentLyricSizePip = index
  9672. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  9673. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  9674. } else {
  9675. this.currentLyricSize = index
  9676. this.lyricController.setTextSize(this.currentLyricSize)
  9677. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  9678. }
  9679. }
  9680. private setHighLyricTextSize(scale: number, isPip: boolean) {
  9681. if (isPip) {
  9682. this.currentHightLyricSizePip = scale
  9683. this.lyricControllerXF
  9684. .setHighlightScale(this.currentHightLyricSizePip)
  9685. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  9686. } else {
  9687. this.currentHightLyricSize = scale
  9688. this.lyricController
  9689. .setHighlightScale(this.currentHightLyricSize)
  9690. PreferencesUtil.putSync('HighLyricTextSize', scale)
  9691. }
  9692. }
  9693. private setLyricLineSpace(index: number, isPip: boolean) {
  9694. if (isPip) {
  9695. this.currentLyricLineSpacePip = index
  9696. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  9697. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  9698. } else {
  9699. this.currentLyricLineSpace = index
  9700. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  9701. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  9702. }
  9703. }
  9704. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  9705. LogUtil.info('onecold isBG = ' + isBG)
  9706. if (isBG) { //如果是设置悬浮背景
  9707. this.pipBg = color
  9708. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  9709. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  9710. return
  9711. }
  9712. if (isPip) {
  9713. this.currentLyricColorPip = color
  9714. this.lyricControllerXF
  9715. .setTextColor(this.currentLyricColorPip)
  9716. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  9717. } else {
  9718. this.currentLyricColor = color
  9719. this.lyricController
  9720. .setTextColor(this.currentLyricColor)
  9721. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  9722. }
  9723. }
  9724. private changeLyricHightLightColor(color: string, isPip: boolean) {
  9725. if (isPip) {
  9726. this.currentHighLightLyricColorPip = color
  9727. this.lyricControllerXF
  9728. .setHighlightColor(this.currentHighLightLyricColorPip)
  9729. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  9730. } else {
  9731. this.currentHighLightLyricColor = color
  9732. this.lyricController
  9733. .setHighlightColor(this.currentHighLightLyricColor)
  9734. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  9735. }
  9736. }
  9737. // 构建时间控制器
  9738. @Builder
  9739. BuildTimeControls() {
  9740. Column() {
  9741. // 时间显示
  9742. Text(this.getTimeText())
  9743. .fontSize(18)
  9744. .fontColor(Color.White)
  9745. .margin({ bottom: 10 })
  9746. Row() {
  9747. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  9748. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  9749. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  9750. }
  9751. .justifyContent(FlexAlign.Center)
  9752. }
  9753. .margin({ top: 12, bottom: 8 })
  9754. }
  9755. // 精度按钮组件
  9756. @Builder
  9757. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  9758. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9759. Column() {
  9760. Image(icon)
  9761. .width(28)
  9762. .margin({ bottom: 5 })
  9763. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  9764. Text(label)
  9765. .fontSize(12)
  9766. .fontColor('#FFFFFF')
  9767. }
  9768. }
  9769. .backgroundColor(Color.Transparent)
  9770. .enabled(!this.isButtonDisabled(step))
  9771. .onClick(() => this.handlePrecisionAdjust(step))
  9772. .padding(5)
  9773. .width(66)
  9774. .height(66)
  9775. .margin({ left: 18, right: 18 })
  9776. .border({
  9777. color: '#FFFFFF',
  9778. width: 1.8
  9779. })
  9780. }
  9781. private handlePrecisionAdjust(step: number) {
  9782. if (step === 0) {
  9783. this.timeOffset = 0
  9784. return
  9785. }
  9786. // 精度处理:保留1位小数
  9787. const newOffset = Number((this.timeOffset + step).toFixed(5))
  9788. // 边界保护(±15.0秒)
  9789. if (newOffset < -30.0 || newOffset > 30.0) {
  9790. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  9791. return
  9792. }
  9793. // 状态更新
  9794. this.timeOffset = newOffset
  9795. }
  9796. // 按钮禁用逻辑
  9797. private isButtonDisabled(step: number): boolean {
  9798. const futureOffset = this.timeOffset + step
  9799. return (futureOffset < -30.0) || (futureOffset > 30.0)
  9800. }
  9801. // 时间显示文本升级
  9802. private getTimeText(): string {
  9803. const absValue = Math.abs(this.timeOffset)
  9804. return this.timeOffset === 0
  9805. ? '歌词时间已重置'
  9806. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  9807. }
  9808. // 导入 本地歌词 搜索歌词
  9809. @Builder
  9810. pushLyricButton(icon: Resource, step: number, label: string) {
  9811. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9812. Row() {
  9813. Image(icon)
  9814. .width(14)
  9815. .margin({ left: 13 })
  9816. Text(label)
  9817. .fontSize(12)
  9818. .margin({ left: 6 })
  9819. .fontColor('#FFFFFF')
  9820. }
  9821. }
  9822. .onClick(() => {
  9823. switch (step) {
  9824. case 0:
  9825. this.callFilePickerSelectFileForLyric()
  9826. break;
  9827. case 1:
  9828. //判断有没有设置api
  9829. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  9830. this.isLyricSetting = false
  9831. this.showTipsDialog()
  9832. return
  9833. }
  9834. if (StrUtil.isNotEmpty(this.videoUrl)) {
  9835. ToastUtil.showToast('正在获取')
  9836. this.isLyricSetting = false
  9837. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  9838. this.initLyric(lyricPath, true);
  9839. }
  9840. break;
  9841. }
  9842. })
  9843. .padding(5)
  9844. .width(110)
  9845. .backgroundColor(Color.Transparent)
  9846. .height(40)
  9847. .margin({ left: 6, right: 6 })
  9848. .border({
  9849. color: '#FFFFFF',
  9850. radius: 20,
  9851. width: 1.8
  9852. })
  9853. }
  9854. showVipDialog() {
  9855. DialogHelper.showCustomContentDialog({
  9856. dialogId: 'vip',
  9857. title: "友情提示",
  9858. autoCancel: false, //点击遮障层时,不关闭弹窗
  9859. backCancel: true, //点击返回键,不关闭弹窗
  9860. contentBuilder: () => {
  9861. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  9862. },
  9863. buttons: [],
  9864. })
  9865. }
  9866. //去赞助的自定义内容
  9867. @Builder
  9868. customVipBuilder(content: string) {
  9869. Column() {
  9870. Text(content)
  9871. .fontColor(Color.Gray)
  9872. .fontSize(16)
  9873. .alignSelf(ItemAlign.Start)
  9874. .margin({ bottom: 15 })
  9875. .fontSize(16)
  9876. Row() {
  9877. Button('取消')
  9878. .fontColor(Color.White)
  9879. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  9880. .height(50)
  9881. .layoutWeight(1)
  9882. .stateEffect(true)
  9883. .margin({ right: 6 })
  9884. .onClick(() => {
  9885. DialogHelper.closeDialog('vip'); //关闭弹框
  9886. })
  9887. Button('开通')
  9888. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  9889. .layoutWeight(1)
  9890. .height(50)
  9891. .backgroundColor(this.themeColor)
  9892. .stateEffect(true)
  9893. .margin({ left: 6 })
  9894. .onClick(() => {
  9895. DialogHelper.closeDialog('vip'); //关闭弹框
  9896. this.isShowPlay = false
  9897. this.mType = 1 //跳转到用户中心
  9898. // router.pushUrl({
  9899. // url: 'pages/VipPage'
  9900. // }, router.RouterMode.Single);
  9901. })
  9902. }
  9903. }
  9904. .width("100%")
  9905. .padding(10)
  9906. }
  9907. showTipsDialog() {
  9908. DialogHelper.showCustomContentDialog({
  9909. dialogId: 'tips',
  9910. title: "友情提示",
  9911. autoCancel: false, //点击遮障层时,不关闭弹窗
  9912. backCancel: true, //点击返回键,不关闭弹窗
  9913. contentBuilder: () => {
  9914. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  9915. },
  9916. buttons: [],
  9917. })
  9918. }
  9919. @Builder
  9920. customTipsBuilder(content: string) {
  9921. Column() {
  9922. Text(content)
  9923. .fontColor(Color.Gray)
  9924. .fontSize(16)
  9925. .alignSelf(ItemAlign.Start)
  9926. .margin({ bottom: 15 })
  9927. .fontSize(16)
  9928. Row() {
  9929. Button('取消')
  9930. .fontColor(Color.White)
  9931. .backgroundColor(this.themeColor)
  9932. .height(50)
  9933. .layoutWeight(1)
  9934. .stateEffect(true)
  9935. .margin({ right: 6 })
  9936. .onClick(() => {
  9937. DialogHelper.closeDialog('tips'); //关闭弹框
  9938. })
  9939. Button('跳转')
  9940. .fontColor(Color.White)//
  9941. .layoutWeight(1)
  9942. .height(50)
  9943. .backgroundColor(this.themeColor)
  9944. .stateEffect(true)
  9945. .margin({ left: 6 })
  9946. .onClick(() => {
  9947. DialogHelper.closeDialog('tips'); //关闭弹框
  9948. this.isShowEdit = false
  9949. this.longItemFilePath = ''
  9950. // if(this.isGridMusic&&!this.isShowPlay){
  9951. // this.longItemFilePath== ''
  9952. // }else{
  9953. // this.isShowEdit = false
  9954. // }
  9955. this.isShowMoreView = false;
  9956. this.isShowPlay = false
  9957. this.mType = 4
  9958. // router.pushUrl({
  9959. // url: 'pages/SettingPage'
  9960. // }, router.RouterMode.Single);
  9961. })
  9962. }
  9963. }
  9964. .width("100%")
  9965. .padding(10)
  9966. }
  9967. @Builder
  9968. PlayMoreSheet() {
  9969. Column() {
  9970. this.MoreList()
  9971. }
  9972. .width('100%')
  9973. .height('100%')
  9974. }
  9975. @Builder
  9976. MoreList() {
  9977. Scroll() {
  9978. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  9979. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  9980. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9981. Row() {
  9982. if (more.id === 3&&this.currentSong) {
  9983. Image(more.image)
  9984. .width(24)
  9985. .height(24)
  9986. .margin({ left: 10, right: 10 })
  9987. Text(more.title)
  9988. .fontSize(16)
  9989. .fontColor(Color.White)
  9990. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  9991. height: this.isCoverOpacity() ? '95%' : '95%',
  9992. dragBar: true,
  9993. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9994. showClose: true,
  9995. blurStyle: BlurStyle.Thin,
  9996. backgroundColor: Color.Transparent,
  9997. title: { title: '歌曲信息' }
  9998. })
  9999. } else if (more.id === 15 && this.currentSong) { //编辑标签
  10000. Image(more.image)
  10001. .width(24)
  10002. .height(24)
  10003. .margin({ left: 10, right: 10 })
  10004. Text(more.title)
  10005. .fontSize(16)
  10006. .fontColor(Color.White)
  10007. } else if (more.id === 5) { //定时关闭
  10008. Image(more.image)
  10009. .width(24)
  10010. .height(24)
  10011. .margin({ left: 10, right: 10 })
  10012. Text(more.title)
  10013. .fontSize(16)
  10014. .fontColor(Color.White)
  10015. .onClick(() => {
  10016. this.doMore(more.id)
  10017. })
  10018. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  10019. height: this.isCoverOpacity() ? '95%' : '95%',
  10020. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  10021. dragBar: true,
  10022. showClose: true,
  10023. title: { title: $r('app.string.time_close') }
  10024. })
  10025. } else if (more.id === 2) { //歌词设置
  10026. Image(more.image)
  10027. .width(24)
  10028. .height(24)
  10029. .margin({ left: 10, right: 10 })
  10030. Text(more.title)
  10031. .fontSize(16)
  10032. .fontColor(Color.White)
  10033. } else if (more.id === 16) { //悬浮歌词设置
  10034. Image(more.image)
  10035. .width(24)
  10036. .height(24)
  10037. .margin({ left: 10, right: 10 })
  10038. Text(more.title)
  10039. .fontSize(16)
  10040. .fontColor(Color.White)
  10041. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  10042. height: this.isCoverOpacity() ? '95%' : '95%',
  10043. dragBar: true,
  10044. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  10045. showClose: true,
  10046. blurStyle: BlurStyle.Thin,
  10047. backgroundColor: Color.Transparent,
  10048. title: { title: '悬浮歌词' }
  10049. })
  10050. } else if (more.id === 11) {
  10051. Image(more.image)
  10052. .width(24)
  10053. .height(24)
  10054. .margin({ left: 10, right: 10 })
  10055. Text(more.title)
  10056. .fontSize(16)
  10057. .fontColor(Color.White)
  10058. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  10059. height: this.isCoverOpacity() ? '95%' : '60%',
  10060. dragBar: true,
  10061. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  10062. showClose: true,
  10063. blurStyle: BlurStyle.Thin,
  10064. backgroundColor: Color.Transparent,
  10065. title: { title: '跳过头尾' }
  10066. })
  10067. } else if (more.id === 12) { //投播
  10068. AVCastPicker({
  10069. customPicker: (): void => this.TPImageBuilder(more),
  10070. onStateChange: (state) => {
  10071. if (state == AVCastPickerState.STATE_APPEARING) {
  10072. console.log(' The picker starts showing.');
  10073. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  10074. console.log(' The picker finishes presenting.');
  10075. }
  10076. },
  10077. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  10078. sessionType: 'video'
  10079. })
  10080. .id('AVCastPicker')
  10081. } else {
  10082. Image(more.image)
  10083. .width(24)
  10084. .height(24)
  10085. .fillColor(Color.White)
  10086. .margin({ left: 10, right: 10 })
  10087. .onClick(() => {
  10088. this.doMore(more.id)
  10089. })
  10090. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  10091. .fontSize(16)
  10092. .fontColor(Color.White)
  10093. .onClick(() => {
  10094. this.doMore(more.id)
  10095. })
  10096. Select([//倍速
  10097. { value: '0.25x' },
  10098. { value: '0.5x' },
  10099. { value: '0.75x' },
  10100. { value: '1x' },
  10101. { value: '1.25x' },
  10102. { value: '1.5x' },
  10103. { value: '1.75x' },
  10104. { value: '2x' },
  10105. { value: '3x' }])
  10106. .font({ size: 16, weight: FontWeight.Medium })
  10107. .fontColor($r('sys.color.white'))
  10108. .margin({ left: 25 })
  10109. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  10110. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  10111. .value(Utility.optimizedFormat(this.playSpeed))
  10112. .onSelect(async (_index: number, text?: string | undefined) => {
  10113. let speed = parseFloat(text?.replace('x', '') || '1');
  10114. if (!CommonConstants.video_speed_list.includes(speed)) {
  10115. speed = 1;
  10116. }
  10117. this.playSpeed = speed
  10118. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  10119. })
  10120. Slider({
  10121. value: this.volume,
  10122. min: 0,
  10123. max: 1,
  10124. step: 0.1,
  10125. style: SliderStyle.OutSet
  10126. })
  10127. .margin({ left: 18, right: 8 })
  10128. .blockColor(this.themeColor)
  10129. .trackColor($r('app.color.speed_text_color'))
  10130. .selectedColor(Color.White)
  10131. .trackThickness(9)
  10132. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  10133. .onChange((value: number) => {
  10134. this.volume = value;
  10135. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  10136. PreferencesUtil.putSync('DefalutVolume',this.volume)
  10137. })
  10138. .layoutWeight(1)
  10139. Blank()
  10140. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  10141. .selectedColor(this.themeColor)
  10142. .switchPointColor(Color.White)
  10143. .margin({ right: 15 })
  10144. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10145. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  10146. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  10147. if (more.id == 6) {
  10148. this.isMusicMemoryPlay = checked;
  10149. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  10150. if (this.isMusicMemoryPlay) {
  10151. ToastUtil.showToast('记忆播放已开启')
  10152. } else {
  10153. ToastUtil.showToast('记忆播放已关闭')
  10154. }
  10155. }
  10156. })
  10157. .width(48)
  10158. .height(24);
  10159. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  10160. .selectedColor(this.themeColor)
  10161. .switchPointColor(Color.White)
  10162. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10163. .margin({ right: 15 })
  10164. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  10165. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  10166. if (more.id == 7) {
  10167. this.isMusicBGCover = checked;
  10168. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  10169. if (this.isMusicBGCover) {
  10170. ToastUtil.showToast('播放背景随音乐封面已开启')
  10171. } else {
  10172. ToastUtil.showToast('播放背景随音乐封面已关闭')
  10173. }
  10174. }
  10175. })
  10176. .width(48)
  10177. .height(24);
  10178. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  10179. .selectedColor(this.themeColor)
  10180. .switchPointColor(Color.White)
  10181. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10182. .margin({ right: 15 })
  10183. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  10184. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  10185. if (more.id == 8) {
  10186. this.isSavePlayMode = checked;
  10187. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  10188. if (this.isSavePlayMode) {
  10189. ToastUtil.showToast('保存播放模式已开启')
  10190. } else {
  10191. ToastUtil.showToast('保存播放模式已关闭')
  10192. }
  10193. }
  10194. })
  10195. .width(48)
  10196. .height(24);
  10197. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  10198. .selectedColor(this.themeColor)
  10199. .switchPointColor(Color.White)
  10200. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10201. .margin({ right: 15 })
  10202. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  10203. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  10204. if (more.id == 13) {
  10205. this.isCoverRectangle = checked;
  10206. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  10207. if (this.isCoverRectangle) {
  10208. ToastUtil.showToast('封面方形已开启')
  10209. this.animationRoFun()
  10210. } else {
  10211. ToastUtil.showToast('封面圆形已开启')
  10212. this.animationRoFun()
  10213. }
  10214. }
  10215. })
  10216. .width(48)
  10217. .height(24);
  10218. Toggle({ type: ToggleType.Switch, isOn: this.isShowBgLiuGUANG })
  10219. .selectedColor(this.themeColor)
  10220. .switchPointColor(Color.White)
  10221. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10222. .margin({ right: 15 })
  10223. .visibility(more.id == 21 ? Visibility.Visible : Visibility.None)
  10224. .onChange((checked: boolean) => { // 是否开启背景流光效果
  10225. if (more.id == 21) {
  10226. this.isShowBgLiuGUANG = checked;
  10227. PreferencesUtil.putSync('isShowBgLiuGUANG',this.isShowBgLiuGUANG)
  10228. }
  10229. })
  10230. .width(48)
  10231. .height(24);
  10232. }
  10233. }
  10234. .width('100%')
  10235. .height(45)
  10236. .padding(15)
  10237. .backgroundColor(Color.Transparent)
  10238. .borderRadius(12)
  10239. .margin({ bottom: 6 })
  10240. }
  10241. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  10242. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  10243. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  10244. .backgroundColor(Color.Transparent)
  10245. .onClick(() => {
  10246. this.doMore(more.id)
  10247. })
  10248. });
  10249. }
  10250. .width('100%')
  10251. .padding(16)
  10252. }.margin({ bottom: 18 })
  10253. }
  10254. @Builder
  10255. TPImageBuilder(more: MoreItem): void {
  10256. Row() {
  10257. Image($r('app.media.tuoping'))
  10258. .width(22)
  10259. .height(22)
  10260. .margin({ left: 10, right: 10 })
  10261. Text(more.title)
  10262. .fontSize(16)
  10263. .fontColor(Color.White)
  10264. }
  10265. .width('100%')
  10266. .layoutWeight(1)
  10267. .alignItems(VerticalAlign.Center)
  10268. .justifyContent(FlexAlign.Start)
  10269. }
  10270. private moreItems: MoreItem[] = [
  10271. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  10272. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  10273. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  10274. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  10275. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  10276. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  10277. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  10278. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  10279. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  10280. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  10281. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  10282. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  10283. { id: 4, image: $r('app.media.share2'), title: '分享' },
  10284. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  10285. // { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  10286. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  10287. { id : 21, image: $r('app.media.music_red'), title: '开启背景流光' },
  10288. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  10289. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  10290. ];
  10291. @State isShowBgLiuGUANG: boolean = true;
  10292. @State isShowMoreView: boolean = false;
  10293. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  10294. @State isShowTimeCloseMore: boolean = false
  10295. @State isShowDetailMore: boolean = false
  10296. @State isMusicBGCover: boolean = true
  10297. @State isSavePlayMode: boolean = true
  10298. @State isLyricSetting: boolean = false
  10299. @State isJumpSetting: boolean = false
  10300. @State isShowEdit: boolean = false
  10301. @State showPipLyric: boolean = false
  10302. async setRingTone() {
  10303. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  10304. return
  10305. }
  10306. // 确定后的逻辑
  10307. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  10308. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  10309. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  10310. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  10311. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  10312. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  10313. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  10314. , this.videoUrl, this.name).then(res => {
  10315. LogUtil.info('onecold setFlag :' + res);
  10316. });
  10317. }
  10318. doMore(moreId: number) {
  10319. switch (moreId) {
  10320. case 2: //歌词
  10321. this.isLyricSetting = !this.isLyricSetting;
  10322. this.isShowMoreView = false
  10323. break;
  10324. case 3: //详情
  10325. this.isShowDetailMore = !this.isShowDetailMore;
  10326. break;
  10327. case 4: //分享
  10328. if (this.currentSong !== undefined) {
  10329. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  10330. }
  10331. this.isShowMoreView = false
  10332. break;
  10333. case 5: //定时关闭
  10334. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  10335. break;
  10336. case 10: //设为铃声
  10337. this.setRingTone()
  10338. this.isShowMoreView = false
  10339. break;
  10340. case 11: //跳过头尾
  10341. this.isJumpSetting = !this.isJumpSetting;
  10342. break;
  10343. case 13: //倍速
  10344. break;
  10345. case 14: //搜索封面
  10346. if (this.currentSong !== undefined) {
  10347. this.doSearchCover(this.currentSong)
  10348. }
  10349. this.isShowMoreView = false
  10350. break;
  10351. case 15: //编辑标签
  10352. this.setEditStrEmpty()
  10353. this.tempLyricContent = this.lyricContent
  10354. this.isShowEdit = !this.isShowEdit;
  10355. break;
  10356. case 16: //悬浮歌词
  10357. this.showPipLyric = !this.showPipLyric;
  10358. break;
  10359. case 17: //横屏模式
  10360. if (this.isLandscape) {
  10361. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  10362. } else {
  10363. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  10364. }
  10365. this.isShowMoreView = false
  10366. break;
  10367. case 20://AB循环
  10368. this.isABSheet = !this.isABSheet
  10369. break;
  10370. }
  10371. }
  10372. //AB循环
  10373. @State isOpenAB:boolean = false
  10374. @State jumpATime:number = 0
  10375. @State jumpBTime:number = 0
  10376. @State isABSheet:boolean = false
  10377. @Builder
  10378. ABLoopSheet() {
  10379. ABLoopComptent({
  10380. jumpATime:this.jumpATime,
  10381. jumpBTime:this.jumpBTime,
  10382. onClickAItem: async ()=>{
  10383. if(this.mIjkMediaPlayer){
  10384. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  10385. }
  10386. },
  10387. onClickBItem: async ()=>{
  10388. if(this.mIjkMediaPlayer){
  10389. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  10390. if(this.jumpBTime<=this.jumpATime){
  10391. ToastUtil.showToast('设置B点时间不能小于A点时间')
  10392. this.jumpBTime = 0
  10393. }
  10394. }
  10395. },
  10396. onCancleButtonClick: async ()=>{
  10397. this.isOpenAB = false
  10398. this.isABSheet = false
  10399. },
  10400. onStartButtonClick: async ()=>{
  10401. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  10402. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  10403. return
  10404. }
  10405. this.isABSheet = false
  10406. this.startABLoop()
  10407. },
  10408. })
  10409. }
  10410. //开始AB循环
  10411. startABLoop(){
  10412. if(this.mIjkMediaPlayer){
  10413. this.seekTo(this.jumpATime+'')
  10414. this.isOpenAB = true
  10415. }
  10416. }
  10417. /**
  10418. * 切换横竖屏
  10419. *
  10420. */
  10421. setOrientation(orientation: number) {
  10422. this.windowClass.setPreferredOrientation(orientation).then(() => {
  10423. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  10424. }).catch((err: BusinessError) => {
  10425. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  10426. });
  10427. }
  10428. /**
  10429. * 画中画功能(悬浮歌词功能)
  10430. *
  10431. */
  10432. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  10433. pipController?: PiPWindow.PiPController;
  10434. navigationId: string = '';
  10435. @State curState: string = '';
  10436. @State curError: ResourceStr = '';
  10437. @State pipBg: string = '#E8E8E8'
  10438. @State buttonAction: string = '';
  10439. //开启画中画功能
  10440. async startPip() {
  10441. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  10442. if (!this.pipController) {
  10443. await this.createPipController();
  10444. }
  10445. if (!this.pipController) {
  10446. Logger.info(`[${TAG}] pipController create error`);
  10447. return;
  10448. }
  10449. await this.pipController.startPiP();
  10450. }
  10451. async stopPip() {
  10452. if (!this.pipController) {
  10453. Logger.info(`[${TAG}] pipController is not exist`);
  10454. return;
  10455. }
  10456. this.isOpenPip = false
  10457. await this.pipController.stopPiP();
  10458. }
  10459. async createPipController() {
  10460. this.pipController = await PiPWindow.create({
  10461. context: getContext(this),
  10462. componentController: this.xcomponentController,
  10463. navigationId: this.navigationId,
  10464. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  10465. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  10466. customUIController: this.nodeController,
  10467. });
  10468. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  10469. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  10470. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10471. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  10472. this.onStateChange(state, reason);
  10473. });
  10474. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  10475. this.onActionEvent(event, status);
  10476. });
  10477. }
  10478. destroyPipController() {
  10479. if (!this.pipController) {
  10480. return;
  10481. }
  10482. this.pipController.off('stateChange');
  10483. this.pipController.off('controlPanelActionEvent');
  10484. this.pipController = undefined;
  10485. }
  10486. onStateChange(state: PiPWindow.PiPState, reason: string) {
  10487. switch (state) {
  10488. case PiPWindow.PiPState.ABOUT_TO_START:
  10489. this.curState = 'ABOUT_TO_START';
  10490. this.curError = $r('app.string.current_error_hint');
  10491. break;
  10492. case PiPWindow.PiPState.STARTED:
  10493. this.curState = 'STARTED';
  10494. this.curError = $r('app.string.current_error_hint');
  10495. break;
  10496. case PiPWindow.PiPState.ABOUT_TO_STOP:
  10497. this.curState = 'ABOUT_TO_STOP';
  10498. this.curError = $r('app.string.current_error_hint');
  10499. break;
  10500. case PiPWindow.PiPState.STOPPED:
  10501. this.curState = 'STOPPED';
  10502. this.curError = $r('app.string.current_error_hint');
  10503. this.stopPip()
  10504. this.destroyPipController()
  10505. break;
  10506. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  10507. this.curState = 'ABOUT_TO_RESTORE';
  10508. this.curError = $r('app.string.current_error_hint');
  10509. break;
  10510. case PiPWindow.PiPState.ERROR:
  10511. this.curState = 'ERROR';
  10512. this.curError = reason;
  10513. break;
  10514. default:
  10515. break;
  10516. }
  10517. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  10518. }
  10519. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  10520. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  10521. switch (event) {
  10522. case 'playbackStateChanged':
  10523. if (status === 0) {
  10524. this.pause();
  10525. } else {
  10526. console.info('onecold startPlayOrResumePlay 9869')
  10527. this.startPlayOrResumePlay();
  10528. }
  10529. break;
  10530. case 'nextVideo':
  10531. // 切换到下一个视频
  10532. this.playNext().catch(() => {
  10533. Logger.error('heanup onActionEvent playNext', `播放下一首失败`);
  10534. });
  10535. break;
  10536. case 'previousVideo':
  10537. // 切换到上一个视频
  10538. this.playPrevious().catch(() => {
  10539. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败`);
  10540. });
  10541. break;
  10542. case 'previousVideo':
  10543. // 切换到上一个视频
  10544. this.playPrevious().catch(() => {
  10545. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败:`);
  10546. });
  10547. break;
  10548. default:
  10549. }
  10550. this.buttonAction = event + `-status:${status}`;
  10551. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  10552. }
  10553. /**
  10554. * 画中画功能(悬浮歌词功能)结束
  10555. *
  10556. */
  10557. async doSearchCover(item: VideoItem): Promise<string> {
  10558. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  10559. this.isShowMoreView = false;
  10560. this.showTipsDialog();
  10561. return ''; // Return empty string when no API is configured
  10562. }
  10563. if (!item) {
  10564. return ''; // Return empty string if item is undefined
  10565. }
  10566. const artist = item?.artist || ''; // Use empty string if artist is missing
  10567. return this.searchCover(item, item.name, artist); // Await is not needed here as we return the promise directly
  10568. }
  10569. /**
  10570. *api搜索封面
  10571. *item,根据title和artist
  10572. */
  10573. searchCover(item: VideoItem, title: string, artist: string): Promise<string> {
  10574. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  10575. LogUtil.debug("onecold res =" + res);
  10576. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  10577. if (item.filePath == this.currentSong?.filePath) {
  10578. this.cover = res;
  10579. if (this.currentSong) {
  10580. this.currentSong.pixelMapPath = res;
  10581. }
  10582. }
  10583. // Update pixel map path but always return res regardless of success
  10584. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  10585. if (success) {
  10586. this.doUpdateData();
  10587. console.log("onecold 更新音乐封面成功,数据库已同步");
  10588. } else {
  10589. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  10590. }
  10591. // Note: We don't resolve/reject here because we already returned res
  10592. });
  10593. LogUtil.debug("onecold this.cover =" + this.cover);
  10594. }
  10595. return res; // Always return res regardless of updatePixelMapPath result
  10596. });
  10597. }
  10598. @State jumpTopTime: number = 0
  10599. @State jumpEndTime: number = 0
  10600. @State isOpenJump: boolean = false
  10601. @Builder
  10602. JumpTopEndSheet() {
  10603. Scroll() {
  10604. Column() {
  10605. Column() {
  10606. Text('仅对本播放列表有效')
  10607. .fontSize(16)
  10608. .fontColor($r('app.color.text_color'))
  10609. // 跳过头尾
  10610. Column() {
  10611. Row() {
  10612. Text('跳过片头:')
  10613. .fontSize(16)
  10614. .fontColor($r('app.color.text_color'))
  10615. Text(this.jumpTopTime + 's')
  10616. .fontSize(16)
  10617. .fontColor($r('app.color.text_color'))
  10618. }
  10619. .margin({ bottom: 5 })
  10620. Row() {
  10621. Slider({
  10622. value: this.jumpTopTime,
  10623. min: 0,
  10624. max: 120,
  10625. step: 1,
  10626. style: SliderStyle.OutSet
  10627. })
  10628. .blockColor(this.themeColor)
  10629. .trackColor($r('app.color.speed_text_color'))
  10630. .selectedColor(Color.White)
  10631. .trackThickness(8)
  10632. .onChange((value: number) => {
  10633. this.jumpTopTime = value;
  10634. })
  10635. .width('85%')
  10636. }
  10637. .alignItems(VerticalAlign.Top)
  10638. }
  10639. .margin({ top: 10, bottom: 10 })
  10640. // 跳过头尾
  10641. Column() {
  10642. Row() {
  10643. Text('跳过片尾:')
  10644. .fontSize(16)
  10645. .fontColor($r('app.color.text_color'))
  10646. Text(this.jumpEndTime + 's')
  10647. .fontSize(16)
  10648. .fontColor($r('app.color.text_color'))
  10649. }
  10650. .margin({ bottom: 5 })
  10651. Row() {
  10652. Slider({
  10653. value: this.jumpEndTime,
  10654. min: 0,
  10655. max: 120,
  10656. step: 1,
  10657. style: SliderStyle.OutSet
  10658. })
  10659. .blockColor(this.themeColor)
  10660. .trackColor($r('app.color.speed_text_color'))
  10661. .selectedColor(Color.White)
  10662. .trackThickness(8)
  10663. .onChange((value: number) => {
  10664. this.jumpEndTime = value;
  10665. })
  10666. .width('85%')
  10667. }
  10668. .alignItems(VerticalAlign.Top)
  10669. }
  10670. .margin({ top: 10, bottom: 10 })
  10671. Row() {
  10672. Button('保存设置')
  10673. .fontColor(Color.White)
  10674. .layoutWeight(1)
  10675. .height(40)
  10676. .width(80)
  10677. .backgroundColor(this.themeColor)
  10678. .stateEffect(true)
  10679. .margin({ left: 0, bottom: 20 })
  10680. .onClick(async () => {
  10681. if (!Utility.isNoble()) {
  10682. this.isJumpSetting = false
  10683. this.isShowMoreView = false
  10684. this.showVipDialog()
  10685. return
  10686. }
  10687. if (this.currentSong === undefined) {
  10688. return
  10689. }
  10690. if (this.modeType === 0) {
  10691. let parentPath = FileUtil.getParentPath(this.videoUrl)
  10692. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  10693. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  10694. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  10695. } else if (this.modeType === 1) { //媒体库
  10696. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  10697. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  10698. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  10699. } else if (this.modeType === 2) { //艺术家
  10700. if (this.currentSong?.artist) {
  10701. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  10702. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  10703. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  10704. }
  10705. } else if (this.modeType === 3) { //专辑
  10706. if (this.currentSong?.album) {
  10707. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  10708. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  10709. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  10710. }
  10711. }
  10712. ToastUtil.showShort("保存成功")
  10713. this.isJumpSetting = false
  10714. })
  10715. }
  10716. .margin({
  10717. left: 38,
  10718. right: 38,
  10719. top: 10,
  10720. bottom: 10
  10721. })
  10722. .width(120)
  10723. .height(50)
  10724. }
  10725. }
  10726. }
  10727. .width('100%')
  10728. .height('100%')
  10729. }
  10730. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  10731. private onStateVastChange(state: AVCastPickerState) {
  10732. if (state == AVCastPickerState.STATE_APPEARING) {
  10733. console.log('The picker starts showing.');
  10734. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  10735. console.log('The picker finishes presenting.');
  10736. }
  10737. }
  10738. private showSelectLyric() {
  10739. DialogHelper.showActionSheetDialog({
  10740. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  10741. // sheets: ["本地歌词", "搜索歌词"],
  10742. sheets: [
  10743. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  10744. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  10745. ],
  10746. maskColor: Color.Transparent,
  10747. backgroundColor: $r('app.color.bg_card'),
  10748. transition: AnimationHelper.transitionInDown(666),
  10749. onAction: (index) => {
  10750. switch (index) {
  10751. case 0:
  10752. this.callFilePickerSelectFileForLyric()
  10753. break;
  10754. case 1:
  10755. if (StrUtil.isNotEmpty(this.videoUrl)) {
  10756. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  10757. this.initLyric(lyricPath);
  10758. }
  10759. break;
  10760. }
  10761. }
  10762. })
  10763. }
  10764. // 拉起picker选择文件管理器
  10765. async callFilePickerSelectFileForLyric(): Promise<void> {
  10766. try {
  10767. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  10768. DocumentSelectOptions.maxSelectNumber = 1
  10769. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  10770. let documentPicker = new picker.DocumentViewPicker();
  10771. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  10772. Logger.info(TAG,
  10773. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  10774. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  10775. this.saveVideoDatasLyric(DocumentSelectResult)
  10776. }
  10777. }).catch((err: BusinessError) => {
  10778. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  10779. });
  10780. } catch (err) {
  10781. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  10782. }
  10783. }
  10784. async saveVideoDatasLyric(uris: string[]) {
  10785. if (ArrayUtil.isEmpty(uris)) {
  10786. return
  10787. }
  10788. let newUris: string[] = [];
  10789. for (let i = 0; i < uris.length; i++) {
  10790. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  10791. Logger.info(TAG, 'filePath uri: ' + filePath);
  10792. newUris.push(filePath)
  10793. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  10794. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  10795. fileIo.copyFileSync(file.fd, file2.fd)
  10796. fileIo.closeSync(file);
  10797. fileIo.closeSync(file2);
  10798. this.initLyric(filePath,false,false,true)
  10799. }
  10800. }
  10801. private initDelayPlay(context: object) {
  10802. this.mContext = context;
  10803. }
  10804. startPipLyric() {
  10805. if (this.pipController) {
  10806. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  10807. PiPWindow.PiPControlStatus.PLAY);
  10808. }
  10809. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  10810. if (this.isOpenPip) {
  10811. this.startPip()
  10812. } else {
  10813. this.stopPip()
  10814. }
  10815. }
  10816. //startOffset 从cue分轨时间开始播
  10817. private startPlayOrResumePlay(startOffset?:number) {
  10818. //针对dsf文件高采样率sampleRate>441000,统一转wav播放
  10819. const sampleRate = this.currentSong?.sampleRate||0
  10820. if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  10821. console.info('onecold 采样率 ='+sampleRate)
  10822. let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  10823. console.info('onecold newDsfPath ='+newDsfPath)
  10824. if(!FileUtil.accessSync(newDsfPath)){
  10825. const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  10826. taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  10827. this.videoUrl = newDsfPath
  10828. this.startPlay(startOffset)
  10829. }).catch((e:object)=>{
  10830. console.info("task1 catch e: " + e);
  10831. })
  10832. }else{
  10833. this.videoUrl = newDsfPath
  10834. this.startPlay(startOffset)
  10835. }
  10836. }else{
  10837. this.startPlay(startOffset)
  10838. }
  10839. }
  10840. startPlay(startOffset?:number) {
  10841. this.startPipLyric()
  10842. this.mDestroyPage = false;
  10843. this.animationState = AnimationStatus.Running
  10844. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  10845. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  10846. this.stopProgressTask();
  10847. this.startProgressTask();
  10848. this.play(this.videoUrl.toString(),startOffset);
  10849. }
  10850. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  10851. this.mIjkMediaPlayer.start();
  10852. this.setProgress()
  10853. this.CONTROL_PlayStatus = PlayStatus.PLAY
  10854. }
  10855. this.setIsPlaying(true)
  10856. this.updateSessionPlayState(true)
  10857. this.watchStatus();
  10858. this.updateLastPlayTimeStr(this.videoUrl)
  10859. }
  10860. updateLastPlayTimeStr(filePath: string) {
  10861. // 检查是否为网络音频(WebDAV),如果是则不更新本地数据库
  10862. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_WEBDAV) {
  10863. Logger.info(`heanup 检测到网络音频播放,跳过数据库更新: ${filePath}`)
  10864. return;
  10865. }
  10866. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  10867. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  10868. if (success) {
  10869. this.getHistoryList(false)
  10870. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  10871. } else {
  10872. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  10873. }
  10874. });
  10875. }
  10876. private completionNum(num: number): string | number {
  10877. if (num < 10) {
  10878. return '0' + num;
  10879. } else {
  10880. return num;
  10881. }
  10882. }
  10883. private stringForTime(timeMs: number): string {
  10884. let totalSeconds: number | string = (timeMs / 1000);
  10885. let newSeconds: number | string = totalSeconds % 60;
  10886. let minutes: number | string = (totalSeconds / 60) % 60;
  10887. let hours: number | string = totalSeconds / 3600;
  10888. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  10889. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  10890. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  10891. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  10892. if (this.isCurrentTime) {
  10893. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  10894. this.oldSeconds = newSeconds
  10895. } else {
  10896. newSeconds = this.oldSeconds
  10897. }
  10898. }
  10899. newSeconds = this.completionNum(newSeconds);
  10900. if (hours > 0) {
  10901. return hours + ":" + minutes + ":" + newSeconds;
  10902. } else {
  10903. return minutes + ":" + newSeconds;
  10904. }
  10905. }
  10906. private setProgress() {
  10907. let position = this.mIjkMediaPlayer.getCurrentPosition();
  10908. let duration = this.mIjkMediaPlayer.getDuration();
  10909. let pos = 0;
  10910. if (duration > 0) {
  10911. this.slideEnable = true;
  10912. let curPercent = position / duration;
  10913. pos = curPercent * 100;
  10914. if (pos > this.PROGRESS_MAX_VALUE) {
  10915. this.progressValue = this.PROGRESS_MAX_VALUE
  10916. } else {
  10917. this.progressValue = pos;
  10918. }
  10919. }
  10920. // LogUtils.getInstance()
  10921. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  10922. this.totalTime = this.stringForTime(duration);
  10923. if (position > duration) {
  10924. position = duration;
  10925. }
  10926. this.isCurrentTime = true;
  10927. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  10928. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  10929. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  10930. this.currentTime = this.stringForTime(position);
  10931. this.isCurrentTime = false
  10932. if (this.mIjkMediaPlayer.isPlaying()) {
  10933. this.randomColor =
  10934. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  10935. //如果是开启AB循环
  10936. if(this.isOpenAB){
  10937. if(position >=this.jumpBTime){
  10938. this.seekTo(this.jumpATime+'')
  10939. return
  10940. }
  10941. }
  10942. // 判断是否播放到结束时间
  10943. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  10944. if (position >= duration - this.jumpEndTime * 1000) {
  10945. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  10946. this.CONTROL_PlayStatus = PlayStatus.INIT
  10947. this.startPlayOrResumePlay();
  10948. }else if (this.playType == 2) { //2:正常播放,单曲播完
  10949. this.showRePlay();
  10950. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  10951. this.progressValue = this.PROGRESS_MAX_VALUE;
  10952. this.slideEnable = false;
  10953. this.stop();
  10954. // ToastUtil.showToast('开始重新播放')
  10955. }else{
  10956. this.playNext().catch(() => {
  10957. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  10958. });
  10959. }
  10960. }
  10961. }
  10962. } else {
  10963. this.randomColor = 'rbg(0,0,0)'
  10964. }
  10965. }
  10966. private startProgressTask() {
  10967. let that = this;
  10968. this.updateProgressTimer = setInterval(() => {
  10969. //LogUtils.getInstance().LOGI("startProgressTask");
  10970. if (!that.mDestroyPage) {
  10971. that.setProgress();
  10972. }
  10973. }, 300);
  10974. }
  10975. private stopProgressTask() {
  10976. LogUtils.getInstance().LOGI("stopProgressTask");
  10977. clearInterval(this.updateProgressTimer);
  10978. }
  10979. private showLoadIng() {
  10980. this.loadingVisible = Visibility.Visible;
  10981. this.replayVisible = Visibility.None;
  10982. }
  10983. private hideLoadIng() {
  10984. this.loadingVisible = Visibility.None;
  10985. this.replayVisible = Visibility.None;
  10986. }
  10987. private showRePlay() {
  10988. this.loadingVisible = Visibility.None;
  10989. this.replayVisible = Visibility.Visible;
  10990. }
  10991. private async play(url: string,startOffset?:number) {
  10992. this.isShowBgLiuGUANG = PreferencesUtil.getBooleanSync('isShowBgLiuGUANG', true)
  10993. console.info('onecold this.url 1= '+url)
  10994. if(!url.toLowerCase().startsWith('http')){
  10995. let hasPermission = await PermissionUtil.activatePermission(url)
  10996. console.info('onecold this.hasPermission 1= '+hasPermission)
  10997. if(!url.includes(this.packName)){
  10998. const file = fs.openSync(url)
  10999. this.videoUrl = file.path
  11000. url= this.videoUrl
  11001. }
  11002. console.info('onecold this.hasPermission 1= '+hasPermission)
  11003. console.info('onecold this.videoUrl 1= '+this.videoUrl)
  11004. }
  11005. let that = this;
  11006. that.showLoadIng();
  11007. this.isOpenAB = false
  11008. //设置XComponent回调的context
  11009. if (!!this.mContext) {
  11010. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  11011. }
  11012. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  11013. this.mIjkMediaPlayer.reset();
  11014. }
  11015. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  11016. //设置debug模式
  11017. this.mIjkMediaPlayer.setDebug(false);
  11018. //初始化配置
  11019. this.mIjkMediaPlayer.native_setup();
  11020. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  11021. if(this.volumeSmall){
  11022. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  11023. this.mIjkMediaPlayer.setVolume('1', '1');
  11024. }else{
  11025. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  11026. }
  11027. }else{
  11028. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  11029. }
  11030. //设置视频源
  11031. this.mIjkMediaPlayer.setDataSource(url);
  11032. // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
  11033. const headers = new Map<string, string>();
  11034. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  11035. headers.set("Accept", "*/*");
  11036. headers.set("Range", "bytes=0-");
  11037. if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
  11038. &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
  11039. //如果封面为空,则搜索封面
  11040. this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
  11041. }
  11042. // 如果是WebDAV网络音频,使用webdav_account_id获取认证信息(等待完成后再设置一次性头部)
  11043. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_WEBDAV) {
  11044. Logger.info(`heanup WebDAV歌曲认证 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
  11045. if (this.currentSong.webdav_account_id) {
  11046. try {
  11047. const webdavManager = WebdavManager.getInstance();
  11048. const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  11049. if (webDavHeaders && webDavHeaders.size > 0) {
  11050. webDavHeaders.forEach((value, key) => headers.set(key, value));
  11051. Logger.info(`heanup 成功通过webdav_account_id获取并合并WebDAV认证头`);
  11052. } else {
  11053. Logger.warn(`heanup 通过webdav_account_id获取认证头失败,播放可能无法继续`);
  11054. }
  11055. } catch (error) {
  11056. const err = error as Error;
  11057. Logger.error(`heanup 获取WebDAV认证头时出错: ${err.message}`);
  11058. }
  11059. } else {
  11060. Logger.error(`heanup WebDAV歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法进行认证`);
  11061. }
  11062. }
  11063. // 统一设置带认证的请求头
  11064. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  11065. if (this.currentSong&&this.currentSong.type === CommonConstants.TYPE_WEBDAV) {
  11066. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  11067. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  11068. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  11069. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  11070. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  11071. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  11072. // 缓冲和播放优化设置
  11073. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  11074. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  11075. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1"); // 预加载启动
  11076. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  11077. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  11078. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  11079. // 网络相关设置
  11080. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  11081. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  11082. // 重连设置
  11083. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  11084. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  11085. }
  11086. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  11087. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  11088. // }
  11089. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  11090. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  11091. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  11092. const fileSize = await this.getFileSize(this.videoUrl);
  11093. let bufferSize = 1 * 1024 ; // 默认缓冲区大小为1MB
  11094. if (fileSize > 3 * 1024 * 1024 * 1024) { // 文件大于3GB
  11095. bufferSize = 25 * 1024 * 1024; // 设置缓冲区大小为25MB
  11096. }
  11097. // 使用软件解码(通常比硬件解码更节省内存)
  11098. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", '0');
  11099. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", '0');
  11100. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", '1024');
  11101. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzeduration", '500000');
  11102. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  11103. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  11104. //停止预读的最小帧数
  11105. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  11106. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  11107. // 设置其他缓冲相关选项
  11108. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  11109. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  11110. //启动预加载
  11111. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  11112. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  11113. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  11114. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  11115. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  11116. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  11117. // 因此需要播放器丢包,才不会累积延时
  11118. // 这个和第三个参数packet-buffering无关。
  11119. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  11120. // 无限制收流
  11121. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  11122. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  11123. // 屏幕常亮
  11124. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  11125. // 设置超时
  11126. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  11127. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  11128. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  11129. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  11130. // 变速播放
  11131. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  11132. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  11133. let Speed = this.mIjkMediaPlayer.getSpeed()
  11134. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  11135. //是否开启循环播放
  11136. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  11137. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  11138. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  11139. if (height === 0) {
  11140. return;
  11141. }
  11142. const va = width / height;
  11143. const vpa = that.videoParentAspectRatio;
  11144. if (vpa > va) {
  11145. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  11146. } else {
  11147. that.videoWidth = '100%';
  11148. }
  11149. if (width && height) {
  11150. that.videoAspectRatio = width / height;
  11151. }
  11152. LogUtils.getInstance()
  11153. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  11154. that.hideLoadIng();
  11155. }
  11156. }
  11157. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  11158. let mOnPreparedListener: OnPreparedListener = {
  11159. onPrepared: async () => {
  11160. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  11161. try {
  11162. //保存碰一碰分享的当前的歌曲
  11163. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  11164. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  11165. await this.initLyric(lyricPath);
  11166. setTimeout(() => {
  11167. this.avSessionController.initAvSession(false);
  11168. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  11169. this.setAvSessionListener();
  11170. this.updateSessionPlayState(true)
  11171. this.setCurrentPlayMode()
  11172. }, 500)
  11173. if(startOffset&&startOffset>0){//cue分轨播放
  11174. this.seekTo(startOffset + "");
  11175. this.saveLastPlayList()
  11176. return
  11177. }
  11178. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  11179. let timeoutPlay = 0
  11180. if (StrUtil.isNotEmpty(this.videoUrl) &&
  11181. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  11182. timeoutPlay = 1000
  11183. }
  11184. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  11185. if (this.modeType === 0) { //文件夹
  11186. let parentPath = FileUtil.getParentPath(this.videoUrl)
  11187. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  11188. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  11189. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  11190. } else if (this.modeType === 1) { //媒体库
  11191. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  11192. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  11193. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  11194. } else if (this.modeType === 2) { //艺术家
  11195. if (this.currentSong?.artist) {
  11196. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  11197. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  11198. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  11199. }
  11200. } else if (this.modeType === 3) { //专辑
  11201. if (this.currentSong?.album) {
  11202. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  11203. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  11204. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  11205. }
  11206. }
  11207. this.duration = this.mIjkMediaPlayer.getDuration()
  11208. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  11209. if (this.mIjkMediaPlayer != null) {
  11210. let jumpTopTimeMs = this.jumpTopTime*1000;
  11211. if (jumpTopTimeMs <= this.duration) {
  11212. // 调用 seekTo 方法,跳到指定时间
  11213. if(PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY,true)){
  11214. console.log('onecold jumpTopTime = '+jumpTopTimeMs);
  11215. const position:number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  11216. console.log('onecold position = '+position);
  11217. if (position > jumpTopTimeMs) {
  11218. jumpTopTimeMs = position
  11219. }
  11220. }
  11221. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  11222. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  11223. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  11224. }
  11225. }, timeoutPlay)
  11226. } else {
  11227. // 提示用户无法跳过
  11228. ToastUtil.showToast('跳过时间超过视频时长');
  11229. }
  11230. }
  11231. } else {
  11232. this.jumpTopTime = 0
  11233. this.jumpEndTime = 0
  11234. console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  11235. console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  11236. console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  11237. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  11238. //记忆播放(每一首都会记忆播放)
  11239. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  11240. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  11241. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  11242. this.restorePlaybackPosition() //读取播放记忆功能
  11243. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  11244. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  11245. this.restorePlaybackPosition() //读取播放记忆功能
  11246. }
  11247. this.isFirstStartPlay = false
  11248. }, timeoutPlay)
  11249. } else {
  11250. this.isFirstStartPlay = false
  11251. }
  11252. }
  11253. this.saveLastPlayList()
  11254. } catch (error) {
  11255. let err: BusinessError = error as BusinessError;
  11256. console.error('onecold failed with err: ' + JSON.stringify(err));
  11257. }
  11258. }
  11259. }
  11260. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  11261. let mOnTimedTextListener: OnTimedTextListener = {
  11262. onTimedText: () => {
  11263. }
  11264. }
  11265. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  11266. let mOnCompletionListener: OnCompletionListener = {
  11267. onCompletion: () => {
  11268. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  11269. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  11270. // 异步调用playNext
  11271. this.playNext().catch(() => {
  11272. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  11273. });
  11274. } else if (this.playType == 1) { //1:单片重复播放
  11275. this.CONTROL_PlayStatus = PlayStatus.INIT
  11276. console.info('onecold startPlayOrResumePlay 10592')
  11277. that.startPlayOrResumePlay();
  11278. } else if (this.playType == 2) { //2:正常播放,单曲播完
  11279. that.showRePlay();
  11280. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  11281. that.progressValue = this.PROGRESS_MAX_VALUE;
  11282. that.slideEnable = false;
  11283. that.stop();
  11284. // ToastUtil.showToast('开始重新播放')
  11285. } else if (this.playType == 3) { //3:随机播放
  11286. // 异步调用randomPlay
  11287. this.randomPlay().catch(() => {
  11288. Logger.error('heanup OnCompletionListener randomPlay', `随机播放失败`);
  11289. });
  11290. }
  11291. }
  11292. }
  11293. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  11294. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  11295. onBufferingUpdate: (percent: number) => {
  11296. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  11297. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  11298. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  11299. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  11300. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  11301. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  11302. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  11303. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  11304. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  11305. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  11306. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  11307. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  11308. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  11309. let Looping = this.mIjkMediaPlayer.isLooping()
  11310. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  11311. }
  11312. }
  11313. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  11314. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  11315. onSeekComplete: () => {
  11316. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  11317. console.info('onecold startPlayOrResumePlay 10643')
  11318. that.startPlayOrResumePlay();
  11319. }
  11320. }
  11321. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  11322. let mOnInfoListener: OnInfoListener = {
  11323. onInfo: (what: number, extra: number) => {
  11324. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  11325. that.hideLoadIng();
  11326. }
  11327. }
  11328. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  11329. let mOnErrorListener: OnErrorListener = {
  11330. onError: (what: number, extra: number) => {
  11331. this.stopProgressTask();
  11332. LogUtils.getInstance().LOGI("heanup OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  11333. LogUtils.getInstance().LOGI('heanup 播放错误,歌曲详情:' + JSON.stringify(this.currentSong))
  11334. // 检查是否为WebDAV播放错误
  11335. let isWebDavError = false;
  11336. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_WEBDAV && this.currentSong.filePath) {
  11337. try {
  11338. const globalContext = GlobalContext.getContext();
  11339. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  11340. if (webDavAuthInfo) {
  11341. isWebDavError = true;
  11342. }
  11343. } catch (error) {
  11344. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  11345. }
  11346. }
  11347. if (isWebDavError) {
  11348. Logger.error(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  11349. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  11350. // this.currentWebDavAuthInfo = null;
  11351. Logger.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  11352. // 根据错误代码提供更具体的错误信息
  11353. let errorMessage = "WebDAV播放失败";
  11354. if (what === -1) { // 网络错误
  11355. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  11356. } else if (what === -1004) { // HTTP 404
  11357. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  11358. } else if (what === -1001) { // 超时
  11359. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  11360. } else if (what === -1003) { // 无法解析主机
  11361. errorMessage = "无法连接到WebDAV服务器";
  11362. }
  11363. ToastUtil.showToast(errorMessage);
  11364. } else {
  11365. if (StrUtil.isNotEmpty(this.videoUrl) &&
  11366. !this.videoUrl.startsWith('http://') &&
  11367. !this.videoUrl.startsWith('https://') &&
  11368. !FileUtil.accessSync(this.videoUrl)) {
  11369. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  11370. } else {
  11371. ToastUtil.showToast(getContext()
  11372. .resourceManager
  11373. .getStringByNameSync("Honey_the_video_is_playing_errant_The_system_is_wandering"))
  11374. }
  11375. }
  11376. that.hideLoadIng();
  11377. }
  11378. }
  11379. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  11380. this.mIjkMediaPlayer.setMessageListener();
  11381. this.mIjkMediaPlayer.prepareAsync();
  11382. this.mIjkMediaPlayer.start();
  11383. }
  11384. //保存最后播放的那首歌和已经对应的播放列表
  11385. saveLastPlayList() {
  11386. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  11387. PreferencesUtil.putSync('LastMusicList', this.songList)
  11388. }
  11389. // 清空播放记录
  11390. clearVideoHistory() {
  11391. this.table.clearPlayHistory((success: boolean, error?: string) => {
  11392. if (success) {
  11393. this.historyList = [];
  11394. this.updateListData(this.historyList)
  11395. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  11396. ToastUtil.showToast('清空播放记录成功')
  11397. } else {
  11398. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  11399. }
  11400. });
  11401. }
  11402. public async setAvSessionListener() {
  11403. if (!this.avSessionController) {
  11404. return;
  11405. }
  11406. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  11407. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  11408. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  11409. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  11410. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  11411. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  11412. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  11413. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  11414. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  11415. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  11416. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  11417. }
  11418. setLoopMode() {
  11419. let itype = this.playType + 1
  11420. if (itype >= 4) {
  11421. this.playType = 0
  11422. ToastUtil.showToast('连续播放')
  11423. } else if (itype === 1) {
  11424. this.playType = 1
  11425. ToastUtil.showToast('单曲循环')
  11426. } else if (itype === 2) {
  11427. this.playType = 2
  11428. ToastUtil.showToast('单曲播完')
  11429. } else if (itype === 3) {
  11430. this.playType = 3
  11431. ToastUtil.showToast('随机播放')
  11432. } else if (itype === 0) {
  11433. this.playType = 0
  11434. ToastUtil.showToast('连续播放')
  11435. }
  11436. PreferencesUtil.putSync('musicPlayType', this.playType)
  11437. this.setCurrentPlayMode()
  11438. }
  11439. private sessionSetLoopModeCallback = (mode: number) => {
  11440. if (this.mIjkMediaPlayer != null) {
  11441. ToastUtil.showToast('当前播放模式:' + mode)
  11442. Logger.info('onecold 当前播放模式= ' + mode)
  11443. let hmPlayMode = mode + 1
  11444. if (hmPlayMode >= 4) {
  11445. hmPlayMode = 0
  11446. }
  11447. if (hmPlayMode === 1) {
  11448. this.playType = 1
  11449. ToastUtil.showToast('单曲循环')
  11450. } else if (hmPlayMode === 0) {
  11451. this.playType = 2
  11452. ToastUtil.showToast('单曲播完')
  11453. } else if (hmPlayMode === 3) {
  11454. this.playType = 3
  11455. ToastUtil.showToast('随机播放')
  11456. } else if (hmPlayMode === 2) {
  11457. this.playType = 0
  11458. ToastUtil.showToast('连续播放')
  11459. }
  11460. PreferencesUtil.putSync('musicPlayType', this.playType)
  11461. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  11462. let playBackState: avSession.AVPlaybackState = {
  11463. loopMode: hmPlayMode,
  11464. };
  11465. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  11466. console.info(`set setLoopMode AVPlaybackState successfully`);
  11467. }).catch((err: BusinessError) => {
  11468. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  11469. });
  11470. }
  11471. }
  11472. setCurrentPlayMode() {
  11473. if (!this.avSessionController) {
  11474. return;
  11475. }
  11476. let mLoopMode = 0
  11477. switch (this.playType) {
  11478. case 0:
  11479. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  11480. break;
  11481. case 1:
  11482. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  11483. break;
  11484. case 2:
  11485. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  11486. break;
  11487. case 3:
  11488. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  11489. break;
  11490. }
  11491. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  11492. let playBState: avSession.AVPlaybackState = {
  11493. loopMode: mLoopMode,
  11494. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  11495. };
  11496. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  11497. console.info(`set setLoopMode AVPlaybackState successfully`);
  11498. }).catch((err: BusinessError) => {
  11499. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  11500. });
  11501. }
  11502. private sessionToggleFavoriteCallback = (assetId: string) => {
  11503. if (this.mIjkMediaPlayer != null && this.currentSong) {
  11504. console.info(`on toggleFavorite `);
  11505. // 应用收到收藏命令,进行收藏处理。
  11506. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  11507. this.doFav(this.currentSong)
  11508. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  11509. let playbackState: avSession.AVPlaybackState = {
  11510. isFavorite: !this.isFac,
  11511. };
  11512. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  11513. console.info(`SetAVPlaybackState successfully`);
  11514. }).catch((err: BusinessError) => {
  11515. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  11516. });
  11517. }
  11518. }
  11519. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  11520. device: avSession.OutputDeviceInfo) => {
  11521. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  11522. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  11523. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  11524. await this.startCasting();
  11525. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  11526. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  11527. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  11528. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  11529. if (device) {
  11530. this.endCasting();
  11531. }
  11532. }
  11533. };
  11534. private async startCasting() {
  11535. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  11536. this.setPlaybackStateChangeListener();
  11537. this.pause();
  11538. this.initQueueItem();
  11539. this.prepare();
  11540. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  11541. refToIsCasting?.set(true);
  11542. this.castSeek = true;
  11543. this.isCastPlaying = true;
  11544. }
  11545. async changeCasting() {
  11546. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  11547. this.initQueueItem();
  11548. this.prepare();
  11549. this.setPlaybackStateChangeListener();
  11550. this.isCastPlaying = true;
  11551. this.castSeek = true;
  11552. }
  11553. public endCasting() {
  11554. this.avSessionController.getAvSession()?.stopCasting();
  11555. this.stopCast();
  11556. this.isCastPlaying = false;
  11557. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  11558. refToIsCasting?.set(false);
  11559. this.pause();
  11560. this.setIsPlaying(false);
  11561. // if (this.curIndex === this.curSource.index) {
  11562. // this.play
  11563. // this.seek(this.currentTime * 1000);
  11564. // this.setIsPlaying(true);
  11565. // } else {
  11566. // this.pauseVideo();
  11567. // this.setIsPlaying(false);
  11568. // }
  11569. }
  11570. public setIsPlaying(isPlayer: boolean) {
  11571. this.isPlaying = isPlayer;
  11572. // 发送播放状态变化事件给歌单详情页面
  11573. try {
  11574. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  11575. const currentFilePath = this.currentSong?.filePath || ''
  11576. const eventData: emitter.EventData = {
  11577. data: {
  11578. isPlaying: this.isPlaying,
  11579. curIndex: this.curIndex,
  11580. currentFilePath: currentFilePath
  11581. }
  11582. };
  11583. emitter.emit(eventPlaybackStatus, eventData)
  11584. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  11585. } catch (error) {
  11586. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  11587. }
  11588. }
  11589. private setPlaybackStateChangeListener(): void {
  11590. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  11591. this.castController?.on('endOfStream', this.reloadCasting);
  11592. this.castController?.on('playNext', this.playNextCallback);
  11593. this.castController?.on('playPrevious', this.playPreviousCallback);
  11594. }
  11595. private updateSessionPlayState(isPlay: boolean): void {
  11596. // if(!this.isBgPlayOpen)
  11597. // return
  11598. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  11599. this.setAVSessionPlayState({
  11600. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  11601. position: {
  11602. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  11603. updateTime: new Date().getTime()
  11604. }
  11605. });
  11606. }
  11607. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  11608. this.avSessionController.setAvSessionPlayState(playbackState)
  11609. }
  11610. private positionChange(position: number) {
  11611. this.currentTime2 = position / 1000;
  11612. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  11613. }
  11614. private playDurationChange(duration: number) {
  11615. this.duration = duration;
  11616. this.durationTime = Math.floor(this.duration / 1000);
  11617. this.durationStringTime = secondToTime((this.durationTime));
  11618. }
  11619. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  11620. const duration = playbackState?.extras?.duration;
  11621. if (typeof duration === 'number') {
  11622. this.playDurationChange(duration as number);
  11623. }
  11624. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  11625. this.positionChange(playbackState?.position?.elapsedTime);
  11626. }
  11627. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  11628. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  11629. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  11630. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  11631. this.isCastPlaying = false;
  11632. }
  11633. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  11634. this.isCastPlaying = true;
  11635. }
  11636. };
  11637. private reloadCasting = async () => {
  11638. let item = this.songList[this.curIndex];
  11639. let uri = fileUri.getUriFromPath(item.filePath);
  11640. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  11641. // description.startPosition = 0;
  11642. this.castItem = {
  11643. itemId: this.curIndex,
  11644. description: {
  11645. assetId: item.filePath,
  11646. title: item.name,
  11647. artist: '',
  11648. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  11649. // mediaUri: item.filePath,
  11650. fdSrc: {
  11651. fd: file.fd
  11652. },
  11653. // 该字段大写,音频'AUDIO',视频'VIDEO'
  11654. mediaType: 'VIDEO',
  11655. mediaSize: item.videoSize,
  11656. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  11657. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  11658. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  11659. duration: this.duration,
  11660. // albumCoverUri: 'https://www.example.jpeg',
  11661. // albumTitle: '《ExampleAlbum》',
  11662. appName: this.appName,
  11663. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  11664. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  11665. }
  11666. };
  11667. this.prepare();
  11668. this.isCastPlaying = true;
  11669. };
  11670. public playNextCallback = (): void => {
  11671. this.playNext().catch(() => {
  11672. Logger.error('heanup playNextCallback', `播放下一首失败`);
  11673. });
  11674. };
  11675. public playPreviousCallback = (): void => {
  11676. this.playPrevious().catch(() => {
  11677. Logger.error('heanup playNextCallback', `播放上一首失败`);
  11678. });
  11679. };
  11680. async prepare() {
  11681. await this.castController?.prepare(this.castItem);
  11682. await this.castController?.start(this.castItem);
  11683. }
  11684. public initQueueItem() {
  11685. let item = this.songList[this.curIndex];
  11686. let time = this.currentTime;
  11687. let uri = fileUri.getUriFromPath(item.filePath);
  11688. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  11689. this.castItem = {
  11690. itemId: this.curIndex,
  11691. description: {
  11692. assetId: item.filePath,
  11693. title: item.name,
  11694. artist: '',
  11695. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  11696. fdSrc: {
  11697. fd: file.fd
  11698. },
  11699. // 该字段大写,音频'AUDIO',视频'VIDEO'
  11700. mediaType: 'AUDIO',
  11701. mediaSize: item.videoSize,
  11702. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  11703. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  11704. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  11705. duration: this.duration,
  11706. // albumCoverUri: 'https://www.example.jpeg',
  11707. // albumTitle: '《ExampleAlbum》',
  11708. appName: this.appName,
  11709. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  11710. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  11711. }
  11712. };
  11713. }
  11714. async stopCast() {
  11715. try {
  11716. this.castController?.off('playbackStateChange');
  11717. this.castController?.off('endOfStream');
  11718. this.castController?.off('playNext');
  11719. this.castController?.off('playPrevious');
  11720. this.castController?.off('error');
  11721. } catch (error) {
  11722. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  11723. }
  11724. }
  11725. private sessionPlayCallback = (): void => {
  11726. console.info('onecold playOrPause 11050')
  11727. this.playOrPause()
  11728. };
  11729. private sessionPauseCallback = (): void => {
  11730. console.info('onecold playOrPause 11054')
  11731. this.pause()
  11732. };
  11733. private playOrPause() {
  11734. if (!this.debounce()) {
  11735. return;
  11736. }
  11737. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  11738. this.pause();
  11739. } else {
  11740. console.info('onecold startPlayOrResumePlay 11064')
  11741. this.startPlayOrResumePlay();
  11742. this.playChange()
  11743. }
  11744. }
  11745. private sessionPlayNextCallback = (): void => {
  11746. this.playNext().catch(() => {
  11747. Logger.error('heanup sessionPlayPreviousCallback', `播放下 一首失败`);
  11748. });
  11749. };
  11750. private sessionPlayPreviousCallback = (): void => {
  11751. this.playPrevious().catch(() => {
  11752. Logger.error('heanup sessionPlayPreviousCallback', `播放上一首失败`);
  11753. });
  11754. };
  11755. private sessionStopCallback = (): void => {
  11756. this.stop()
  11757. };
  11758. private sessionFastForwardCallback = (time?: number) => {
  11759. if (!time) {
  11760. return;
  11761. }
  11762. if (this.mIjkMediaPlayer != null) {
  11763. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  11764. let seeTime = curPosition + time * 1000;
  11765. // 限制 seekValue 在合法范围内
  11766. if (seeTime < 0) {
  11767. seeTime = 0;
  11768. } else if (seeTime > this.duration) {
  11769. seeTime = this.duration;
  11770. }
  11771. Logger.info('onecold seeTime= ' + seeTime)
  11772. this.setSeekToActionProgress(seeTime)
  11773. this.seekTo(seeTime + "")
  11774. }
  11775. };
  11776. /**
  11777. * Gesture method onActionUpdate.
  11778. *
  11779. * @param event Gesture event.手势拖动设置快进和后退
  11780. */
  11781. private setSeekToActionProgress(position: number) {
  11782. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  11783. let duration = this.mIjkMediaPlayer.getDuration();
  11784. let pos = 0;
  11785. if (duration > 0) {
  11786. this.slideEnable = true;
  11787. let curPercent = position / duration;
  11788. pos = curPercent * 100;
  11789. if (pos > this.PROGRESS_MAX_VALUE) {
  11790. this.progressValue = this.PROGRESS_MAX_VALUE
  11791. } else {
  11792. this.progressValue = pos;
  11793. }
  11794. }
  11795. // LogUtils.getInstance()
  11796. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  11797. this.totalTime = this.stringForTime(duration);
  11798. if (position > duration) {
  11799. position = duration;
  11800. }
  11801. this.isCurrentTime = true;
  11802. this.currentTime = this.stringForTime(position);
  11803. this.isCurrentTime = false
  11804. }
  11805. private sessionRewindCallback = (time?: number) => {
  11806. if (!time) {
  11807. return;
  11808. }
  11809. if (this.mIjkMediaPlayer != null) {
  11810. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  11811. let seeTime = curPosition - time * 1000;
  11812. // 限制 seekValue 在合法范围内
  11813. if (seeTime < 0) {
  11814. seeTime = 0;
  11815. } else if (seeTime > this.duration) {
  11816. seeTime = this.duration;
  11817. }
  11818. Logger.info('onecold seeTime= ' + seeTime)
  11819. this.setSeekToActionProgress(seeTime)
  11820. this.seekTo(seeTime + "")
  11821. }
  11822. };
  11823. private sessionSeekCallback = (seekTime: number) => {
  11824. if (this.mIjkMediaPlayer != null) {
  11825. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  11826. this.seekTo(seekTime + "")
  11827. }
  11828. };
  11829. private async getFileSize(filePath: string): Promise<number> {
  11830. try {
  11831. const stat = await fs.stat(filePath);
  11832. return stat.size;
  11833. } catch (err) {
  11834. console.error('Failed to get file size: ' + err.message);
  11835. return 0;
  11836. }
  11837. }
  11838. private pause() {
  11839. if (this.mIjkMediaPlayer.isPlaying()) {
  11840. this.savePlaybackPosition();
  11841. this.mIjkMediaPlayer.pause();
  11842. this.setProgress();
  11843. this.mDestroyPage = true;
  11844. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  11845. this.updateSessionPlayState(false)
  11846. this.playChange()
  11847. if (this.pipController) {
  11848. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  11849. PiPWindow.PiPControlStatus.PAUSE);
  11850. }
  11851. }
  11852. }
  11853. private stop() {
  11854. this.savePlaybackPosition();
  11855. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11856. this.mIjkMediaPlayer.stop();
  11857. this.mIjkMediaPlayer.release();
  11858. this.stopProgressTask();
  11859. this.updateSessionPlayState(false)
  11860. this.playChange()
  11861. this.watchStatus();
  11862. }
  11863. //保持记忆播放功能
  11864. private savePlaybackPosition() {
  11865. if (this.mIjkMediaPlayer != null) {
  11866. const position = this.mIjkMediaPlayer.getCurrentPosition();
  11867. // ToastUtil.showToast('保存记忆播放 = ' + position)
  11868. const duration = this.mIjkMediaPlayer.getDuration();
  11869. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  11870. // 如果播放位置接近视频末尾,则保存 position 为 0
  11871. const playbackPosition = (duration - position < threshold) ? 0 : position;
  11872. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  11873. }
  11874. }
  11875. //获取记忆播放功能
  11876. private restorePlaybackPosition() {
  11877. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  11878. // ToastUtil.showToast('position = ' + position)
  11879. if (this.mIjkMediaPlayer != null && position > 0) {
  11880. // ToastUtil.showToast('seekTo = ' + position)
  11881. this.seekTo(position + "");
  11882. }
  11883. }
  11884. private seekTo(value: string) {
  11885. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  11886. ToastUtil.showToast('wma格式不支持拖动快进。')
  11887. return
  11888. }
  11889. this.isSeekTo = true
  11890. this.mIjkMediaPlayer.seekTo(value);
  11891. console.info('onecold startPlayOrResumePlay 11227')
  11892. // this.startPlayOrResumePlay()
  11893. // 在这里恢复计时器状态
  11894. this.setProgress()
  11895. this.isSeekTo = false
  11896. }
  11897. // 添加到下一首播放
  11898. private addToNextPlay(song: VideoItem) {
  11899. if (!this.debounce()) {
  11900. return;
  11901. }
  11902. if (this.currentSong) {
  11903. if (this.currentSong === song) {
  11904. ToastUtil.showToast('当前已经在播放这首歌了!')
  11905. return
  11906. }
  11907. }
  11908. // 如果未开始播放或队列为空
  11909. if (this.curIndex === -1 || this.songList.length === 0) {
  11910. this.songList = [song];
  11911. this.curIndex = 0;
  11912. this.doPlay(song)
  11913. return;
  11914. }
  11915. // 插入到当前索引+1的位置
  11916. const insertPos = this.curIndex + 1;
  11917. this.songList.splice(insertPos, 0, song);
  11918. this.songList = [...this.songList]; // 触发状态更新
  11919. this.sonDataSource.pushArrayData(this.songList)
  11920. ToastUtil.showToast('已添加至下一首播放')
  11921. }
  11922. //后退10s,可再设置设置默认几秒
  11923. backForward() {
  11924. if(this.mIjkMediaPlayer){
  11925. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  11926. let value = pos - Number(this.fastForwardSeconds) * 1000;
  11927. this.seekTo(value+"");
  11928. }
  11929. }
  11930. //快进10s,可再设置设置默认几秒
  11931. fastForward() {
  11932. if(this.mIjkMediaPlayer){
  11933. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  11934. let value = pos + Number(this.fastForwardSeconds) * 1000;
  11935. this.seekTo(value+"");
  11936. }
  11937. }
  11938. //下一个
  11939. private async playNext() {
  11940. if (!this.debounce()) {
  11941. return;
  11942. }
  11943. if (this.playType == 3) { //3:随机播放
  11944. await this.randomPlay()
  11945. return;
  11946. }
  11947. if (ArrayUtil.isNotEmpty(this.songList)) {
  11948. if (this.curIndex == this.songList.length - 1) {
  11949. this.curIndex = 0;
  11950. } else {
  11951. this.curIndex++;
  11952. }
  11953. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11954. this.stop();
  11955. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  11956. this.currentSong = this.songList[this.curIndex];
  11957. Logger.info('heanup playNext', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  11958. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  11959. this.videoUrl = await setVideoUrlForSong(this.currentSong);
  11960. this.artist = this.songList[this.curIndex].artist
  11961. this.name = this.songList[this.curIndex].name
  11962. //this.cover = this.songList[this.curIndex].pixelMapPath
  11963. this.changeImageAnimation()
  11964. }
  11965. }
  11966. changeImageAnimation() {
  11967. if(this.openSkipSongAnimate){
  11968. // 第一步:淡出动画
  11969. this.getUIContext()?.animateTo({
  11970. duration: 500,
  11971. curve: Curve.EaseOut,
  11972. }, () => {
  11973. this.opacityValueImage = 0.1;
  11974. if(this.isCoverRectangle){
  11975. this.scaleValueImage = 0.88
  11976. }
  11977. });
  11978. // 第二步:切换图片后淡入
  11979. setTimeout(() => {
  11980. this.cover = this.songList[this.curIndex].pixelMapPath
  11981. this.getUIContext()?.animateTo({
  11982. duration: 500,
  11983. curve: Curve.EaseIn,
  11984. }, () => {
  11985. this.opacityValueImage = 1;
  11986. this.scaleValueImage = 1 // 图标恢复到原始大小
  11987. this.startPlayOrResumePlay()
  11988. });
  11989. }, 500);
  11990. }else{
  11991. this.cover = this.songList[this.curIndex].pixelMapPath
  11992. this.startPlayOrResumePlay()
  11993. }
  11994. }
  11995. // 存储已播放的歌曲索引
  11996. private playedIndices: Set<number> = new Set();
  11997. //随机播放
  11998. private async randomPlay() {
  11999. // if (!this.debounce()) {
  12000. // return;
  12001. // }
  12002. if (ArrayUtil.isNotEmpty(this.songList)) {
  12003. if (this.songList.length > 3) {
  12004. // 如果所有歌曲都播放过一次,清空已播放索引集合
  12005. if (this.playedIndices.size === this.songList.length) {
  12006. this.playedIndices.clear();
  12007. }
  12008. // 随机选择一个未播放的歌曲索引
  12009. let newIndex: number;
  12010. // 添加超时机制防止无限循环
  12011. let attempt = 0;
  12012. const maxAttempts = 100; // 根据需求调整
  12013. do {
  12014. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  12015. attempt++;
  12016. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  12017. if (attempt >= maxAttempts) {
  12018. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  12019. newIndex = Math.floor(Math.random() * this.songList.length);
  12020. }
  12021. this.curIndex = newIndex;
  12022. this.playedIndices.add(newIndex);
  12023. } else {
  12024. // 当歌曲数量小于或等于3时,直接播放下一首
  12025. if (this.curIndex == this.songList.length - 1) {
  12026. this.curIndex = 0;
  12027. } else {
  12028. this.curIndex++;
  12029. }
  12030. }
  12031. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12032. this.stop();
  12033. this.currentSong = this.songList[this.curIndex];
  12034. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12035. this.videoUrl = await setVideoUrlForSong(this.currentSong);
  12036. this.name = this.songList[this.curIndex].name;
  12037. this.artist = this.songList[this.curIndex].artist
  12038. // this.cover = this.songList[this.curIndex].pixelMapPath
  12039. this.changeImageAnimation()
  12040. }
  12041. }
  12042. private async playIndex(index: number) {
  12043. if (!this.debounce()) {
  12044. return;
  12045. }
  12046. if (ArrayUtil.isNotEmpty(this.songList)) {
  12047. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12048. this.stop();
  12049. this.curIndex = index;
  12050. this.currentSong = this.songList[index];
  12051. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12052. this.videoUrl = await setVideoUrlForSong(this.currentSong);
  12053. this.name = this.currentSong.name
  12054. this.artist = this.currentSong.artist
  12055. this.changeImageAnimation()
  12056. }
  12057. }
  12058. //上一个
  12059. private async playPrevious() {
  12060. if (!this.debounce()) {
  12061. return;
  12062. }
  12063. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  12064. this.randomModePlayFromHistory()
  12065. return;
  12066. }
  12067. if (this.curIndex == 0) {
  12068. this.curIndex = this.songList.length - 1;
  12069. } else {
  12070. this.curIndex--;
  12071. }
  12072. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12073. this.stop();
  12074. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  12075. this.currentSong = this.songList[this.curIndex];
  12076. Logger.info('heanup playPrevious', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  12077. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12078. this.videoUrl = await setVideoUrlForSong(this.currentSong);
  12079. this.name = this.songList[this.curIndex].name
  12080. this.artist = this.songList[this.curIndex].artist
  12081. this.changeImageAnimation()
  12082. }
  12083. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  12084. private async randomModePlayFromHistory() {
  12085. if (this.historyList.length >= 2) {
  12086. // 播放历史记录的第二首
  12087. const prevSong = this.historyList[1];
  12088. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  12089. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12090. this.stop();
  12091. // 直接使用历史记录中的歌曲信息,历史记录中的数据应该是完整的
  12092. this.currentSong = prevSong;
  12093. Logger.info('heanup randomModePlayFromHistory', `直接使用历史歌曲信息: ${prevSong.name}, type: ${prevSong.type}`);
  12094. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12095. this.videoUrl = await setVideoUrlForSong(this.currentSong);
  12096. this.cover = prevSong.pixelMapPath
  12097. this.artist = prevSong.artist
  12098. this.name = prevSong.name;
  12099. console.info('onecold startPlayOrResumePlay 11434')
  12100. this.startPlayOrResumePlay();
  12101. } else {
  12102. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  12103. if (this.curIndex === 0) {
  12104. this.curIndex = this.songList.length - 1;
  12105. } else {
  12106. this.curIndex--;
  12107. }
  12108. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12109. this.stop();
  12110. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  12111. this.currentSong = this.songList[this.curIndex];
  12112. Logger.info('heanup randomModePlayFromHistory', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  12113. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12114. this.videoUrl = await setVideoUrlForSong(this.currentSong);
  12115. this.artist = this.songList[this.curIndex].artist
  12116. this.name = this.songList[this.curIndex].name;
  12117. this.changeImageAnimation()
  12118. }
  12119. }
  12120. debounce() {
  12121. const delay = 600;
  12122. let cur = new Date().getTime();
  12123. if (cur - this.last > delay) {
  12124. this.last = cur;
  12125. return true;
  12126. }
  12127. return false;
  12128. }
  12129. /**
  12130. * Sets whether the screen is a constant based on the playback status.
  12131. */
  12132. watchStatus() {
  12133. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  12134. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  12135. this.windowClass.setWindowKeepScreenOn(true);
  12136. } else {
  12137. this.windowClass.setWindowKeepScreenOn(false);
  12138. }
  12139. }
  12140. /**
  12141. * Volume gesture method onActionStart.
  12142. *
  12143. * @param event Gesture event.
  12144. */
  12145. private customDialogComponentIdMM: number = 0
  12146. @Builder
  12147. customDialogComponentMM() {
  12148. Column() {
  12149. Row() {
  12150. Blank()
  12151. Text('验证密码')
  12152. .fontSize(22)
  12153. .fontColor($r('app.color.pri_bg'))
  12154. .margin({ top: 18 })
  12155. Blank()
  12156. Image($r('app.media.close'))
  12157. .fillColor(Color.White)
  12158. .margin({ top: 18, right: 18 })
  12159. .width(20)
  12160. .onClick(() => {
  12161. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  12162. })
  12163. }
  12164. .width('100%') // 使Row占据整个宽度
  12165. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  12166. Verify({
  12167. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  12168. });
  12169. }.height('60%')
  12170. .backgroundColor($r('app.color.index_background'))
  12171. .justifyContent(FlexAlign.SpaceBetween)
  12172. }
  12173. private handleVerifyCompleted(isSuccess: boolean) {
  12174. if (isSuccess) {
  12175. console.log('验证成功');
  12176. // 在这里处理验证成功后的逻辑
  12177. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  12178. this.currentPath = this.lockPath
  12179. this.getSortedFiles(this.currentPath)
  12180. } else {
  12181. // console.log('验证失败');
  12182. ToastUtil.showToast('验证失败')
  12183. }
  12184. }
  12185. private showVerifyDialog() {
  12186. promptAction.openCustomDialog({
  12187. transition: TransitionEffect.asymmetric(
  12188. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  12189. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  12190. ,
  12191. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  12192. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  12193. ),
  12194. builder: () => {
  12195. this.customDialogComponentMM()
  12196. },
  12197. isModal: true,
  12198. autoCancel: true,
  12199. maskColor: Color.Transparent,
  12200. alignment: DialogAlignment.Bottom,
  12201. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  12202. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  12203. console.log("dialog onWillDismiss")
  12204. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  12205. dismissDialogAction.dismiss()
  12206. }
  12207. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  12208. dismissDialogAction.dismiss()
  12209. }
  12210. }
  12211. }).then((dialogId: number) => {
  12212. this.customDialogComponentIdMM = dialogId
  12213. })
  12214. }
  12215. //左滑操作 移动文件 重命名 删除等操作
  12216. @Builder
  12217. DeleteButton(item: VideoItem, index: number, filePath: string) {
  12218. Row() {
  12219. //加入收藏
  12220. Button() {
  12221. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  12222. .fillColor(Color.White)
  12223. .width(20)
  12224. }
  12225. .width(40)
  12226. .height(40)
  12227. .type(ButtonType.Circle)
  12228. .backgroundColor(this.themeColor)
  12229. .margin(5)
  12230. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  12231. .onClick(() => {
  12232. if (item) {
  12233. this.doFav(item)
  12234. }
  12235. })
  12236. //加入下一首播放
  12237. Button() {
  12238. Image($r('app.media.next_to_play'))
  12239. .fillColor(Color.White)
  12240. .width(20)
  12241. }
  12242. .width(40)
  12243. .height(40)
  12244. .type(ButtonType.Circle)
  12245. .backgroundColor(this.themeColor)
  12246. .margin(5)
  12247. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  12248. .onClick(() => {
  12249. this.addToNextPlay(item);
  12250. })
  12251. //复制文件
  12252. Button() {
  12253. Image($r('app.media.copy'))
  12254. .fillColor(Color.White)
  12255. .width(20)
  12256. }
  12257. .width(40)
  12258. .height(40)
  12259. .type(ButtonType.Circle)
  12260. .backgroundColor(this.themeColor)
  12261. .margin(5)
  12262. .id(filePath + 'copy')
  12263. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  12264. .onClick(() => {
  12265. this.showCopyDialog(false, item, index, filePath + 'copy');
  12266. })
  12267. //移动文件
  12268. Button() {
  12269. Image($r('app.media.cut'))
  12270. .fillColor(Color.White)
  12271. .width(20)
  12272. }
  12273. .width(40)
  12274. .height(40)
  12275. .type(ButtonType.Circle)
  12276. .backgroundColor(this.themeColor)
  12277. .margin(5)
  12278. .id(filePath)
  12279. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  12280. .onClick(() => {
  12281. this.showCutDialog(false, item, index, filePath);
  12282. })
  12283. Button() {
  12284. Image($r('app.media.cut_current'))
  12285. .fillColor(Color.White)
  12286. .width(20)
  12287. }
  12288. .width(40)
  12289. .height(40)
  12290. .type(ButtonType.Circle)
  12291. .backgroundColor(this.themeColor)
  12292. .margin(5)
  12293. .id(filePath + 'current')
  12294. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  12295. (this.isHasDir ? Visibility.Visible : Visibility.None))
  12296. .onClick(() => {
  12297. this.showCutDialog(true, item, index, filePath + 'current');
  12298. })
  12299. //重命名
  12300. Button() {
  12301. Image($r('app.media.rename2'))
  12302. .fillColor(Color.White)
  12303. .width(20)
  12304. }
  12305. .width(40)
  12306. .height(40)
  12307. .type(ButtonType.Circle)
  12308. .backgroundColor(this.themeColor)
  12309. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  12310. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  12311. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  12312. .margin(5)
  12313. .onClick(() => {
  12314. this.showReNameDialog(item, index + '', filePath)
  12315. })
  12316. Button() {
  12317. Image($r('app.media.delete2'))
  12318. .fillColor(Color.White)
  12319. .width(20)
  12320. }
  12321. .width(40)
  12322. .height(40)
  12323. .type(ButtonType.Circle)
  12324. .backgroundColor(this.themeColor)
  12325. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  12326. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  12327. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  12328. .margin(5)
  12329. .onClick(() => {
  12330. this.selectedFiles.push(item)
  12331. this.showWarnIsDelete()
  12332. // this.showWarnIsDeleteFile(item, index + '', filePath)
  12333. })
  12334. Button() {
  12335. Image($r('app.media.share2'))
  12336. .fillColor(Color.White)
  12337. .width(20)
  12338. }
  12339. .width(40)
  12340. .height(40)
  12341. .type(ButtonType.Circle)
  12342. .backgroundColor(this.themeColor)
  12343. .margin(5)
  12344. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  12345. .onClick(() => {
  12346. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  12347. })
  12348. }
  12349. }
  12350. /**
  12351. * 穿山甲banner广告
  12352. */
  12353. // private declare bannerAd: CSJNativeExpressAd;
  12354. // @State private status: string = "未加载"
  12355. // @State private isShowAd: boolean = false
  12356. // private declare mAdSlot: AdSlot;
  12357. // private mBiddingAdm = '' //服务端bidding才需要设置
  12358. // private expressLoadAdListener: NativeExpressAdListener = {
  12359. // /**
  12360. // * 加载失败的回调
  12361. // *
  12362. // * @param code
  12363. // * @param message
  12364. // */
  12365. // onError: (code: number, message: string) => {
  12366. // console.error("加载广告失败,code=" + code + ",message=" + message);
  12367. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  12368. // },
  12369. //
  12370. // /**
  12371. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  12372. // *
  12373. // * @param ads 返回的广告列表
  12374. // */
  12375. //
  12376. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  12377. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  12378. // if (ads && ads.length > 0) {
  12379. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  12380. // ad.setExpressInteractionListener({
  12381. // /**
  12382. // *广告的点击回调
  12383. // * @param type 广告的交互类型
  12384. // */
  12385. // onAdClicked: (type: number) => {
  12386. // console.log("BannerExpressAdPage==onAdClicked......");
  12387. // },
  12388. //
  12389. // /**
  12390. // * 广告的展示回调 每个广告仅回调一次
  12391. // * @param type 广告的交互类型
  12392. // */
  12393. // onAdShow: (type: number) => {
  12394. // console.log("BannerExpressAdPage==onAdShow......");
  12395. // },
  12396. //
  12397. // /**
  12398. // * 模板渲染失败
  12399. // */
  12400. // onRenderFail: (code: number, msg: string) => {
  12401. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  12402. // },
  12403. //
  12404. // /**
  12405. // * 模板渲染成功
  12406. // * @param width 返回view的宽 单位 vp
  12407. // * @param height 返回view的高 单位 vp
  12408. // */
  12409. // onRenderSuccess: (width: number, height: number) => {
  12410. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  12411. // this.bannerAd = ad;
  12412. // this.status = "广告加载完成待展示";
  12413. //
  12414. // this.showBannerAd()
  12415. // }
  12416. // })
  12417. // //渲染广告
  12418. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  12419. // this.setDislikeCallback(ad); //设置dislike
  12420. // ad.render(this.getUIContext())
  12421. // this.status = "广告加载中...";
  12422. // });
  12423. // }
  12424. // }
  12425. // }
  12426. //
  12427. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  12428. // ad.setDislikeCallback({
  12429. // /**
  12430. // * dislike show
  12431. // */
  12432. // onShow: () => {
  12433. // console.log("BannerExpressAdPage==dislike......show");
  12434. // },
  12435. //
  12436. // /**
  12437. // * @param position 选择的位置
  12438. // * @param value 选择的内容
  12439. // * @param enforceRemove 是否强制关闭广告
  12440. // */
  12441. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  12442. // this.isShowAd = false;
  12443. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  12444. // ",enforce=" + enforceRemove);
  12445. // },
  12446. //
  12447. // /**
  12448. // * 点击取消
  12449. // */
  12450. // onCancel: () => {
  12451. // console.log("BannerExpressAdPage==dislike......onCancel");
  12452. // }
  12453. //
  12454. // })
  12455. // }
  12456. /**
  12457. * 加载Banner广告
  12458. */
  12459. loadBannerAd(rit: string) {
  12460. // if (Utility.isNoble()) {
  12461. // return
  12462. // }
  12463. // if (!Utility.isPassInstallTime(2)) {
  12464. // return
  12465. // }
  12466. // this.isShowAd = false;
  12467. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  12468. // this.mAdSlot = new AdSlotBuilder()
  12469. // .setCodeId(rit)
  12470. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  12471. // .setAdCount(1)
  12472. // .setBidAdm(this.mBiddingAdm)
  12473. // .build()
  12474. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  12475. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  12476. // this.status = "广告加载中..."
  12477. }
  12478. /**
  12479. * 展示Banner广告
  12480. */
  12481. // showBannerAd() {
  12482. // if (!this.bannerAd) {
  12483. // return
  12484. // }
  12485. // this.isShowAd = true
  12486. // this.status = "已展示"
  12487. // }
  12488. /**
  12489. * 穿山甲广告代码结束
  12490. */
  12491. /**
  12492. * 处理歌单播放请求
  12493. */
  12494. private async handlePlaylistPlayRequest(playlistId: string, playlistName:
  12495. string, songFilePaths: string[], startIndex: number) {
  12496. try {
  12497. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 歌曲数量: ${songFilePaths.length}, 开始索引: ${startIndex}`)
  12498. // 检查是否为WebDAV播放请求
  12499. if (playlistId === 'webdav-playlist') {
  12500. Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
  12501. // 从全局内存读取videoItems数据
  12502. const videoItems = getWebdavVideoItems();
  12503. const currentPlayIndex = getWebdavCurrentPlayIndex();
  12504. Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
  12505. if (videoItems && videoItems.length > 0) {
  12506. // 验证webdav_account_id设置情况
  12507. const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
  12508. Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
  12509. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName)
  12510. return
  12511. } else {
  12512. return
  12513. }
  12514. }
  12515. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  12516. const songMap: Map<number, VideoItem> = new Map()
  12517. let completedQueries = 0
  12518. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  12519. // 遍历所有文件路径,使用索引记录位置
  12520. for (let i = 0; i < songFilePaths.length; i++) {
  12521. const filePath = songFilePaths[i]
  12522. const index = i
  12523. // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  12524. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  12525. const queryPromise = this.table.queryVideoByFilePath(filePath)
  12526. // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  12527. queryPromise.then((videoItem) => {
  12528. completedQueries++
  12529. // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  12530. if (videoItem) {
  12531. // 使用索引作为key保存到Map中,保持原始顺序
  12532. songMap.set(index, videoItem)
  12533. // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  12534. } else {
  12535. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  12536. }
  12537. // 检查是否所有歌曲都已加载完成
  12538. if (completedQueries === songFilePaths.length) {
  12539. // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  12540. // 按照索引顺序重建歌曲数组
  12541. const songs: VideoItem[] = []
  12542. for (let j = 0; j < songFilePaths.length; j++) {
  12543. const song = songMap.get(j)
  12544. if (song) {
  12545. songs.push(song)
  12546. // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  12547. }
  12548. }
  12549. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  12550. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  12551. }
  12552. }).catch((error: Error) => {
  12553. completedQueries++
  12554. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  12555. // 即使出错也要检查是否完成所有查询
  12556. if (completedQueries === songFilePaths.length) {
  12557. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  12558. // 按照索引顺序重建歌曲数组
  12559. const songs: VideoItem[] = []
  12560. for (let j = 0; j < songFilePaths.length; j++) {
  12561. const song = songMap.get(j)
  12562. if (song) {
  12563. songs.push(song)
  12564. }
  12565. }
  12566. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  12567. }
  12568. })
  12569. }
  12570. } catch (error) {
  12571. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  12572. ToastUtil.showToast('播放失败')
  12573. }
  12574. }
  12575. /**
  12576. * 完成歌单加载并开始播放
  12577. */
  12578. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string) {
  12579. if (songs.length === 0) {
  12580. Logger.error('heanup 没有找到任何可播放的歌曲')
  12581. ToastUtil.showToast('没有找到可播放的歌曲')
  12582. return
  12583. }
  12584. this.songList = songs
  12585. this.sonDataSource.pushArrayData(songs)
  12586. this.sonDataSource.notifyDataReload()
  12587. this.curIndex = startIndex
  12588. if (songs[startIndex]) {
  12589. // 确保当前播放的歌曲也更新到存储
  12590. AppStorage.setOrCreate('currentSong', songs[startIndex])
  12591. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  12592. this.doPlay(songs[startIndex], startIndex, true)
  12593. }
  12594. PreferencesUtil.putSync('LastMusicList', this.songList)
  12595. ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  12596. }
  12597. }
  12598. //视频气泡窗口的布局
  12599. @Builder
  12600. function customPopupBuilder(dataBu: BubbleBean) {
  12601. List() {
  12602. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  12603. ListItem() {
  12604. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  12605. Row() {
  12606. Column() {
  12607. Image(dataBu.imageRes[index])
  12608. .height(28)
  12609. .fillColor(dataBu.color)
  12610. .alignSelf(ItemAlign.Center)
  12611. }
  12612. .width(32)
  12613. Text(item)
  12614. .padding({
  12615. top: 10,
  12616. bottom: 10,
  12617. right: 10,
  12618. left: 10
  12619. })
  12620. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  12621. .textAlign(TextAlign.Start)
  12622. .width("100%")
  12623. }
  12624. }
  12625. .backgroundColor($r('app.color.settings_background_main'))
  12626. .margin({ top: 6, bottom: 6 })
  12627. }
  12628. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  12629. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  12630. TransitionEffect.scale({ x: 0, y: 0 })))
  12631. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  12632. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  12633. .onClick(() => {
  12634. dataBu.onItemClick?.(index)
  12635. })
  12636. })
  12637. }
  12638. .scrollBar(BarState.Off)
  12639. .width(120)
  12640. .divider({
  12641. strokeWidth: 1,
  12642. color: "#22FFFFFF"
  12643. })
  12644. }
  12645. // Function to calculate a hash for the file list
  12646. function simpleHash(fileList: string[]): string {
  12647. let hash = 0;
  12648. const str = fileList.join(',');
  12649. for (let i = 0; i < str.length; i++) {
  12650. const char = str.charCodeAt(i);
  12651. hash = (hash << 5) - hash + char;
  12652. hash |= 0; // Convert to 32bit integer
  12653. }
  12654. return hash.toString();
  12655. }
  12656. interface MoreItem {
  12657. id: number;
  12658. image: Resource;
  12659. title: string;
  12660. }
  12661. //视频气泡窗口的布局
  12662. @Builder
  12663. function cutPopupBuilder(dataBu: BubbleBean) {
  12664. Column() {
  12665. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  12666. .padding({
  12667. top: 10,
  12668. bottom: 10,
  12669. right: 10,
  12670. left: 10
  12671. })
  12672. .textAlign(TextAlign.Start)
  12673. .width(160)
  12674. .fontWeight(666)
  12675. .fontSize(16)
  12676. List() {
  12677. ForEach(dataBu.data, (item: string, index: number) => {
  12678. ListItem() {
  12679. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  12680. Row() {
  12681. Column() {
  12682. Image($r('app.media.music_group'))
  12683. .height(28)
  12684. .fillColor(dataBu.color)
  12685. .alignSelf(ItemAlign.Center)
  12686. }
  12687. .width(32)
  12688. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  12689. .padding({
  12690. top: 10,
  12691. bottom: 10,
  12692. right: 10,
  12693. left: 10
  12694. })
  12695. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  12696. .fontSize(15)
  12697. }
  12698. }
  12699. .backgroundColor(Color.Transparent)
  12700. .margin({ top: 7, bottom: 7 })
  12701. }
  12702. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  12703. .animation({ duration: 500 }),
  12704. TransitionEffect.scale({ x: 0, y: 0 })))
  12705. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  12706. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  12707. .onClick(() => {
  12708. dataBu.onItemClick?.(index)
  12709. })
  12710. })
  12711. }
  12712. .scrollBar(BarState.Off)
  12713. .width(150)
  12714. .divider({
  12715. strokeWidth: 1,
  12716. color: "#22FFFFFF"
  12717. })
  12718. }
  12719. .height(300)
  12720. .padding({
  12721. bottom: 30
  12722. })
  12723. }
  12724. function getFileDirName(filePath: string,rootPath:string): string{
  12725. if(filePath===rootPath){
  12726. return '首页'
  12727. }
  12728. let result = FileUtil.getFileName(filePath)
  12729. if(StrUtil.isEmpty(result))
  12730. return ''
  12731. if(result.startsWith('.'))
  12732. result = result.replace(/\./g, '')
  12733. return result
  12734. }
  12735. //只扫描当前目录下文件(不扫描子文件夹)的方法
  12736. @Concurrent
  12737. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  12738. const table: MediaTable = new MediaTable(context);
  12739. try {
  12740. // 直接获取当前目录下的文件列表
  12741. const files = FileUtil.listFileSync(dirPath);
  12742. await Promise.all(files.map(async (file) => {
  12743. const fPath = `${dirPath}/${file}`;
  12744. // 跳过目录,只处理文件
  12745. if (FileUtil.isDirectory(fPath)) {
  12746. return;
  12747. }
  12748. // 跳过特定格式文件
  12749. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  12750. return;
  12751. }
  12752. // 检查是否为媒体文件
  12753. if (Utility.isMeidaByExtension(fPath)) {
  12754. let mType = CommonConstants.TYPE_LOCAL;
  12755. if (fPath.includes(lockPath)) {
  12756. mType = CommonConstants.TYPE_LOCK;
  12757. }
  12758. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  12759. context, fPath, mType, true
  12760. );
  12761. table.insert(mediaItem, (id: number) => {
  12762. // 插入回调函数
  12763. }, cover_api);
  12764. }
  12765. }));
  12766. } catch (error) {
  12767. console.error(' 扫描当前目录失败:', error);
  12768. }
  12769. }